views:

39

answers:

4

I'm very new to PHP, SQL I've worked with using Coldfusion but only with very simple queries. In coldfusion to access a specific database

<cfquery dbname="blah">

I know in PHP I have to use mysql_query() and mysql_connect(), and here is the code I have, so I understand how to access a server and a table, but not the database. How can this be done?

<?php
$sql_branch = "SELECT BranchNum
              FROM Branch WHERE
              branchName = '$_POST[branch]'";
$connect = mysql_connect('students','xxxxxxx','xxxxxxx');
if(mysql_query($sql_branch, $connect)) {
  $branch = mysql_query($sql_branch, $connect);
}
else {
  echo "error".mysql_error();
}
$sql_result = "USE henrybooks;
              SELECT AuthorFirst, AuthorLast, OnHand, Title
              FROM Inventory i, Wrote w, Author a, Book b
              WHERE i.BookCode = b.BookCode AND
              i.BookCode = w.BookCode AND a.AuthorNum =
              w.AuthorNum AND i.BranchNum = $branch";
if(mysql_query($sql_result, $connect)) {
  $result = mysql_query($sql_result, $connect);
}
else {
  echo "Error".mysql_error();
}

Also I'm unsure if my Error checking is right, my professor did not really explain how that works exactly.

Thanks!

+3  A: 

Find out the database name and select it before making any queries:

$connect = mysql_connect('students','xxxxxxx','xxxxxxx');
mysql_select_db('dbName', $connect);

Documentation for mysql_select_db.

Saul
do I need to store the results of the mysql_select_db() function anywhere? or will PHP handle all of this automatically for me?
rajh2504
You could start another question for this, but the short answer is no, unless you plan to be using multiple mysql connections.
Extrakun
@Greg: Only if you want to be sure that the database you attempted to select really exists. mysql_select_db returns false on failure and you can define further actions to recover from such errors but it's not mandatory.
Saul
@Greg Laubenstein You only do it once. Only recall it if you want to switch database (that use the same user as specified in the mysql_connect call).
AlexV
A: 

Use mysql_select_db to connect to the database. Most of the mysql_ functions should be what you are looking for when working with mysql databases.

Extrakun
A: 

You probably want to use mysql_select_db:

$connect = mysql_connect('students','xxxxxxx','xxxxxxx');
mysql_select_db( "blah", $connect );
Christopher W. Allen-Poole
A: 

Are you looking for mysql_select_db?

You can find all mysql functions here.

AlexV