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'];
.............
}
Related
$database = new mysqli("localhost","username","password","database");
$sql = "SELECT * FROM values ORDER BY value DESC";
$values = $database->query($sql);
while($row = $values->fetch_assoc()){
echo $row["value"];
}
$database->close();
PHP fetches the associative array from the SQL table values, then it loops through the array and echoes the 'value' column. How can I get it to echo the row number as well? I can't have a separate column with the row numbers in it because the rows are ordered the number stored in the 'value' column and regularly change about.
Thanks.
well the simplest solution would likely be:
$database = new mysqli("localhost","username","password","database");
$sql = "SELECT * FROM values ORDER BY value DESC";
$values = $database->query($sql);
$cnt = 0;
while($row = $values->fetch_assoc()){
$cnt ++;
echo $row["value"] . $cnt;
}
$database->close();
If you have an "id" column in the table you can echo $row["id"], otherwise create a variable $i=0, increment its value by 1 on every iteration of the loop and echo $i
My table now
the above picture shows how my table looks like after select from sql. I wish to eliminate the first row of the time column move all rows up of the time column by one row. like the picture below.desired table Please advice. Any advice that would help is welcome.
code:
<?php
require_once 'db.php';
mysqli_set_charset($conn, "utf8");
$arr = array();
$sql = ("SELECT * FROM myTable WHERE idvisit=384 ORDER BY server_time ASC ");
$sql = mysqli_query($conn, $sql) or die ("ERROR :" .mysqli_error($conn));
while ($row = mysqli_fetch_array($sql, MYSQLI_ASSOC)){
$arr[] = $row['time_spent'];
echo "<br>";
}
$fruit = array_shift($arr);
print_r($arr);
echo $arr;
?>
First store the result into an array then remove first item from the array.
Sample Code:
$data = array();
while($row = mysqli_fetch_assoc($query))
{
$data[] = $row;
}
array_shift($data); //array_shift() remove first element of an array
Now run another loop if you want to grab result of each row. If you want to show it in table, here is a sample loop with html table.
echo "<table><tbody>";
forach($data as $item){
echo "<tr><td>";
echo $item['column_name'];
echo "</td></tr>";
}
echo "</tbody></table>";
Now, in the table it will show the result without first row from database.
I struggled all day to display the results of an SQL query using PHP.
I have a table in the database named coins with the following columns:
- nr_unic (which is the index);
- rank;
- name;
- symbol;
- price_usd;
- price_btc;
What I need to do is to fetch the values of each coin (from the name field) and display the symbol, price_usd, price_btc, and rank. The piece of code which contains the query I am running and trying to display the values is:
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// SQL QUERY
$sql= "SELECT rank, name, symbol, price_usd, price_btc, 24h_volume_usd FROM coins WHERE rank BETWEEN 1 AND 10 ORDER BY nr_unic DESC LIMIT 10";
$result = $conn->query($sql);
$rows = array();
if ($result) {
while($row = mysqli_fetch_array($result, MYSQLI_BOTH)) {
$rows[] = $row['name'] . " " . $row['price_usd'] . " " . $row['symbol'] . " " . $row['rank'];
foreach ($rows as $key => $value) {
echo $value;
}
}
mysqli_free_result ($result);
}
Thank you!
LATER EDIT
Following #Máté Solymosi indications I managed updated the code and to display the results. The problem now is they are getting duplicated: I get the first coin, then the first and the second, then the first, second and third... and so on.
The code I use was updated
The return statement in your while loop causes the function to terminate immediately, returning just the first row. Instead, you should collect the results in an array and return the array at the end:
$rows = array();
while($row = mysqli_fetch_array($result, MYSQLI_BOTH)) {
$rows[] = $row['name'] . " " . // ...
}
mysqli_free_result($result);
return $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";
}
$sql = "SELECT title, article, filename, caption FROM articles
INNER JOIN images WHERE articles.image_id = images.image_id";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
var_dump($row);
This only grabs the first row in the db when what I need is for it to grab all rows. How can I achieve this?
fetch_assoc() returns the next row of the result set with each call, so you need to call it in a loop like this:
while($row = $result->fetch_assoc()) {
var_dump($row);
}
The loop ends when $row = null (i.e. there's no more rows in the result set).
Please have a look at the Quick start guide, more specifically the Executing statements chapter. Right from that page:
$mysqli->real_query("SELECT id FROM test ORDER BY id ASC");
$res = $mysqli->use_result();
echo "Result set order...\n";
while ($row = $res->fetch_assoc()) {
echo " id = " . $row['id'] . "\n";
}