I want to fetch data from a mysql table using php. Please, can anyone tell me what is wrong with this code? What is the correct code to fetch data from a mysql database:
Change the "WHILE" to "while". Because php is case sensitive like c/c++.
use this code
while ($rows = mysql_fetch_array($query)):
$name = $rows['Name'];
$address = $rows['Address'];
$email = $rows['Email'];
$subject = $rows['Subject'];
$comment = $rows['Comment'];
echo "$name<br>$address<br>$email<br>$subject<br>$comment<br><br>";
endwhile;
?>
Try this
<?php
// 1. Enter Database details
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'password';
$dbname = 'database name';
// 2. Create a database connection
$connection = mysql_connect($dbhost,$dbuser,$dbpass);
if (!$connection) {
die("Database connection failed: " . mysql_error());
}
// 3. Select a database to use
$db_select = mysql_select_db($dbname,$connection);
if (!$db_select) {
die("Database selection failed: " . mysql_error());
}
$query = mysql_query("SELECT * FROM users WHERE name = 'Admin' ");
while ($rows = mysql_fetch_array($query)) {
$name = $rows['Name'];
$address = $rows['Address'];
$email = $rows['Email'];
$subject = $rows['Subject'];
$comment = $rows['Comment']
echo "$name<br>$address<br>$email<br>$subject<br>$comment<br><br>";
}
?>
Not tested!! *UPDATED!!
If this is the code you have, then you will get an error because, you are reassigning $row while in the loop, so you would never be able to iterate over the results. Replace
$rows = $rows['Name'];
with
$name = $rows['Name']'
So your code would look like
WHILE ($rows = mysql_fetch_array($query)):
$name = $rows['Name'];
$address = $rows['Address'];
$email = $rows['Email'];
$subject = $rows['Subject'];
$comment = $rows['Comment'];
Also I am assuming that the column names in the table users are Name, Address, Email etc. and not name,address, email. Remember that every variable name/field nameh is case sensitive.