Select All MySQL Rows - php

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";
}

Related

Get top 4 highest rows based on ID

I'm trying to grab the highest 4 rows in a table and assign variables to them so that I can use them throughout my code.
Here is what I was able to get so far...
<?php
$username="USERNAME";
$password="PASSWORD";
$database="DATABASE";
$conn = mysqli_connect(localhost, $username, $password, $database);
$query = "SELECT * from `shoutbox` ORDER BY `id` DESC LIMIT 4";
$result = $conn->query($query);
while($row = $result->fetch_assoc()) {
$name =($row["name"]);
$message =($row["message"]);
$time =($row["time"]);
}
?>
How am I able to assign more variables to get the next 3 rows?
I believe it's (sorry, long day so I might be off)
$result = array();
while(...){
$result[] = $row;
}
I suggest you loop through the result set and assign each iteration to an array, you can then pull the values back out of the array later.
Here is a working update to your code
// ...
$query = "SELECT * from `shoutbox` ORDER BY `id` DESC LIMIT 4";
$result = $conn->query($query);
// create array to hold queried result set
$output = array();
// loop through result set and assign each row to a key in $output array
// Note: the fetch_assoc() method auto-increments an internal pointer
// so as you spin through the result set $row will move down the rows
while($row = $result->fetch_assoc()) {
$output[] = $row;
}
// $output now contains an associative array on each key representing
// each row, so to access each row:
foreach($output as $row) {
echo $row["name"] . "<br>";
echo $row["message"] . "<br>";
echo $row["message"] . "<hr>";
}
Define $result as array after while
$result = array();
while($row= .... ){
$var= $row['name'];
.............
}

Converting mysql into PDO format

I'm trying to convert some old php mysql code into PDO format but am stuck. I've looked at other posts on here but can't quite figure it out.
This is the old code:
<?php
if (isset($_POST['query'])) {
// Connect to database
mysql_connect("localhost", "xxxxx", "xxxxx");
mysql_select_db("xxxxx");
// Retrieve the query
$query = $_POST['query'];
// Search the database for all similar items
$sql = mysql_query("SELECT * FROM articles WHERE title LIKE '%{$query}%'");
$array = array();
while ($row = mysql_fetch_assoc($sql))
{
$array[] = $row['title'];
}
// Return the json array
echo json_encode($array);
}
?>
And this is what I've managed to do but think there's something wrong in the "while" part.
<?php
if (isset($_POST['query'])) {
require( "config.php" );
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
// Retrieve the query
$query = $_POST['query'];
// Search the database for all similar items
$sql = "SELECT * FROM articles WHERE title LIKE '%{$query}%'";
$array = array();
while ($row = $sql->fetchAll()) {
$array[] = $row['title'];
}
// Return the json array
echo json_encode($array);
}
?>
You are trying to call fetchAll on "sql" which is a string.
Now, you could use query but i suggest you to use prepare instead (for security reason, because you insert POST data).
$q = $conn->prepare("SELECT * FROM articles WHERE title LIKE CONCAT('%', ? ,'%')");
$q->execute(array($query));
// result contains all returned data
$result = $q->fetchAll();
// or row by row
while($row = $q->fetch())
From PHP.net
foreach ($conn->query($sql) as $row) {
Try somehing like this:
<?php
if (isset($_POST['query'])) {
require( "config.php" );
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
// Retrieve the query
$query = $_POST['query'];
//Build Query - Search the database for all similar items
$sql = "SELECT * FROM articles WHERE title LIKE '%{$query}%'";
$array = array();
$sth = $conn->query($sql);
$result = $sth->fetchAll();
foreach($result as $row){
$array[] = $row['title'];
}
// Return the json array
echo json_encode($array);
}
?>
=========Updated Answer========
//Better alternative
$query = $_POST['query'];
$sql = "SELECT * FROM articles WHERE title LIKE CONCAT('%', ? ,'%')";
$sth = $con->prepare($sql);
$sth->bind_param("s", $query);
$sth->execute();
$result = $sth->fetchAll();
foreach($result as $row){
$array[] = $row['title'];
}
// Return the json array
echo json_encode($array);
PS: Best practice is to stick with prepared statements and execute for increased security.
Try to run this:
$rows = $conn->prepare("SELECT * FROM articles WHERE title LIKE ?")->execute(array('%'.$query.'%'))->fetchAll();
while($row = $rows->fetch()) {
// TODO: Parse the rows
}
Also, try not to use * in your queries, that's not the best practice, it is better to use a column list instead separated by commas, as you do not necessary need to load the values of all columns. select * is less scalable and it might be the source of security vulnerabilities, like accidentally loading the inappropriate column and passing its value to the inappropriate place.

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();

php loop through sql result

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

Categories