php loop through sql result - php

I have a table called sales_product with columns
sales_product_id, sales_id, type, class, age
I have a query in php saying
$sql = "SELECT * from sales_product WHERE sales_id = " . $_GET['sales_id];
Suppose this query returns two rows.
$result = mysql_query($sql);
How do I loop through this result and save in an array so that later on I can retrieve data like
echo $sales_product[$i]['sales_product_id'];
echo $sales_product[$i]['sales_product_id'];
........

Do mysql_fetch_assoc in while loop:
$result = mysql_query($sql);
$rows[] = array();
while ( $row = mysql_fetch_assoc($result) ) {
echo $row['sales_product_id'];
$rows[] = $row;
}
var_dump($rows);

Use mysql_fetch_assoc
while ($row = mysql_fetch_assoc($result)) {
echo $row["sales_product_id"];
}

Try this,
$result = mysql_query($sql);
while ( $row = mysql_fetch_assoc($result) ) {
echo $row['columnName'];
}
Use mysql_fetch_array() if u need with index

check this one.
$sql="SELECT sales_product_id, sales_id, type, class, age From sales_product";
$sales= $db->query($sql);
while($sale = $db->fetchByAssoc($sales))
{
echo $sales['sales_product_id'];
echo $sales['type'];
// here instead echo uyou will add data in your array
}

Take a look at
mysql_fetch_array();
Note
Use of this extension is discouraged. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:
mysqli_fetch_array()
PDOStatement::fetch()

Something like this should work, this will give you the format you requested (untested):
while($row = mysql_fetch_assoc($result)) {
$sales_product[] = $row;
}

Since mysql_ has been declared deprecated so i am going to answer your question with
mysqli_* extension
//Prepare an SQL statement for execution
$stmt = $mysqli->prepare("SELECT * from sales_product WHERE sales_id = ?");
//bind parameter to the prepared statement
$stmt->bind_param("i", $_GET['sales_id]);
//execute it
$stmt->execute();
//store the result
$result = $stmt->get_result();
//loop through the result set
while ($myrow = $result->fetch_assoc())
{
$salesIds[] = $myrow["sales_product_id"];
}
For more information please refer to php documentation.
Thanks

Related

How to store multiple variables returned from a SELECT in arrays of their own - PDO

I'm rewriting all my old mysql code as PDO code but I can't think of a way to store multiple variables returned from a SELECT in arrays of their own.
I can put ONE set of values in a new array as follows:
$stmt1 = $db->prepare("SELECT P_ID
FROM personal
WHERE personal.firstname=:firstname
AND personal.lastname=:lastname");
// Bind
// Execute
// Fetch
// Store
if ($row)
{
foreach ($row as $key)
{
$PIDs[] = $key;
}
}
But in this query I want to put firstnames and secondnames in different arrays:
$stmt2 = $db->prepare("SELECT FirstName, LastName
FROM personal");
In mysql I was doing:
while ($row = mysql_fetch_array($result))
{
$firstnames[] = $row[0];
$lastnames[] = $row[1];
}
Can someone please help? Every sample PDO SELECT I can find only handles one returned field.
Assuming you fetch data from your statement $stmt:
$stmt2 = $db->prepare("SELECT FirstName, LastName FROM personal");
$stmt2->execute();
while ($row = $stmt2->fetch(PDO::FETCH_ASSOC))
{
$firstnames[] = $row['FirstName'];
$lastnames[] = $row['LastName'];
}
You want to set the PDO fetch mode so you can reference the 2D array by name and then fetch all of the rows.
$stmt = $dbh->query($sql);
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$result = $stmt->fetchAll();
More information can be found here.
And then you can use array_column, more information can be found here;
$firstNames = array_column($result, 'FirstName');
$lastNames = array_column($result, 'LastName');

Select All MySQL Rows

I have the following code which choose all rows in MYSQL but it show the last row only
$query = mysql_query("SELECT * FROM `users`") or die(mysql_error());
while ( $row = mysql_fetch_assoc($query) )
{
$token = $row['instagram_access_token'];
}
echo "$token";
Your code echo last row because, within while loop every time you overwrites $token value with new value. Try to connect using PDO & assign variable to array like this.
$token=[];
$user='your_user_name';
$pass='your_password';
$conn= new PDO('mysql:host=your_host_name;dbname=your_db_name', $user, $pass);
$query = $conn->prepare('SELECT * FROM `users`');
$query->execute();
// alternatively you could use PDOStatement::fetchAll() and get rid of the loop
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
$token[] = $row['instagram_access_token']; // see this line with []
}
echo '<pre>';
print_r($token);
echo '</pre>';
Note: Don't use mysql_* see more here Why shouldn't I use mysql_* functions in PHP?
Change your code to this:
$query = mysql_query("SELECT * FROM `users` ORDER BY RAND()") or
die(mysql_error());
while ( $row = mysql_fetch_assoc($query) )
{
$m = $row['instagram_access_token'];
echo "$m";
}

PHP loop not performing as it should

$query = "SELECT * FROM table WHERE data = '$userinput'";
$row = mysql_query($query);
while ($row = mysql_fetch_array($row))
{
echo $row['data'];
}
Ok So my questions are:
What exactly does mysql_fetch_array return?
AND if my WHERE clause finds multiple matches, shouldn't the loop execute numerous times?
I am running a program and I can only get the first result to print
You're overwriting $row. Instead use a different variable for the query result.
$query = "SELECT * FROM table WHERE data = '$userinput'";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result))
{
echo $row['data'];
}
Try using mysql_fetch_assoc($row)
You should not use the same variable as the index and the loop variable.
$row = mysql_query
while( $row = ...
Replace the first $row with $result

Get result out of query [duplicate]

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
How do i “echo” a “Resource id #6” from a MySql response in PHP?
I am looking for the result out of a query, but it keeps giving me resource id #3.
The following is my code.
$type = "SELECT `sellingid` FROM `ticket` WHERE `ticketid` = $_GET[ticketid]";
$typeResult = mysql_query($type);
print_r($typeResult);
What step am I missing here?
You need to fetch the result. All you're doing is sending the query.
Be aware that if you are writing new code, you should use mysqli_ or PDO functions as your query is vulnerable to SQL injection and mysql_ functions are being deprecated. Hesitantly, below is a sample for mysql_fetch_assoc.
<?php
$sql = "SELECT `sellingid` FROM `ticket` WHERE `ticketid` = $_GET[ticketid]";
$result = mysql_query($sql);
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
// While a row of data exists, put that row in $row as an associative array
// Note: If you're expecting just one row, no need to use a loop
// Note: If you put extract($row); inside the following loop, you'll
// then create $userid, $fullname, and $userstatus
while ($row = mysql_fetch_assoc($result)) {
echo $row[sellingid];
}
mysql_free_result($result);
?>
Reference
$type = "SELECT `sellingid` FROM `ticket` WHERE `ticketid` = $_GET[ticketid]";
$typeResult = mysql_query($type);
$row = mysql_fetch_array($typeResult);
print_r($row);
More clear hint - use MySQLi class/functions, read this:
http://lt1.php.net/manual/en/mysqli-result.fetch-assoc.php
or if you like OOP approach more then
http://lt1.php.net/manual/en/mysqli-result.fetch-object.php
You are not actually fetching the results of your query. Below are two examples that use WHILE loops to fetch the results as rows. You can then grab the column values and work with them.
Incorrect and depreciated method, but working:
$type = "SELECT `sellingid` FROM `ticket` WHERE `ticketid` = $_GET[ticketid]";
$typeResult = mysql_query($type);
// for each row
while ($row = mysql_fetch_array($typeResult)) {
// grab the columns
$value = $row['column_name'];
}
I would recommend using MySQLi or PDO like to following (MySQLi):
$mysqli_connection = new mysqli("hostname", "username", "password", "database");
$type = "SELECT `sellingid` FROM `ticket` WHERE `ticketid` = $_GET[ticketid]";
$res = $mysqli_connection->query($type);
while($row = $res->fetch_array(MYSQLI_ASSOC)) {
$value = $row['column_name'];
}
$res->free();
$mysqli_connection->close();

Pulling Data from a Mysql Table Field and putting it into an array

I can find lots of tutorials showing you how to load an array into a database field but can't seem to figure out how to pull each entry in a field into an array as seperate items. Seems simple enough just can't get it to work, any help?
If using the modern PDO library, use the PDOStatement->fetchAll() function with the fetch_style parameter set to PDO::FETCH_COLUMN.
Based on a sample from that page:
$sth = $dbh->prepare("SELECT field FROM dbtable");
$sth->execute();
$array = $sth->fetchAll(PDO::FETCH_COLUMN);
If using the old MySQL API (not recommended, example omits error checking)
$array = array();
$result = mysql_query("SELECT field FROM dbtable");
while ($row = mysql_fetch_row($result)) {
$array[] = $row[0];
}
mysql_free_result($result);
$big_2_dimensional_array_of_data;
foreach ($big_array_of_data as $row) {
$query = "INSERT INTO table_name (field1, field2, ...) VALUES($row[0], $row[1], ...)
mysql_query($query);
}
Something like that I think
after reading his question a few times, i guess what he wants to do is something like this:
$query = "SELECT field1, field2, ... fieldn FROM table;";
$r = mysql_query($query,$conn);
$row = mysql_fetch_assoc($r);
i'm still not quite sure what it is he exactly wants...
My interpretation of this question is that the questioner has inserted a number of rows into a table, and isn't sure how to handle getting them out other than one at a time. (It's possible that the question might also be referring to data serialized and then stuck into a single field... but I hope not!)
So, here's how to get multiple rows:
$query = "SELECT field1, field2, ... fieldn FROM table;";
$r = mysql_query($query,$conn);
$data = array();
while($row = mysql_fetch_assoc($r)) {
$data[] = $row;
}
You'd now have all the rows returned by your query in $data, so something like this would work to access it: $data[2]['field1']
The examples below assume your SELECT statement is stored in $select and your connection is stored in $db. A two-dimensional array of the results is stored in $rows afterward.
If you're using mysql (for mysqli procedures, just replace mysql_ with mysqli_):
$result = mysql_query($select, $db);
$rows = [];
while ($row = mysql_fetch_assoc($result) {
$rows[] = $row;
}
Using mysqli classes:
$result = $db->query($select);
$rows = [];
while ($row = $result->fetch_assoc()) {
$rows[] = $row;
}
$result->close()
Using PDO:
$stmt = $db->query($select);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

Categories