Part I. Connect to the Database and the table
The code below connects to our database and SELECTS every row and column in it!.
If you run the query below, all that you will get is a ResourceId..not very interesting it seems, but we will see that that holds all of the data that we want.
<?php
$connection = mysql_connect("localhost","root","");
$connectToDB = mysql_select_db('firstDB', $connection) or die(mysql_error());
$selectTable = "SELECT * FROM apcs";
$res = mysql_query($selectTable ) or die(mysql_error());
echo "<br /> Results of select : " . $res ;
?>
Selecting all the rows and priting all of the data!
Now, the heavy lifting for small bit of code is the while() loop that prints out all of the data. You should be able to figure out how the loop works based on the names.
<?php
$connection = mysql_connect("localhost","root","");
$connectToDB = mysql_select_db('firstDB', $connection) or die(mysql_error());
$selectTable = "SELECT * FROM apcs";
$selectEntireTable= mysql_query($selectTable ) or die(mysql_error());
while($rowFromTable = mysql_fetch_array($selectEntireTable) )
{
echo $rowFromTable['firstName'] . ' '. $rowFromTable['lastName'] . ": age =" . $rowFromTable['age'] .
', grade = ' .$rowFromTable['gradeLevel'] . ', unique id = ' . $rowFromTable['id'] .
'<br />';
}
?>
mysql_num_rows()
(A very, very useful function)
Usually you want to determine whether or not a row already exists in a table BEFORE you do anything else like adding a row. To determine if a row already exists try to "SELECT" data from the row and then see how many rows were affeced with mysql_num_rows() . Note this method is used for SELECT statements. A similar function, mysql_affected_rows() , perfoms the same role for INSERT, UPDATE, and DELETE statments.
<?php
$connection = mysql_connect("localhost","root","");
$resultsOfConnect = mysql_select_db('database1', $connection);
$checkIfStudentALreadyIn= "SELECT firstName,lastName FROM apcs WHERE firstName='Andrew' ";
$queryResults = mysql_query($checkIfStudentALreadyIn) or die(mysql_error()) ;
echo "<br /><br />Number of affected Rows " . mysql_num_rows();
echo '<br /><br />results of find andrew ' .$queryResults ;
?>