I've got a problem with fetching data from a MySQL database. It fetches rows, and when printing the result with print_r it looks correct, but when getting one item in the array is always empty, and I don't have a clue why!
If I use phpMyAdmin I can see all rows in the database and they look correct.
Anyone got an idea?
<?php
$con = mysqli_connect($host, $user, $password) or die("Failed to connect to MySQL: " . mysqli_connect_error());;
mysqli_select_db($con, $database) or die("Cannot select DB");
$r = mysqli_query($con, "SELECT Question FROM TempQuestions") or die('Query failed: ' . mysql_error());
Print "Rows ". mysqli_num_rows($r) . "<br>"; // Returns 10 rows
while ($dbResult = mysqli_fetch_array( $r)) {
print_r($dbResult); // Prints the question like Array ([0] => The question in DB, [Question] => The question in DB)
Print "<br><br>";
Print "Question: ";
Print $dbresult['Question']; // Is always empty!
Print $dbresult[0]; // Is always empty!
Print "<br><br>";
}
mysqli_free_result($r);
mysqli_close($con);
?>
... or die('Query failed: ' . mysql_error());
You cannot mix up mysql_* with mysqli_*.
And this should be working now, variable names are case-sensitive:
while ($dbresult = mysqli_fetch_array($r)) {
print_r($dbresult);
Print "<br><br>";
Print "Question: ";
Print $dbresult['Question'];
Print $dbresult[0];
Print "<br><br>";
}
Related
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.
Good day,
I'm a noob at PHP and MySQl. Looking to be pointed in the right direction.
I have a MySql table with 5 columns. Each column represents a specific set of data. All numerical.
I want to write PHP code which takes each value in a single column and puts it into an array that I can then modify.
I don't know how to get each column as a separate array. Should I get an array of all the rows and then do something extra to separate each of the 5 numbers in each row into 5 separate arrays?
**
require_once 'login.php';
echo $db;
$conn = mysqli_connect($hn,$un,$pw,$db);
if (!$conn) {
echo "Error: Unable to connect to MySQL." . PHP_EOL;
echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
exit;
}
$query = "SELECT xox FROM tablex WHERE id = '1'";
$result = $conn->query($query);
if(!$result) die ("Database access failed: " . $conn->error);
$rows = mysqli_fetch_row($result);
while($rows){
echo $rows['index'];
}
echo $rows[0];
?>
$statement = **yourDatabaseConnection**->query('SELECT column1 FROM table');
$datas = $statement->fetch();
$datas will be an array of your column1 datas
Try reviewing the php documentation, here is a good place to start...php:mysql_fetch_row
Take a look at the example below, if is not what you looking for, please edit your question and provide the approach you are taking (your code) so that we have a better understanding where you are having issues.
<?php
$result = mysql_query("SELECT id,email FROM people WHERE id = '42'");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$row = mysql_fetch_row($result);
echo $row[0]; // 42
echo $row[1]; // the email value
?>
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);
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.
I'm fairly new to php and mysql and I'm on the home stretch of finishing my page but I've been banging my head on the keyboard all day trying to figure out how to fix this problem. I've set up a php script to run as a cron even every 24 hours. The script assigns a random number between 10 and 30 to each field in my table. That works fine and every time I load the script the values change.
The problem I'm having is when I try to use those values. The result keeps printing as the word Array instead of the number in the table. So I'll give you some snippets of the code I'm running here. This is the cron event.
?php
$con = mysql_connect("localhost","username","pass");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("dbname", $con);
$random= rand(10, 30);
mysql_query("UPDATE winners SET pool= '$random'");
mysql_close($con);
And here is the script to call up the values.
php?
$db = mysql_connect('localhost','username','pass') or die("Database error");
mysql_select_db('dbname', $db);
$query = "SELECT pool FROM winners";
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($result))
if ( $row % 2 )
{
echo "<h4>Result 1</h4>";
echo "$row";
echo "<br />";
}
else
{
echo "<h4>Result 2</h4>";
echo "<br />";
}
I've tried every possible variation I can think of to this code but all I can get is it to echo either Array or Resource #9. Any insight into this would be greatly appreciated.
You do not want to echo the content of $row, which contains all data returned for the current line you've fetched from the database when calling mysql_fetch_array().
Instead, you want to access the content of $row's pool item :
echo $row['pool'];
You should probably take a closer look at the manual page for mysql_fetch_array(), and the examples it contains.
Note that you'll probably also want to modify the condition in the following line :
if ( $row % 2 )
You probably don't want the test to be done on $row, but on an item it contains.
$query = "SELECT pool FROM winners";
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($result))
{
if ( $row['pool'] % 2 )
{
echo "<h4>Result 1</h4>";
echo "$row['pool']";
echo "<br />";
}
else
{
echo "<h4>Result 2</h4>";
echo "<br />";
}
}
Hope this helps.