Simple question. lets say I run the following:
$results = mysql_query("SELECT * FROM table");
How can I load the mysql results array into a PHP array without doing a while loop? Example:
$mysql_results = array();
$results = mysql_query("SELECT * FROM table");
$mysql_results = mysql_load_all_results_into_array($results);
Thanks!
PHP's mysql_ library does not offer a method to "fetch all" rows without looping through the results-object using mysql_fetch_row() (or similar).
You can, however, update your code to use the mysqli library which contains a method named mysqli_result::fetch_all to perform the task you desire. Alternatively, you could update to use PDO which contains a similar method named PDOStatement::fetchAll.
As the mysql_ methods are being deprecated, updating to mysqli (or PDO) is the recommended way to go regardless.
You can't do that with mysql. You have to loop. You can do that with PDO
Use MySQLi extension please :
http://php.net/manual/en/mysqli-result.fetch-all.php
use: $values = mysql_fetch_array($results); but do check for success of your operation.... thus: while ($values = mysql_fetch_array($result)) { $msg = "Array gotten successfully."; }
Related
How could I return the values from this query as an array so that I can perform an action with the array?
$sql = mysql_query("SELECT username FROM `users`");
$row = mysql_fetch_array($sql);
How would I get the code to be like the following? Here, the user1 and user2 would be the usernames of the users selected from the above query.
$userarray = array("user1","user2");
Before I point out best practices, you need working code first. So I'll give you a simple solution first.
To run a query with the mysql extension the function is mysql_query, you can't pass the query text directly to mysql_fetch_array. Nextly mysql_fetch_array doesn't do what you think it does. mysql_fetch_array combines the functionality of mysql_fetch_row and mysql_fetch_assoc together by storing the key names of the resulting columns along with their numeric indexes. The mysql_fetch_array function does not return an array with all rows from your query. To get all rows from the query, you need to run mysql_fetch_array in a loop like so:
$sql = "SELECT username FROM `users`";
$result = mysql_query($sql);
if(!$result){echo mysql_error();exit;}
$rows=array();
while($row = mysql_fetch_array($result))
{
$rows[]=$row;
}
print_r($rows);
Nextly, do note that the mysql_* functions are deprecated because the mysql extension in PHP is no longer maintained. This doesn't mean MySQL databases are deprecated, it just means the database adapter called mysql in PHP is old and newer adapters are available that you should be using instead, such as mysqli and PDO.
Next point, it is bad practice to rely upon short tags as it can be disabled by php.ini settings, always use either <?php ... ?> or <?= ... ?> for easy echoing which isn't affected by short tags.
Please read up on some mysqli or PDO simple examples to get started with one or the other. The mysqli extension is specific for MySQL while PDO (PHP Data Objects) is designed as a generic adapter for working with several kinds of databases in a unified way. Make your pick and switch so you're no longer using the deprecated mysql_* functions.
You would need to use a foreach loop to do it:
$userarray = [];
foreach($row as $single)
{
array_push($userarray, $single['username']);
}
and if can, try to use this MySQLi Class, it's very simple to get what you want from the database.
$db = new MysqliDb ('host', 'username', 'password', 'databaseName');
$userarray = $db->getValue('users', 'username', null);
I have a MySQL Database Table containing products and prices.
Though an html form I got the product name in a certain php file.
For the operation in this file I want to do I also need the corresponding price.
To me, the following looks clear enough to do it:
$price = mysql_query("SELECT price FROM products WHERE product = '$product'");
However, its echo returns:
Resource id #5
instead a value like like:
59.95
There seem to be other options like
mysqli_fetch_assoc
mysqli_fetch_array
But I can't get them to output anything meaningful and I don't know which one to use.
Thanks in advance.
You will need to fetch data from your database
$price = mysql_query("SELECT price FROM products WHERE product = '$product'");
$result = mysql_fetch_array($price);
Now you can print it with
echo $result['price'];
As side note I would advise you to switch to either PDO or mysqli since mysql_* api are deprecated and soon will be no longer mantained
If you read the manual at PHP.net (link), it will show you exactly what to do.
In short, you perform the query using mysql_query (as you did), which returns a Result-Resource. To actually get the results, you need to perform either mysql_fetch_array, mysql_fetch_assoc or mysql_fetch_object on the result resource. Like so:
$res = mysql_query("SELECT something FROM somewhere"); // perform the query on the server
$result = mysql_fetch_array($res); // retrieve the result from the server and put it into the variable $result
echo $result['something']; // will print out the result you retrieved
Please be aware though that you should not use the mysql extension anymore; it has been officially deprecated. Instead you should use either PDO or MySQLi.
So a better way to perform the same process, but using for example the MySQLi extension would be:
$db = new mysqli($host, $username, $password, $database_name); // connect to the DB
$query = $db->prepare("SELECT price FROM items WHERE itemId=?"); // prepate a query
$query->bind_param('i', $productId); // binding parameters via a safer way than via direct insertion into the query. 'i' tells mysql that it should expect an integer.
$query->execute(); // actually perform the query
$result = $query->get_result(); // retrieve the result so it can be used inside PHP
$r = $result->fetch_array(MYSQLI_ASSOC); // bind the data from the first result row to $r
echo $r['price']; // will return the price
The reason this is better is because it uses Prepared Statements. This is a safer way because it makes SQL injection attacks impossible. Imagine someone being a malicious user and providing $itemId = "0; DROP TABLE items;". Using your original approach, this would cause your entire table to be deleted! Using the prepared queries in MySQLi, it will return an error stating that $itemId is not an integer and as such will not destroy your script.
Im always using while loop in generating all record in my database, and some of my friend told me that it is better to use foreach in generating record from a database, but i dont know how.
<?php
$query = mysql_query("select * from sampleTABLE");
while($i = mysql_fetch_array){
echo $i['samplefieldName'];
}
?>
My question is, how to display records from my database using foreach? and can some one compare it in the while loop in terms in syntax and generating its result, thank you.
There is no need to use foreach instead of while here as #Zerkms says
while($i = mysql_fetch_array( $query)){
however ou can do this by below code but i am sure its not good approach
$result_list = array();
while($row = mysql_fetch_array($query)) {
result_list[] = $row;
}
foreach($result_list as $item) {
//you can now echo $item ; or whatever you want
}
Note
The entire ext/mysql PHP extension, which provides all functions named with the prefix mysql_, is officially deprecated as of PHP v5.5.0 and will be removed in the future. So use either PDO or MySQLi
Good read
The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead
PDO Tutorial for MySQL Developers
Pdo Tutorial For Beginners
Firstly, the mysql_xxx() functions are deprecated. They are not recommended for use. There are two alternatives in PHP that are recommended instead -- mysqli() and PDO.
The older mysql_xxx() functions do not allow you to use foreach to loop through a recordset.
However, both the newer alternative APIs do allow this, as they implement the Iterator interface.
So yes, it is possible to use foreach to loop through a recordset in PHP, but not with the old mysql_xxx() functions.
You could write code like this:
$conn = new mysqli(....);
foreach ( $conn->query('SELECT ....') as $row ) {
print_r($row);
}
or like this:
$db = new PDO('mysql:....', $user, $pass);
foreach ($db->query('SELECT ....') as $row) {
print_r($row);
}
Having said that, please note that it's only been possible to do this with mysqli since PHP v5.4, so you'll need to be up-to-date with your PHP version for that. PDO on the other hand has supported this feature for ages.
They can, of course, both also use a while loop as well, and this is where your friend isn't quite right, because really there isn't any difference between while and foreach here. Switching from while to foreach won't make any difference to the performance of your code. They do the same thing under the hood. foreach in this case is really just "syntactic sugar".
I would strongly recommend switching to one of these newer APIs, even if you don't plan to use foreach to do your looping, because as I say, the old mysql functions are deprecated, which means that they are likely to be removed entirely from future PHP versions. So if you want your code to keep running into the future, you should switch now.
It's not possible to iterate over a result set using foreach.
foreach only works for cases when you already have the data fetched.
So your friend was just wrong and his advice doesn't make any sense.
#zerkms
I also thought like that.. But following works...
My 'tbl_login' table structure also attached as a
<?php
include '../common/dbConnection.php';
class foreachtest{
function foreachtesting(){
$sql="SELECT * FROM tbl_login";
$query_result=$GLOBALS['con']->query($sql);
return $query_result;
}
}
$myobject = new foreachtest();
$result=$myobject->foreachtesting();
foreach ($result as $a){
echo $a['username'];
}
?>
tbl_login MYSQL table screenshot
If I am doing a PHP MYSQL select of a table using the where clause that will return only 1 result, is there a simpler way to do this:
$result = mysql_query("select * FROM cart WHERE ID='".$cartID."'") or die(mysql_error());
$cartrec = mysql_fetch_array($result);
Is the $cartrec = mysql_fetch_array($result); needed or could I just do:
$cartrec = mysql_query("select * FROM cart WHERE ID='".$cartID."'") or die(mysql_error());
or is there a better syntax to use?
mysql_query gets a result set (actually, a resource that refers to a result set) based on your query. This is the set of records that match your query.
mysql_fetch_array gets the first record from a result set, and returns it as an array.
So, up until you've called mysql_fetch_array, you haven't gotten the data in a usable format.
Side note: Consider using PDO
The fetch array is required, the mysql_query gets a result set (ressource), then mysql_fetch_array get's the element in the result set.
As a side note, be careful of SQL injections: http://en.wikipedia.org/wiki/SQL_injection
EDIT: Might be a bit more advanced that what you need, but it might be worth while looking into PDO: http://php.net/manual/en/book.pdo.php
Is the $cartrec = mysql_fetch_array($result); needed
Yes, otherwise you get a resource pointer not an result set (array).
or is there a better syntax to use?
Yes, MySQLi
No, but its pretty common for people to write their own function for this use case. It's usually named something like fetch_one($sqlString) or fetch_first($sqlString)
You could use this, but if the database structure were to change, it would be problematic
$row = mysql_fetch_row($result);
echo $row[0]; //column 1
echo $row[1]; //column 2
You may want to look at this http://www.php.net/manual/en/function.mysql-fetch-row.php
I'm new to PHP. I have a select statement that returns 100 values for a particular record. I'd like to store these 100 values in an array. Is this the right command to store values that I get from a select statement into an array?
$result = mysql_query("select * from processed1 where record = ('$id') ");
$data = array();
while($row = mysql_fetch_array($result))
{
$data[] = $row; //IS THIS CORRECT?
}
Is there a way where I can avoid typing in the 100 attributes for my table? example : $row[1] ... $row[100]
If you are going to learn PHP in 2011, let's do it right.
First off, mysql_query or mysql_ anything code is deprecated. Don't use it anymore.
Don't worry - what I am suggesting works great with mysql databases, but it will also work great with any database:
PDO is what the PHP community continues to add features to, so I would use that.
PDO is also way more powerful, and makes it easier to switch databases later.
MYSQLi (the i stands for improved) replaces deprecated mysql_ based queries, but I would definitely go straight to using PDO.
You could also easily create an array
of objects later with one line change!
Secondly, Phil mentioned fetchAll(). This is the end goal. The other ways simply move thru it one row at a time. This uses a bulldozer instead of a shovel. Note: not the best way of selecting really large amounts of data, as it will use up memory. Otherwise, it is fine.
To get there, use prepared procedures to protect your code from SQL injection attacks.
<?php
/* Execute a prepared statement by binding PHP variables */
$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
FROM fruit
WHERE calories < :calories AND colour = :colour');
$sth->bindParam(':calories', $calories, PDO::PARAM_INT);
$sth->bindParam(':colour', $colour, PDO::PARAM_STR, 12);
$sth->execute();
/* Fetch all of the rows into an array */
print("Fetch all of the remaining rows in the result set:\n");
$result = $sth->fetchAll();
print_r($result);
?>
Your code looks fine to me. But I would suggest to use mysql_fetch_assoc() instead of mysql_fetch_array(), so that keys are mapped to their values. Also, use mysql_real_escape_string() to prevent SQL injection.
$query = "Select * from processed1 where record = '".mysql_real_escape_string($id)."'";
$result = mysql_query($query);
$data = array();
while($row = mysql_fetch_assoc($result))
{
$data[] = $row;
}
If you're trying to store all the database rows into an array, yes, that code should do it. A few comments, though:
As curiou57 suggested, use mysql_fetch_assoc() to be able to refer to columns in an individual row by their names. (ex: foreach ($data as $row) { echo $row['columnname']; })
Make sure you run $id through mysql_real_escape_string() if you have to continue using the mysql extension. This prevents SQL injection attacks.
If you don't have to continue using the mysql extension, consider using PDO or mysqli.
Switch to mysql_fetch_row() if you want to reference each column by a numeric index (note, zero-based). Otherwise, that looks correct.
If you decide to switch to PDO, you can use the handy PDOStatement::fetchAll() method, using the PDO::FETCH_NUM fetch style to fetch all rows as numeric arrays into an array.
This is the correct way:
while($rows[] = mysqli_fetch_assoc($result));
array_pop($rows); // pop the last row off, which is an empty row