MySQL will not SELECT * FROM database - php

When I select all from my database, it only returns one row. I have changed it to select "column name" from database where "blank" = 1 and set multiple rows to have "blank" = 1 and it still only returns one row.
Here is my code:
<?php
$link = mysqli_connect("host", "database", "password", "database");
if (mysqli_connect_error()) {
die("There was an error, Please try again");
}
$query = "SELECT * FROM `news`";
$result = mysqli_query($link, $query);
$imageTest = mysqli_fetch_array($result);
?>
When I test this and print out the array with
<?php print_r($imageTest); ?>
It only comes back with one row (there are currently 3 test rows in the database)
I know Im probably missing something super small. Ive never really worked a project that I needed to select more than one row of items in a column.
I have another database being used in the same project that Im not having any issues with in its intended function but when I went to that one and tested the same thing, it returned the same results.

As per official documentation, mysqli_fetch_array fetch a single row from the result set every time it's called. Go for the following code to retrieve all of them:
$rows = array();
$result = mysqli_query($link, $query);
while ($row = mysqli_fetch_array($result))
$rows[] = $row;
print_r($rows);

mysqli_fetch_array fetches a single row from the result set.
What you're looking for is mysqli_fetch_all (or a while loop with mysqli_fetch_array ).
I would advise against using mysqli_* functions, and suggest using PDO.
Please refer to the following resources as to why I hold this opinion:
mysqli or PDO - what are the pros and cons?
https://phpdelusions.net/pdo/mysqli_comparison

Related

Explanation of mysqli_fetch_array and foreach

<?php
$connect = mysqli_connect("localhost", "root", "", "hempbag_db") or die("Connection failed");
$query= "Select * from tbl_sales";
$ress = mysqli_query($connect, $query);
$result = mysqli_fetch_array($ress);
foreach($result as $a)
{
echo $a['ID']; // This doesnt print although i used fetch array
}
foreach($ress as $a)
{
echo $a['ID']; // This works why???? This variable has only query run
}
?>
Why does the upper foreach does not run and lower one does? Can anyone explain please?
When you run a query, it returns a result:
$ress = mysqli_query($connect, $query);
var_dump($ress); // You will see it's a result.
At this point $ress just contains the result of what you just queried. Think of it like this:
You goto the warehouse, and you make and order for 1000 boxes of crackers. She heads to the back, and gets your boxes ready, and comes back and hands you a piece of paper with the order number. (This is $ress). Now, you can't loop through that, you can't do anything with that.
You now take that piece of paper, and you hand it to your assistant, and you say you want to get all the crackers on your trucks (This is now mysqli_fetch_array()). Your assistant goes, fetches it, and returns you the crackers.
Simply put, mysqli_query just returns an object like Result#1. From Result#1, mysql can tell you how many rows were returned mysql_num_rows(Result#1), or get actual data if it was a select query: mysqli_fetch_array(Result#1).
Now onto the reasoning: Performance. Let's say you didn't want 1000 crackers, you just wanted to know if they had 1000 crackers. If she came back with all the boxes of crackers and you had to count them yourself, it would be much more difficult. Instead, with that piece of paper, she can determine how many boxes you were able to order. Less data being transferred, and much more efficient.
Just a small note, in later versions of php, they made it so the result is iterable, meaning that if you try and loop through it, it will automagically call mysqli_fetch_array on that result, and return you the results.
Additionally, mysql_fetch_array will return one row from the database, and is not able to be looped through via foreach. Perhaps you were thinking of mysqli_fetch_all? This returns all rows and can be looped through (Although is a bit less performant than using a while loop with mysqli_fetch_array)
$ress = mysqli_query($connect, $query);
This line returns a result set which is Traversable. So your second foreach works fine.
whereas the following line (mysqli_fetch_array) gets one row at a time and makes it an array.
$result = mysqli_fetch_array($ress); // Suppose you have 3 rows, Now cursor is at row 1
echo $result["ID"]; // this will print FIRST row's ID
$result = mysqli_fetch_array($ress); // Now cursor is at row 2
echo $result["ID"]; // this will print SECOND row's ID.
$result = mysqli_fetch_array($ress); // Now cursor is at row 3
echo $result["ID"]; // this will print THIRD row's ID.
To echo all IDs
while($result = mysqli_fetch_array($ress)) {
echo $result["ID"];
}

Query for multiple SQLite tables with PHP

Forgive me if my question sounds stupid as I'm a begginer with SQLite, but I'm looking for the simplest SQLite query PHP solution that will give me full text results from at least three separate SQLite databases.
Google seems to give me links to articles without examples and I have to start from somewhere.
I have three databases:
domains.db (url_table, title_table, date_added_table)
extras.db (same tables as the first db)
admin.db (url_table, admin_notes_table)
Now I need a PHP query script that will execute a query and give me results from domains.db but if there are matches also from extras.db and admin.db.
I'm trying to just grasp the basics of it and looking for a starting point where I can at least study and learn the first code.
First, you connect to 'domains.db', query what you need, save however you want, than if there were a result in the first query, you connect to the others and query them.
$db1 = new SQLite3('domains.db');
$results1 = $db1->query('SELECT bar FROM foo');
if ($results1->numColumns() && $results1->columnType(0) != SQLITE3_NULL) {
// have rows
// so, again, $result2 = $db2->query('query');
// ....
} else {
// zero rows
}
// You can work with the data like this
//while ($row = $results1->fetchArray()) {
// var_dump($row);
//}
Source:
http://php.net/manual/en/sqlite3.query.php
http://php.net/manual/en/class.sqlite3result.php
Edit.: A better approach would be to use PDO, you can find a lot of tutorials and help to use it.
$db = new PDO('sqlite:mydatabase.db');
$result = $db->query('SELECT * FROM MyTable');
foreach ($result as $row) {
echo 'Example content: ' . $row['column1'];
}
You can also check the row count:
$row_count = sqlite_num_rows($result);
Source: http://blog.digitalneurosurgeon.com/?p=947

mysqli query in WHILE loop

1.) Can you nest a msqli_query inside a while loop?
2.) If yes, why would the PHP below not write any data to the precords table?
If I echo a $build array variable it shows properly, but the mysqli insert writes nothing to the table in the DB. THe code does not error out anywhere, so what am I missing about this?
$data = mysqli_query($con,"SELECT * FROM Cart WHERE Buyer_ID='$_SESSION[cid]' AND Cart_Date='$_SESSION[cdate]'");
while($build = mysqli_fetch_array($data))
{
//echo $build[idex]."<br>";
mysqli_query($con,"INSERT INTO precords (precord,Buyer_ID,Account,Purchase_Date,Item_Number,Item_Qty,Item_Title,Item_FPrice,Item_FFLFlag,ccpass) VALUES ('$build[idex]','$build[Buyer_ID]','$build[Cart_Date]','$build[Item_Number]','$build[Item_Qty]','$build[Item_Title]','$build[Item_FPrice]','$build[Item_FFLFlag]','N')");
};
Thanks for any help.
** P.S. - This code is meant to move certain values from a TEMPORARY table/session variables, over to a permanent record table, but the loop is needed since there is more than one product in the cart associated with the user/session.
yes you can use it in a loop and
you may wanna add mysql_error() function to find out what's wrong with it and try to fix it or by adding the error to the question so we can tell you what to do
$data = mysqli_query($con,"SELECT * FROM Cart WHERE Buyer_ID='$_SESSION[cid]' AND Cart_Date='$_SESSION[cdate]'");
while($build = mysqli_fetch_array($data))
{
// echo $build[idex]."<br>";
mysqli_query($con,"INSERT INTO precords(precord,Buyer_ID,Account,Purchase_Date,Item_Number,Item_Qty,Item_Title,Item_FPrice,Item_FFLFlag,ccpass)
VALUES ('$build[idex]','$build[Buyer_ID]','$build[Cart_Date]','$build[Item_Number]','$build[Item_Qty]','$build[Item_Title]','$build[Item_FPrice]','$build[Item_FFLFlag]','N')")
or die (mysql_error());
};
in a simplified form when you want to fetch data from a database to display in html list I intentionally added mysqli ORDER BY which have only two order ASC[ascending] and DESC[descending] and I also used mysqli LIMIT which i set to 3 meaning that number of result fetch from the database should be three rows only
I concur with the answer of ali alomoulim
https://stackoverflow.com/users/2572853/ali-almoullim
MY SIMPLIFIED CODE FOR THE LOOPING WHILE MYSQLI ORDER BY AND LIMIT
$usersQuery = "SELECT * FROM account ORDER BY acc_id DESC LIMIT 3";
$usersResult=mysqli_query($connect,$usersQuery);
while($rowUser = mysqli_fetch_array($usersResult)){
echo $rowUser["acc_fullname"];
}

Counting the values of rows in a column and using the total value in PHP

I know this is something simple. I'm just forgetting something.
I'm counting the values of the rows in the "numberattending" column of my database.
When I run the SQL statement
SELECT COUNT(numberattending) AS Total FROM RSVP
in the mySQL window I get the total I'm looking for.
When I try to extract that value and echo "num_seats" I get "Resource id #3"
$num_seats = mysql_query("SELECT COUNT(numberattending) AS Total FROM RSVP", $connection);
echo $num_seats;
What I'm I missing?
Thanks for any help ahead of time.
$num_seats represents a MySQL Resource, not the value of the field selected. You'll need to use either mysql_fetch_array() or mysql_fetch_object() depending on which you prefer.
For example:
$number = mysql_fetch_array($num_seats);
echo $number['Total'];
It's also worth noting that the mysql_* family of functions are now deprecated, and you should really be using MySQLi or PDO.
You need to loop through the result sets:
From the PHP site:
// Use result // Attempting to print $result won't allow access to
information in the resource // One of the mysql result functions must
be used // See also mysql_result(), mysql_fetch_array(),
mysql_fetch_row(), etc.
$num_seats = mysql_query("SELECT COUNT(numberattending) AS Total FROM RSVP", $connection);
while ($row = mysql_fetch_assoc($num_seats )) {
echo $row['total'];
}
PS: As others will surely tell you, use of the mysql* functions have been deprecated. Look for the mysqli functions instead.
Try
$query = mysql_query("SELECT COUNT(numberattending) AS Total FROM RSVP", $connection);
$result = mysql_fetch_row($query);
echo $result['Total'];

Loading a whole mySQL table into a PHP array

I have a table with 4 columns and 23 rows. I need all 92 values in the the table as PHP variables (whether that be one array, 4 arrays, 92 individual variables, or whatever).
The rows are:
ID
Category
Summary
Text
I need to build a series of select boxes where the items are grouped by the category, the options available are the summaries, and the resulting text is passed on for processing.
I've been searching, but all the examples I can find are about printing the table out, and I need to continue working with the variables.
I really appreciate any help!
Billy
Just a SELECT * FROM table_name will select all the columns and rows.
$query = "SELECT * FROM table_name";
$result = mysql_query($query);
$num = mysql_num_rows($results);
if ($num > 0) {
while ($row = mysql_fetch_assoc($result)) {
// You have $row['ID'], $row['Category'], $row['Summary'], $row['Text']
}
}
OK, I found my answer with better search terms. I'm still new here, so let me know if this is not a fair way to handle the situation. I upvoted #Indranil since he or she spent so much time trying to help me.
Anyway...
$content = array();
while($row = mysql_fetch_assoc($result)) {
$content[$row['id']] = $row;
}
Puts my whole entire table into one huge, multidimensional array so that I can use it throughout my code. And it even names the first level of the array by the ID (which is the unique identifier).
Thank you to those that tried to help me!
Billy
$pdo = new PDO(
'mysql:host=hostname;dbname=database;charset=utf-8',
'username',
'password'
);
$pdo->setAttribute( PDO::ATTR_EMULATE_PREPARES, false );
$stmt = $pdo->query('SELECT ID, Category, Summary, Text FROM Table');
if ( $stmt !== false )
{
$data = $stmt->fetchAll( PDO::FETCH_ASSOC );
}
In the case if the SQL query has no conditions, use query() , otherwise, you should be using prepare() ans bind the parameters.
Oh .. and please stop using the ancient mysql_* functions, they are in the process of being deprecated and no new code should written with them.

Categories