Retrieving MySQL values and printing them - php

The problem is, that when run, the script returns only the first row's user_email value.
I want the script to compile a list, but this is not happening.
//Retreive database entries for emails
$fetch = mysql_query("SELECT user_email FROM users");
$rows = mysql_fetch_array($fetch);
//Store input in local variables
echo "<ul>";
while ($rows) {
echo "<li>".$rows['user_email']."</li>";
}
echo "</ul>";

You should place your mysql_fetch_array as the while-condition, not outside.
while ($rows = mysql_fetch_array($fetch)) {
echo "<li>".$rows['user_email']."</li>";
}
This will loop through all results from the database, rather than just repeating the first (as it's always returning true, but only for the first row).
Also, you should seriously consider converting to mysqli_* with prepared statements or PDO to prevent SQL-injection.

//Retreive database entries for emails
$fetch = mysql_query("SELECT user_email FROM users");
//Store input in local variables
echo "<ul>";
while ($rows = mysql_fetch_array($fetch) ) {
echo "<li>".$rows['user_email']."</li>";
}
echo "</ul>";

Related

How to start a while loop at row 1 after already done a php fetch

I want to fetch data from the database and use the first row initially. Then later if some values are true I want to loop through all of the rows.
The problem is that the while loop starts at the second row.
Is there a way to make the loop start at the first row?
Below is simplified example:
<?php
//GET THE CONNECTION DATA FOR $CONNECTION
require_once('../connect.php');
$get_data = $connection->prepare('SELECT * FROM db WHERE email = :email');
$get_data -> execute(['email' => 'john#doe.com']);
$data = $get_data->fetch();
echo $data->email;
echo '<br>';
while($data = $get_data->fetch())
{
//STARTS AT THE SECOND ROW BUT NEEDS TO BE THE FIRST ROW
echo $data->last_name;
echo '<br>';
}
Yes you can use fetchAll()
$results = $get_data->fetchAll ();
$data = $results[0];
echo $data->email;
echo '<br>';
foreach($results as $data) {
//...
}
If you need something like this, you are doing something wrong.
For the question stated in the title, Dharman's answer is correct and should be accepted for sake of future visitors.
However, in your particular case, you don't need the first fetch and most likely don't need a while loop.
The first fetch is not needed because it is used to output the data you already have (the email used to query the database).
The while loop is not needed because most likely there is only one record in the database with such email, so you can just echo the username right away.
Either way, a sane version of your code would be either
$get_data = $connection->prepare('SELECT * FROM db WHERE email = :email');
$get_data -> execute(['email' => 'john#doe.com']);
$data = $get_data->fetch();
echo $data->email;
echo '<br>';
echo $data->last_name;
echo '<br>';
or (in case your query indeed returns multiple rows)
$email = 'john#doe.com';
$get_data = $connection->prepare('SELECT * FROM db WHERE email = :email');
$get_data -> execute(['email' => $email]);
echo $email;
echo '<br>';
while($data = $get_data->fetch())
{
echo $data->last_name;
echo '<br>';
}
See - you never need to "restart" the while loop.

PHP: Don't echo a variable in a while loop IF it's a duplicate

I have a variable in an SQL query-based while loop. e.g:
$sql = mysql_query("SELECT * FROM table");
while($row=mysql_fetch_array($sql)){
echo $row['row'];
}
The while loop is functional and works, however the variable contains duplicate strings.
How do I prevent duplicate row variables echoing in my while loop with PHP?
Note: This is a PHP question, not an SQL question.
Just keep track of each row's unique ID. If you see again, skip it.
$sql = mysql_query("SELECT * FROM table");
$ids = array();
while($row=mysql_fetch_array($sql)){
if (!isset($ids[$row['id']])) {
continue;
}
$ids[] = $row['id'];
echo $row['row'];
}
FYI, this is a lot easier and faster if you do it in SQL. But if you must do it in PHP this is how you would do it.

Getting specified rows from an array

Am making a really simple php page which pulls data from a really simple database and displays it as charts for a wall monitor.
I've got the data from the db, no problem, but I seem to be struggling splitting that data up
For now i'm just echoing the data to make sure i have what i need.
My code looks like this:
<?php
mysql_connect("host", "user", 'password' or die(mysql_error());
mysql_select_db("databax") or die(mysql_error());
$dbdata = mysql_query("SELECT * FROM dbcpman_resources")
or die(mysql_error());
$column = mysql_fetch_array( $dbdata );
echo $column[0]."<br>";
echo $column[1]."<br>";
echo $column[2]."<br>";
echo $column[3]."<br>";
echo $column[4]."<br>";
echo $column[5]."<br>";
?>
Indeed, it works - it will echo data from the database, but as i've not specified the row anywhere, its just giving me the first row.
I need to be able to work with each row seperately.
There will only ever be 6 rows in this table.
So can anyone help me out with how I go about replicating this for rows 2,3,4,5 and 6?
Thanks in advance!! :)
You need to loop over the result set. The easiest way is to use a while loop as this automatically terminates at the end of the result set, like this.
while ( $row = mysql_fetch_array( $dbdata );
echo $row [0]."<br>";
echo $row [1]."<br>";
echo $row [2]."<br>";
echo $row [3]."<br>";
echo $row [4]."<br>";
echo $row [5]."<br>";
}
Also if you were to change the function that returns the resuilts to use mysql_fetch_assoc() you can reference each field with the name it has on the database so the code is easier to read, like this:
I dont know your field names so I made some up.
while ( $row = mysql_fetch_array( $dbdata );
echo $row ['name']."<br>";
echo $row ['date']."<br>";
echo $row ['time']."<br>";
echo $row ['value1']."<br>";
echo $row ['value2']."<br>";
echo $row ['value3']."<br>";
}
First of all, I'd rather use mysql_fetch_assoc() instead of mysql_fetch_array() since it doesn't srew up your result, if the table structure changes.
It would be even better if you used either mysqli or PDO instead of mysql_* functions, since they are marked deprecated already!
Second please note, that either function just fetches ONE record from your resultset at a time. To fetch all records try the following:
$records = array();
while($row = mysql_fetch_assoc($dbdata)) {
$records[] = $row;
}
You can do a print_r($records); to see what's inside $records after fetching all.
put this line $column = mysql_fetch_array( $dbdata ); in while loop like this
while($column = mysql_fetch_array( $dbdata ))
{
echo $column[0]."<br>";
echo $column[1]."<br>";
echo $column[2]."<br>";
echo $column[3]."<br>";
echo $column[4]."<br>";
echo $column[5]."<br>";
}

mysql query is not fetching all the elements from the table

it's just fetching the first element from the table.
Table name is categories which contains 2 columns : id, category
I cant understand why is it fetching just first row from the table.
<?php
$sql = "SELECT category FROM categories";
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
//print_r($row);
?>
You need to iterate through the result set in order to retrieve all the rows.
while($row = mysql_fetch_assoc($result)) {
print($row);
}
Also, stop using mysql_ functions. 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.
Use this in while loop :
while ($row = mysql_fetch_assoc($result)) {
print_r($row);
}
Just like you wrote mysql_fetch_assoc($result); will get only one row. You have to use loop to get it all.
If you call mysql_fetch_assoc just once, you'll get only the first row...
while(false !== $row = mysql_fetch_assoc($result)) {
print_r($row)
}
The function you are using only does one record.
Try. ..while($row = mysqli_fetch_array($result))
{
echo $row['id'] . " " . $row['category'];
echo "";
}
For retrieve result set Use loop as per your need
foreach
Use when iterating through an array whose length is (or can be) unknown.
as
foreach($row as $val)
{
echo $val;
}
for
Use when iterating through an array whose length is set, or, when you need a counter.
for(i=0;i<sizeof($row);i++)
{
echo $row[$i];
}
while
Use when you're iterating through an array with the express purpose of finding, or triggering a certain flag.
while($row=mysqli_fetch_array($query))
{
echo $row['flag'];
}

A better way to generate this json array from MySql data with php

Sql fiddle for your convenience here.
I'm taking data from a MySql table and turning it into a json array. All works well and I have the output the way I want it, but is there a way this can be improved (shortened/improved)? The array keys have to remain the same and need to match the dbs output.
My Code
$stmt = $conn->prepare("select name as name, age as age, address as address, pincode as pincode from json where name = 'peter'");
$stmt->execute();
while( $row = $stmt->fetch() ) {
#echo $row['name']." ".$row['age']." ".$row['address']." ".$row['pincode'].'<br>';
$myarray['name'] = $row['name'];
$myarray['age'] = $row['age'];
$myarray['address'] = $row['address'];
$myarray['pincode'] = $row['pincode'];
}
echo json_encode($myarray);
My Output (the above code successfully outputs this)
{"name":"Peter","age":"30","address":"1 Elm Street","pincode":"91550"}
Taking out all the redundancy, using proper prepared statements (assuming PDO) and adding error handling (at least a stub), you end up with this:
$stmt = $conn->prepare('SELECT name, age, address, pincode FROM json WHERE name = ?');
$stmt->execute(array('peter'));
if ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo json_encode($row);
} else {
echo json_encode(array('status' => 'error'));
}
If you expect multiple rows:
echo json_encode($stmt->fetchAll(PDO::FETCH_ASSOC));
You only select needed fields, so you can just do
echo json_encode($stmt->fetch(PDO::FETCH_ASSOC));
EDIT: You mention now that name is unique, so above is all you need.
$row = $stmt->fetch(PDO::FETCH_ASSOC);
echo json_encode($row);
You don't need the while loop, if you only have one row in your result.

Categories