I have a database from which I retrieve information successfully.
//Connect to mysql database
$con = mysqli_connect($host,$user,$pass);
mysqli_select_db($con, $databaseName);
//Query database for data
$sql = "SELECT * FROM donators";
$result = mysqli_query($con, $sql);
I can send it to my browser by iterating print_r($row)
//this returns the result
while($row = mysqli_fetch_array($result))
{
print_r($row);
}
But when I try to retrieve it by iterating $row['lastName'] it does not return anything at all. It works on all other rows. This specific row contains peoples lastName. I am also 100% certain I wrote 'lastName' right.
//no result here but woudl work without "firstName"=>$row['firstName']
while($row = mysqli_fetch_array($result))
{
$output[]= array( "index"=>$row['index'], "firstName"=>$row['firstName'], "lastName"=>$row['lastName']);
}
echo json_encode($output);
Anyone has an idea what can be / is causing this?
Related
I am trying to store the result from a MySQL statement for later use in PHP. I have this code which gets me the result:
// Get the categories from the db.
$categories = array();
$catSql = "SELECT id, name FROM categories";
if ($catStmt = mysqli_prepare($db, $catSql))
{
$catStmt->execute();
$result = $catStmt->get_result();
// Fetch the result variables.
while ($row = $result->fetch_assoc())
{
// Store the results for later use.
}
}
So I know i will have the results in $row["id"] and $row["name"] and I want to save all of the rows so whenever i need them i can loop through them and for example echo them. I have searched for structures and arrays for keeping them in PHP but I cannot seem to find any information about that or maybe I am not searching in the right direction. Can anyone point me where i should read about this to find out how to do this efficiently and if possible post a small example?
Use sessions:
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
// Get the categories from the db.
$categories = array();
$catSql = "SELECT id, name FROM categories";
if ($catStmt = mysqli_prepare($db, $catSql))
{
$catStmt->execute();
$result = $catStmt->get_result();
// Fetch the result variables.
while ($row = $result->fetch_assoc())
{
// Store the results for later use.
$_SESSION['category_' . $row['id']] = $row['name'];
}
}
Then access it later from a different page
$_SESSION['session_variable_name']
You can also create an array of the information and store the entire array in a single session variable.
Just make sure you add the session_start function at the beginning of each page. The if statement prevents you from trying to start it multiple times.
$categories = array();
$catSql = "SELECT id, name FROM categories";
if ($catStmt = mysqli_prepare($db, $catSql))
{
$catStmt->execute();
$result = $catStmt->get_result();
while ($row = $result->fetch_assoc())
{
$categories[$row['id']]=$row['name'];
}
}
And If you want the name anywhere use below :
$categories[$id]
I've rather new at php and mysqli and I've had some success but am currently facing a wall. Mostly because I dont know the terms to express what i'm trying to do.
I can select a row all day long but I seem to be stuck on the same row. I need to be able to select data from further down the column. Here is the code i'm working with.
$qry = "select * from products";
$rs = mysqli_query($conn,$qry);
$getRow = mysqli_fetch_row($rs);
$getRowAssoc = mysqli_fetch_assoc($rs);
echo "<img src=\"".$getRow['1'] . "\">";
i have several links to images in the picture column on my database but can't seem to figure out a simple way to display the links from other rows in that column. I may be way off base here but I dont think I am.
this is a layout of the db db pic
any help would be much appreciated
For each mysqli_fetch_assoc you get the result of the next row. As the index starts in -1, the first time you call it, it goes to the first row. So whenever you call it again, it goes to the next row. Use it inside of a loop and you will be all set.
while($row = mysqli_fetch_assoc($result)){
// $row will have new content each iteration
}
mysqli_fetch_assoc Fetch a result row as an associative array, but just 1 row, if you want to get all the result, you have to go through a loop to get everything for the result, example :
<?php
$query = 'SELECT `products`.* FROM `products`';
$mysqli = new Mysqli('localhost','test','root','password');
$result = $mysqli->query($query);
while ($row = $result->fetch_assoc()) {
echo '<img src="' . htmlentities($row['pic']) . '" /><hr />';
}
unset($row);
$result->free();
$mysqli->close();
if you want to get all the rows in 1 step for later usage, you would use mysqli::fetch_all(), example :
<?php
$query = 'SELECT `products`.* FROM `products`';
$mysqli = new Mysqli('localhost','test','root','password');
$result = $mysqli->query($query);
$products = $result->fetch_all();
$result->free();
$mysqli->close();
print_r($products);
here is my problem.
function getSent($id) {
include 'dbh.php';
$data = array();
$sql = "SELECT * from message WHERE senderid='$id'";
$result = $con->query($sql);
$row = $result->fetch_assoc();
while($row = $result->fetch_assoc()) {
$data[] = $row;
}
return $data;
}
In the theory this method is picking all messages (in this case), but it always find one message less than in the db => If I drop the whole table, I will get an array with the size of 0.
How could I fix this?
Remove the first $row = $result->fetch_assoc();. You are fetching one row, then looping to fetch the rest of the data and you don't store the first fetch.
`
I'd really like some help with the following MySQL / PHP problem (maybe bug?)
I'm trying to retrieve and display an array of data from my database using MySQL / PHP, but when I echo out the array, it returns the first value as 'null'.
So, even though the database has the following info:
"Example 1", "Example 2", "Example 3"...
The php echos out:
"null", "Example 2, "Example 3"
I would imagine this would be a common problem, but I haven't managed to find the required information elsewhere on the internet, so I'm hoping you kind folks can help.
My PHP
/* If connection to database, run sql statement. */
if ($conn) {
$fetch = mysql_query("SELECT column FROM table WHERE approved = '1' ");
// declare empty array to fill later
$result = array();
// make sure the MySQL pointer is looking at the first row
mysql_data_seek($fetch, 0);
while ($row = mysql_fetch_array($fetch, MYSQL_ASSOC)) {
foreach ($row as $value) {
$row_array = $value;
// push info into new array with just the value
array_push($result, $row_array);
}
}
}
/* Free connection resources. */
mysql_close($conn);
/* Toss back results as json encoded array. */
echo json_encode($result);
UPDATE
New code courtesy of Mark B:
if ($conn)
{
$sql = "SELECT column_name FROM table WHERE comment_approved = '1' ";
$query = mysql_query($sql) or die(mysql_error());
$result = array();
while ($row = mysql_fetch_assoc($query)) {
$result[] = $row['column_name'];
}
}
/* Free connection resources. */
mysql_close($conn);
/* Toss back results as json encoded array. */
echo json_encode($result);
NOTE:
The 'null' problem still occurs with or without the:
mysql_data_seek($fetch, 0);
as that appears to do nothing.
Any help would be great!
SOLVED
Thanks to Mark B who pointed out that the problem was probably in the database rather than the PHP, it turned out there was the character ` lurking where there should have been a '. This caused the information to appear 'null'.
$sql = "SELECT column FROM table WHERE approved = '1'";
$result = mysql_query($sql) or die(mysql_error());
$data = array();
while($row = mysql_fetch_assoc($result)) {
$data[] = $row['column'];
}
echo json_encode($data);
You shouldn't have to do the seek, as you've not done anything with the result at the time. And since you're only fetching a single column from the database, there's no need for the inner foreach() loop either.
Try removing the call to mysql_data_seek. I see no reason why the MySQL pointer wouldn't already point to the first row at the first call to mysql_fetch_array.
You could try removing mysql_data_seek($fetch, 0); as the pointer will already be on the first record if you have just made the query.
I have a query which is designed to retireve the "name" field for all records in my "tiles" table but when I use print_r on the result all I get is the first record in the database. Below is the code that I have used.
$query = mysql_query("SELECT name FROM tiles");
$tiles = mysql_fetch_array($query);
I really cant see what I have done wrong, I have also tried multiple searches within google but I cant find anything useful on the matter at hand.
<?php
// Make a MySQL Connection
$query = "SELECT * FROM example";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
echo $row['name']. " - ". $row['age'];
echo "<br />";
}
?>
'mysql_fetch_array'
Returns an array that corresponds to the fetched row and moves the internal data pointer ahead.
This means that it returns array (contains values of each field) of A ROW (a record).
If you want other row, you call it again.
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
// Do something with $row
}
Hope this helps. :D
Use "mysql_fetch_assoc" instead of "mysql_fetch_array".
$query = mysql_query('SELECT * FROM example');
while($row = mysql_fetch_assoc($query)) :
echo $row['whatever'] . "<br />";
endwhile;
I believe you need to do a loop to invoke fetch array until it has retrieved all the rows.
while ($row = mysql_fetch_array($query) ) {
print_r( $row );
}