when a foreach is followed by a mysqli_fetch_row displaying the same query results, the mysqli_fetch_row() doesn't display. However if the mysqli_fetch_row is executed before the foreach() both are displayed. Why is this?
QUERY:
<?php
$connection = mysqli_connect("localhost", "root", "", "login_app");
$query = "SELECT *
FROM users";
$result = mysqli_query($connection, $query);
if(!$result){
die("db connection failed " . mysqli_error());
}
?>
ONLY DISPLAYS THE RESULTS OF FOREACH:
<?php
foreach($result as $results){
echo "User ID: " . $results['userID'] . "<br>";
echo "Username: " . $results['userName'] . "<br>";
echo "Password: " . $results['password'] . "<br>";
};
$row = mysqli_fetch_row($result);
print_r($row);
?>
DISPLAYS RESULTS OF BOTH FOREACH AND MYSQLI_FETCH_ROW:
<?php
$row = mysqli_fetch_row($result);
print_r($row);
foreach($result as $results){
echo "User ID: " . $results['userID'] . "<br>";
echo "Username: " . $results['userName'] . "<br>";
echo "Password: " . $results['password'] . "<br>";
};
?>
Executing a SELECT query with mysqli_query returns an mysqli_result object. That object implements Traversable, which is why you're able to use a foreach loop to display the results.
foreach($result as $results){ ...
is basically a handier way of doing
while ($results = mysqli_fetch_row($result)) { ...
(See Example #3 here.)
Either way you do it, you're fetching all the results, and when you get to the end of the result set $results will hold the last value fetched (null).
From the manual:
Fetches one row of data from the result set and returns it as an enumerated array, where each column is stored in an array offset starting from 0 (zero). Each subsequent call to this function will return the next row within the result set, or NULL if there are no more rows.
By iterating the result set with your foreach loop, you are effectively exhausting all of the row which is why no data is available on any subsequent row fetches after the loop.
Related
I am updating all my code to Mysqli, before I did I had this code and it worked:
while($row = mysql_fetch_assoc($WildHorses)){
$InWild[] = $row['id'];
}
$RandomWild = array_rand($InWild);
$RandomHorse = $InWild[$RandomWild];
This is my SELECT statement:
$sql = "SELECT Horse.id, Horse.Name, Horse.Age, Horse.Image_name, Horse.Owner, Horse.Barn, Images.Image_path, Images.Image_name FROM Horse, Images WHERE Horse.Owner = '$colname_WildHorseList' AND Images.Image_name = Horse.Image_name";
$result = mysqli_query($con,$sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "id: " . $row["id"]. " Name: " . $row["Name"]. " ImageName: " . $row["Image_name"]. "<br>";
}
} else {
echo "0 results";
}
The SELECT statement ends up echoing all of the correct information, but I want to make an array of only the Id's so that I can pick one at random each time a button is clicked.
I have tried multiple different copies and pastes of code to try and get what I want, but nothing seems to come out right.
Can someone point me in the right direction or explain what I'm doing wrong?
In your while loop you can simply do this :-
$i=0;
$animals=array();
$animals[$i]=$row["id"]; //puts id in array
And then you can create a random number by "rand()" between the length of 0-$i
and can get the job done.
I have a row named trailers in a MySQL database and I am querying that table using PHP and storing the result of that query in a variable. After that ,I am using a foreach loop to parse through each value of the variable i.e. each and every trailer value in the table.
But the problem is, when I try to echo the values of the variable only the first value of the variable is getting echoed in place of all other value. This is the query.
$query1 = "SELECT title,img,ratings,star_cast,director,trailer,imdb_ratings,lifetime_collecton,whats_good,whats_bad,watch_or_not
FROM recent_movies";
$result1 = mysqli_query($connect, $query1);
This is the code of the for each loop
<?php
foreach($result1 as $r):
echo $r['trailer'];
endforeach;
?>
Ten same values are getting printed instead of 10 different values.
Use the mysqli_fetch_array function to retrieve rows from a mysqli resultset.
Reference: http://php.net/manual/en/mysqli-result.fetch-array.php
$result1 = mysqli_query($connect, $query1);
while( $row = mysqli_fetch_array($result1,MYSQLI_ASSOC) ) {
echo "<br> " . $row['title'] . " " . $row['ratings'] ;
}
The following mysql query is getting the last 4 records from the 'residential' table but I'm trying to assign a php variable ($postcode) to each row (the 3rd [3] column in particular) for use in on another page. The following doesn't seem to be split the rows out correctly to assign to each variable?
<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM residential ORDER BY My_id DESC LIMIT 4");
$postcodes = array();
while ($row = mysqli_fetch_array($result))
{
$postcodes[] = $row[3];
}
echo "location one " . $postcodes[0];
echo "<br>";
echo "location two " . $postcodes[1];
echo "<br>";
echo "location three " . $postcodes[2];
mysqli_close($con);
?>
fetch calls fetch a single ROW of data. You're just assigning column #3 of each row, over and over again.
You probably want:
$postcodes = array();
while ($row = ...) {
$postcodes[] = $row[3];
}
var_dump($postcodes);
I have the code bellow, it's ok but I want to be able to use for example the 4th value extracted from the database, use it alone, not put all of them in a list, I want to be able to use the values from database individually. How do I echo them?
Edit: I was thinking to simplify things, to be able to add the values from database into one array and then extract the value I need from the array (for example the 4th - ordered by "order_id"). But how?
Right now I can only create a list with all the values one after the other..
(Sorry, I am new to this). Thank you for all your help..
<?php
include '../../h.inc.php';
$con = mysql_connect($db['host'],$db['user'],$db['passwd']);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("database", $con);
$result = mysql_query("SELECT * FROM options WHERE Name LIKE 'x_swift%' ORDER BY order_id");
echo "<table border='1'>
<tr>
<th>Values</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
// echo "<td>" . $row['Name'] . "</td>";
echo "<td>" . $row['VALUE'] . "</td>";
echo "</tr>";
$array = array(mysql_fetch_array($strict));
}
echo "</table>";
mysql_close($con);
?>
To select the value in the value column of the row where order_id is 4, use this SQL:
$query = 'select value from options where order_id = 4';
Then you can access this result in many ways. One is to get the entire result row (which in this case is just one cell) as an associative array:
if ($result = mysql_query($query)) {
$row = mysql_fetch_assoc($result);
echo 'value = ' . $row['value'];
}
You can also get the value directly:
if ($result = mysql_query($query)) {
echo 'value = ' . mysql_result($result, 'value');
}
It would just be a query like...
$result = mysql_query("SELECT * FROM options WHERE ID = 3");
mysql_fetch_row($result);
Unless Im misunderstanding you....let me know
But you really should use PDO, instead of deprecated mysql_* functions
http://php.net/manual/en/book.pdo.php
This is the part of the PHP code I am having the issue:
$query = "SELECT * FROM clients where idcard = '$idcard'";
$result = mysqli_query($dbc, $query)
or die("Error quering database.");
if(mysqli_fetch_array($result) == False) echo "Sorry, no clients found";
while($row = mysqli_fetch_array($result)) {
$list = $row['first_name'] . " " . $row['last_name'] . " " . $row['address'] . " " . $row['town'] . " " . $row['telephone'] . " " . $row['mobile'];
echo "<br />";
echo $list;
}
Even if I insert an existing idcard value I get no output when there is the if statement, an incorrect idcard displays "Sorry, no clients found" fine. However if I remove the if statement if I enter an existing idcard the data displays ok.
Can you let me know what is wrong with the code please ?
Thanks
Use mysqli_num_rows to count the results:
if(mysqli_num_rows($result) == 0) echo "Sorry, no clients found";
mysqli_fetch_array() fetches an item from the database.
This means your if() code fetches a first item from the database.
Then, when you call mysqli_fetch_array() again from the while() condition, the first item has already been fetched, and you are trying to fetch the second one ; which does not exist.
You must ensure that you use the result from mysqli_fetch_array() and not call it one time just for nothing ; or, as an alternative, you could use the mysqli_num_rows() function (quoting) :
Returns the number of rows in the result set.
$query = "SELECT * FROM clients where idcard = '$idcard'";
$result = mysqli_query($dbc, $query)
or die("Error quering database.");
if(mysqli_num_rows($result) == 0) {
echo "Sorry, no clients found";
}else{
while($row = mysqli_fetch_array($result)) {
$list = $row['first_name'] . " " . $row['last_name'] . " " . $row['address'] . " " . $row['town'] . " " . $row['telephone'] . " " . $row['mobile'];
echo $list . "<br />";
}
}
Try this.
EDITED: Added closing bracket.
Use mysqli_num_rows() to test if there is anything returned.
Imagine you put some money in your pocket.
Eventually an idea came to your mind to see if you are still have the money.
You are taking it out and count them. All right.
Still holding them in hand you decided to take them from pocket. Oops! The pocket is empty!
That's your problem.
To see if you got any rows from the database you can use mysqli_num_rows(). It will return the number of bills, without fetching them from the pocket.
The problem is, that you try to use mysqli_fetch_array to queck for the number of results. mysqli_fetch_array will fetch the first result, compare it to false and then discard it. The next mysqli_fetch_array will then fetch the second result, which is not existing.
If you want to check if any clients where found, you can use mysqli_num_rows like this:
$idcard = mysqli_escape_string($dbc, $idcard); // See below: Prevents SQL injection
$query = "SELECT * FROM clients where idcard = '$idcard'";
$result = mysqli_query($dbc, $query) or die("Error quering database.");
if(mysqli_num_rows($result) == 0) {
echo "Sorry, no clients found";
} else {
while($row = mysqli_fetch_array($result)) {
// Do whatever you want
}
}
If $idcard is a user supplied value, please look out for SQL injection attacks.