Reputation: 1149
here is code i am trying to display all data from database...
$sql = mysql_query("SELECT * FROM data ORDER BY id DESC");
$row1 = mysql_fetch_array($sql);
print_R($row1);
but it is displaying only one row.. I have totally three rows in database , if i run the same query in database, it displays all rows.. i want to display all three rows how to fix this?
Upvotes: 0
Views: 1864
Reputation: 1875
its simple to use mysqli just try the following once
$mysqli = new mysqli("localhost", "username", "password", "database");
$strr = "SELECT * FROM data ORDER BY id DESC"; // its a good practice to use column name insted of *
$result = $mysqli->query($strr);
while($arr = $result->fetch_array())
{
print_r($arr);
}
Upvotes: 0
Reputation: 146
u need to loop ur query,
$sql = mysql_query("SELECT * FROM data ORDER BY id DESC");
$row1 = mysql_fetch_array($sql);
print_R($row1);
// wrong one
use mysqli,
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Perform query
$sql = mysqli_query($con,"SELECT * FROM data ORDER BY id DESC");
$mainarr=array();
while($row = mysql_fetch_assoc($sql)) {
$subarr=array();
$subarr['key']=$row['your field'];
array_push($mainarr,$subarr);
}
print_r($mainarr);
Upvotes: 0
Reputation: 41885
Since you're expecting multiple rows you need to loop them using while:
$sql = mysql_query("SELECT * FROM data ORDER BY id DESC");
while($row1 = mysql_fetch_assoc($sql)) {
echo $row1['column_name'];
}
Obligatory Note:
Please, don't use
mysql_*
functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
Here is a simple example coming from PDO's counterpart:
$con = new PDO('mysql:host=localhost;dbname=database_name', 'username', 'password'); // simple connection
$query = $con->query('SELECT * FROM data ORDER BY id DESC'); // put your query here
while($row = $query->fetch(PDO::FETCH_ASSOC)) { // same concept, you need to fetch them and put them inside the while loop since you're expecting multiple rows
echo $row['column_name'];
}
Basically the first answer will work but I urge you to ditch that deprecated API and start using PDO. Don't worry, you won't have shortage of sources in learning this API.
Upvotes: 6
Reputation: 23816
Try while loop
$sql = mysql_query("SELECT * FROM data ORDER BY id DESC");
while($row = mysql_fetch_array($sql))
{
print_r($row);
}
Upvotes: 0