PHP Fetch Associative Array - Selecting Multiple Rows from MySQL DB - php

Currently, I am able to select one row's data from my database table. I was wondering how it would be possible to select information from a specific different row without having to change the code to suit my needs every time. This is for a news article on my website.
Here's my Code:
<?php
session_start();
if(!$_SESSION['username']) {
header('location:index.php');
}
require 'connect.php';
$tbl_name = 'news';
$sql = "SELECT id, title, description, content FROM $tbl_name ORDER BY id DESC LIMIT 3";
$articles = array();
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
printf ('<p class="sidenav">1. %s</p>',$row["id"],$row["title"]);
?>
Now, as you can see, I've selected 3 rows. How can I output data from more than one row? Currently, this will output nothing if I have more than one row. Is there a way to specifically pinpoint certain information without having to select a row with a specific id?
UPDATE:
I've gotten this code now, but what if I wanted to print more than one at a time?
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_array($result,MYSQLI_ASSOC)) {
printf ('<p class="sidenav">1. %s</p>',$row["id"],$row["title"]);
printf ('<p class="sidenav">2. %s</p>',$row["id"],$row["title"]);
printf ('<p class="sidenav">3. %s</p>',$row["id"],$row["title"]);
}

$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_array($result,MYSQLI_ASSOC)) {
printf ('<p class="sidenav">1. %s</p>',$row["id"],$row["title"]);
}

I was able to accomplish this with the following code.
<?php
$i = 0;
$sql = "SELECT id, title FROM news ORDER BY id DESC LIMIT 3";
if ($stmt = mysqli_prepare($conn, $sql)) {
/* execute statement */
mysqli_stmt_execute($stmt);
/* bind result variables */
mysqli_stmt_bind_result($stmt, $id, $title);
/* fetch values */
while (mysqli_stmt_fetch($stmt)) {
$i++;
printf ('<p class="sidenav">' . $i . '. %s</p>',$id,$title);
}
/* close statement */
mysqli_stmt_close($stmt);
}
?>

Related

I only get one value in Mysql [duplicate]

This question already has answers here:
How do I iterate over the results in a MySQLi result set?
(2 answers)
Closed 1 year ago.
I am making a small browser game and I have a database where the high scores of the users are stored.
here an image of the database (name is the username and M1_CPM the score)
with the following code I am trying to get the top 10 values to later desplay them on a leaderboard:
$sql = "SELECT * FROM leaderboard ORDER BY M1_CPM DESC LIMIT 10";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
exit();
}
mysqli_stmt_execute($stmt);
$resultData = mysqli_stmt_get_result($stmt);
echo implode(",", mysqli_fetch_assoc($resultData));
The problem is that it always only echoes the highest score and not the top ten. Why?
The mysql_fetch_assoc() function returns only one row from a recordset as an associative array. to retrieve all rows use a while loop:
while($row = mysqli_fetch_assoc($resultData))
{
echo implode(",", $row);
}
Note: After the data is retrieved, this function moves to the next row in the recordset. Each subsequent call to mysql_fetch_assoc() returns the next row in the recordset.
Each time when mysqli_fetch_assoc($result) is accessed, the pointer moves to the next record. At last when no records are found, it returns null which breaks the while condition.
So you need first get the data with while and then use implode, sth like this
$rows = [];
while ($row = mysqli_fetch_assoc($resultData)) {
$rows[] = $row;
}
And then you can use implode, so your code will become like this
$sql = "SELECT * FROM leaderboard ORDER BY M1_CPM DESC LIMIT 10";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
exit();
}
mysqli_stmt_execute($stmt);
$resultData = mysqli_stmt_get_result($stmt);
$rows = [];
while ($row = mysqli_fetch_assoc($resultData)) {
$rows[] = $row;
}
echo implode(",", $rows);

Multiple MySQL Queries (first one to get an id based on the user) second one to get information of another project in a database with the id

I am trying to accomplish the following:
Get the project id from a database where the username =...
-> Users can be signed into different projects and it is being tracked in a database
Next step is to get information of the project database to display it for the user
-> But since the user can be signed into different projects I want him to see them underneath each other in a not yet specific order (I a
This is basically what I was trying to get to work and it displays the right content but unfortunately stops at the first project. My assumption is that it stops at the first project id and doesn't continue
-> I checked to see what code of the code works and as soon as is cut the information gathering query I get all project_id's
Here is basically the code that I am working with right now:
$sql = "SELECT project_id FROM project_members_db WHERE user_ID = '$user_id'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while ($row = $result->fetch_assoc()) {
//Album Informationen ziehen herausfinden
$sql = "SELECT project_name, sticker_count, manufacturer, sport, creation_datetime FROM project_db WHERE project_id = '$row[project_id]'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while ($row = $result->fetch_assoc()) {
//OUTPUT
echo "
$row['project_name'];
$row['count'];
$row['sport'];
$row['manufacturer'];
$row['creation_datetime'];
";
}
}
}
}
It looks like you ought to be able to do this with a single query - and as you are taking user supplied input you ought to consider using a prepared statement
$sql='select `project_name`, `sticker_count`, `manufacturer`, `sport`, `creation_datetime`
from `project_db` where `project_id` = ( select `project_id` from `project_members` where `user_id` = ? )';
$stmt=$conn->prepare( $sql );
$stmt->bind_param('s',$user_id);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($project_name,$sticker_count,$manufacturer,$sport,$creation_datetime);
while( $stmt->fetch() ){
echo $project_name,$sticker_count,$manufacturer,$sport,$creation_datetime;
}
You overwrite the first result with the second result. Change to:
$sql = "SELECT project_id FROM project_members_db WHERE user_ID = '$user_id'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
//Album Informationen ziehen herausfinden
$sql = "SELECT project_name, sticker_count, manufacturer, sport, creation_datetime FROM project_db WHERE project_id = '$row[project_id]'";
$result2 = $conn->query($sql);
if ($result2->num_rows > 0) {
// output data of each row
while($row2 = $result2->fetch_assoc()) {
//OUTPUT
echo $row2['project_name'] . ' '
$row2['count'] . ' '
$row2['sport'] . ' '
$row2['manufacturer'] . ' '
$row2['creation_datetime'];
}
}
}
}
Note putting arrays in your string doesn't work, so i have concatenated the echo instead.

Error displaying rows from MySQL tables

I am trying to get rows from a table when a condition is satisfied (status = 'no transit') but nothing shows up even when rows are supposed to show up (count is 1 and more).
if($query['num'] == 0){
echo "<p>No shopping orders on transit</p>";
}else{
$sql = "SELECT *, FORMAT(total, 0) AS total, FORMAT(grand_total, 0) AS grand_total FROM shipping_details WHERE status = 'no transit' ORDER BY order_id DESC";
foreach ($db->query($sql) AS $query){
echo" Show some results ";
$select = "SELECT * FROM shipping_order WHERE order_id = :order_id";
foreach ($db->query($select, array('order_id' => $query['order_id'])) AS $items){
echo"
Some results
";
//Foreach ends
}
}
}
You don't show enough that we can tell which codebase you use to connect to your DB (MySQLi, mysql_, or PDO), so the code below may need some tweaking.
The problem is basically that you never retrieve your database results. Instead you try to loop through the query execution itself.
Change
$sql = "SELECT *...";
foreach ($db->query($sql) AS $query)...
To
$sql = "SELECT *...";
$result = $db->query($sql); //execute the query
if(!$result) die($db->error); //exit and show error if query failed
//now we can fetch the results one at a time and loop through them
//this line may need to be adjusted if you're not using MySQLi
while($row = $result->fetch_assoc())...
Within the while loop, $row will contain the values from the DB record. Use print_r($row) to learn its shape.
It is not working, because you forgot to use prepare and execute methods from pdoStatemnt class.
See below:
$stmt = $db->prepare("SELECT * FROM shipping_order WHERE order_id = :order_id");
$stmt->execute(array('order_id' => $query['order_id']));
while ($result = $stmt->fetch(PDO::FETCH_ASSOC)){
echo"
Some results
";
//Foreach ends
}

PHP Displaying data from MySQL database

I wanted to display a page content with PHP and MySQL. But i don't know how to select and display data from PHP.
$name = $_GET['title'];
$query = "SELECT * FROM pages WHERE name = $name";
$result = mysql_query("$query");
But i don't know how to display data. I want to get the string value from content in sql table row where name = $name and display it.
If you can, please help me
You may try and include this in your code:
$name = mysqli_real_escape_string($_GET['title']);
$query = "SELECT * FROM pages WHERE name = $name";
$result = mysqli_query($link, $query);
while ($row = mysqli_fetch_array($result)){
echo $row['content'];
}
mysqli_free_result($result);
Here I have assumed $link as the handle to connect to the database.
N.B.: You may consider passing the $_GET values through mysqli_real_escape_string() to avoid sql injections which may prove fatal to the database and its tables. You also need to consider the usage of mysqli_* functions because mysql_* functions are deprecated and will be discontinued.
You have error in your sql, change
$query = "SELECT * FROM pages WHERE name = $name";
$result = mysql_query("$query");
to
$query = "SELECT * FROM pages WHERE name = '".$name."'"; // as name is char it should be enclosed in quotes
$result = mysql_query($query); // using quotes inside this will just display it without executing the query
You can fetch the results by this (if the result is only single record):
$row=mysql_fetch_array($result); // fetch the result as an array with subscript as the field name
echo $row['content']; // echo the value of the field content
If the query result contains multiple records then you have to do this inside a while loop like this:
while($row=mysql_fetch_array($result)) // fetch the result as an array with subscript as the field name
{
echo $row['content']; // echo the value of the field content
}
you have to do like this
$name = $_GET['title'];
$query = "SELECT * FROM pages WHERE name = '".$name."'";
$result = mysql_query($query);
//get values returned from query
$row=mysql_fetch_array($result);
//display required content
echo $row['content'];
Also mysql_* function are deprecated.You have to stop using this. Start using PDO or prepared statements or mysqli_* function
First of all the mysql_ is deprecated, use mysqli_
<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT Name, CountryCode FROM City ORDER by ID LIMIT 3";
$result = mysqli_query($link, $query);
/* numeric array */
$row = mysqli_fetch_array($result, MYSQLI_NUM);
printf ("%s (%s)\n", $row[0], $row[1]);
/* associative array */
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
printf ("%s (%s)\n", $row["Name"], $row["CountryCode"]);
/* associative and numeric array */
$row = mysqli_fetch_array($result, MYSQLI_BOTH);
printf ("%s (%s)\n", $row[0], $row["CountryCode"]);
/* free result set */
mysqli_free_result($result);
/* close connection */
mysqli_close($link);
?>
Source: http://www.php.net/manual/en/mysqli-result.fetch-array.php
$query = mysql_query("SELECT * FROM table WHERE name = $name");
$result = mysql_fetch_array($query);
//you'll get value in var
$var=$result['content'];
You can do this using Prepared Statements :
$query = "SELECT whatever1, whatever2 FROM pages WHERE name = ?";
$stmt = $connection->prepare($query);
$stmt->bind_param("s", $name);
$stmt->execute();
$stmt->bind_result($value_you_want, $value_you_want_as_well);
while($stmt->fetch()){
echo $value_you_want . $value_you_want_as_well;
}
$stmt->close();
Or you can do this using PDO :
$query = "SELECT whatever1, whatever2 FROM pages WHERE name = :name";
$stmt = $connection->prepare($query);
$stmt->bindParam(':name', $name, PDO::PARAM_STR, 20);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_OBJ);
foreach ($result as $page) {
echo $page->whatever1 . $page->whatever2;
}
$stmt = null; // Set to null to destroy connection

Trouble with urldecode and fetching information from database

I have used urldecode to receive a member ID from a previous site. The correct ID is being displayed in the URL but I can't fetch information from the database.
<?php
$id = urldecode(trim($_GET['memberID']));
$query = "SELECT * FROM members WHERE memberID = '".$id."'";
if ($result = $db->query($query)) {
while ($row = $result->fetch_assoc()){
printf("%s (%s)\n", $row["memberID"], $row['name']);
}
}
?>
All I get is a blank screen.
change mysql.error() to mysql_error()
$query = "SELECT * FROM members WHERE memberID = '".$id."'";

Categories