Porkie Posted March 30, 2009 Share Posted March 30, 2009 i have only just started php and become unstuck with 2 problems. firstly, how do i display data from a database , such as 1 record from a database? Secondly, wot is the code to show how many records there are in a database? regards george Quote Link to comment https://forums.phpfreaks.com/topic/151840-noob-to-php/ Share on other sites More sharing options...
MadTechie Posted March 30, 2009 Share Posted March 30, 2009 Here a nice example for you to play with (i included the link to php.net mysql_fetch_assoc) i hope it helps <?php $conn = mysql_connect("localhost", "mysql_user", "mysql_password"); if (!$conn) { echo "Unable to connect to DB: " . mysql_error(); exit; } if (!mysql_select_db("mydbname")) { echo "Unable to select mydbname: " . mysql_error(); exit; } $sql = "SELECT id as userid, fullname, userstatus FROM sometable WHERE userstatus = 1"; $result = mysql_query($sql); if (!$result) { echo "Could not successfully run query ($sql) from DB: " . mysql_error(); exit; } //THIS GET THE RECORDS FOUND if (mysql_num_rows($result) == 0) { echo "No rows found, nothing to print so am exiting"; exit; } // While a row of data exists, put that row in $row as an associative array // Note: If you're expecting just one row, no need to use a loop // Note: If you put extract($row); inside the following loop, you'll // then create $userid, $fullname, and $userstatus while ($row = mysql_fetch_assoc($result)) { echo $row["userid"]; echo $row["fullname"]; echo $row["userstatus"]; } mysql_free_result($result); ?> Quote Link to comment https://forums.phpfreaks.com/topic/151840-noob-to-php/#findComment-797332 Share on other sites More sharing options...
Maq Posted March 30, 2009 Share Posted March 30, 2009 To find out how many records are in your table, you can use the aggregate COUNT() function: $sql = "SELECT COUNT(*) AS num FROM table"; $result = mysql_query($sql) or die(mysql_error()); $row = mysql_fetch_assoc($result); echo "There are " . $row['num'] . " records in your table"; Quote Link to comment https://forums.phpfreaks.com/topic/151840-noob-to-php/#findComment-797341 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.