Looping mulitple SQL queries in multiple arrays - php

I'm a PHP beginner. I've dabbled before, but when I've begun to get the knack a new project takes me elsewhere. If anyone can assist; I'd appreciate it.
I am using multiple queries and arrays to retrieve data between two mySQL tables starting from 1 initial known variant.
I'd like each query to process all results from the previous query. This is not occurring.
Current results: The first query echos all results. The second query echos one result. The third query echos 1 result. The final echo displays all the final results (desired, but missing the first 148 rows).
Desired results: Echo all 149 results from all three queries then echo a table/array of all 3 queries (to confirm correlation).
<?php
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//Select all POST_IDs for variation 2.1M
$sql = "SELECT post_id FROM wp_postmeta WHERE meta_value = '2-1m'";
$result = $conn->query($sql);
//Array and display POST_IDs
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["post_id"]. "<br>";
}
} else {
echo "0 results";
}
//Prepare POST_IDs for next query
foreach ($result as $row){
$postids = $row["post_id"];
}
//Use POST_IDs to select all PARENT_IDs
$sql2 = "SELECT post_parent FROM wp_posts WHERE ID = ($postids)";
$result2 = $conn->query($sql2);
//Array and display PARENT_IDs
if ($result2->num_rows > 0) {
// output data of each row
while($row2 = $result2->fetch_assoc()) {
echo "parentid: " . $row2["post_parent"]. "<br>";
}
} else {
echo "0 results";
}
//Prepare PARENT_IDs for next query
foreach ($result2 as $row2){
$parentids = $row2["post_parent"];
}
//Select PRICES using PARENT_IDs and META_KEY for Price
$sql3 = "SELECT meta_value FROM wp_postmeta WHERE meta_key = '_price' AND post_id = ($parentids)";
$result3 = $conn->query($sql3);
if ($result3->num_rows > 0) {
// output data of each row
while($row3 = $result3->fetch_assoc()) {
echo "price: " . $row3["meta_value"]. "<br>";
}
} else {
echo "0 results";
}
//Array and display PRICES
foreach ($result3 as $row3){
$prices = $row3["meta_value"];
}
//Display all retrieved data
echo "<div><p>" . $postids . " " . $parentids . " " . $prices . "</p></div>";
$conn->close();
?>

You're overriding your variables instead of cumulate them into an array:
foreach ($result as $row){
$postids = $row["post_id"];
}
Should be :
$postids = [];
foreach ($result as $row){
$postids[] = $row["post_id"];
}
Then :
"WHERE ID = ($postids)"
Should be :
if (!empty($postids)) {
... "...WHERE ID IN (".implode(',', $postids).")..." ...
}
NB: you should have a look to parameterized queries : Parameterized Queries PHP/MySQL
The same thing happend for $parentids.

Related

How do I print this here in any way possible I just want to print a number here

I want to print
<?php echo isset($meta['category_id']) ? $meta['category_id'] : '' ; ?>
This code is here in place number 2
`<?php
$sql = "SELECT title FROM posts WHERE category_id = '2'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row["title"]. "<br>";
}
} else {
echo "0 results";
}
?>`
This is a screenshot, with the knowledge that "category_id" will call the number of the group to which the post belongs.
Thank you all the solution was
$ sql = "SELECT title FROM posts WHERE category_id =". $ meta ['category_id'];

why COUNT function gives wrong input inside php and right result inside phpmyadmin sql

I'm trying to count the rows which are not NULL inside a table when exucting the query inside Phpmyadmin it gives me the right output.
SELECT COUNT(`column_name`) FROM `Table_name`
but when I'm trying to execute it inside Php it always returns one I tried 2 methods both returning one for some reasons any ideas ?
method 1
$query = "SELECT COUNT(`column_name`) FROM `Table_name`";
if ($result = $mysqli->query($query)) {
$field1name = $rowcount=mysqli_num_rows($result);
echo '<tr>
<td>English</td>
<td>'.$field1name.'</td>
</tr>';
$result->free();
}
method 2
$query = "SELECT COUNT(`column_name`) FROM `Table_name`";
if ($result = $mysqli->query($query)) {
while ($rowcount = $result->fetch_assoc()) {
$field1name = $rowcount=mysqli_num_rows($result);
echo '<tr>
<td>Bahdini</td>
<td>'.$field1name.'</td>
</tr>';
}
$result->free();
}
The SELECT COUNT Query returns a resultset of 1 row, in that row you get the number of rows: 10228 as you stated.
the function mysqli_num_rows returns the number of rows in the RESULTSET, that's why it returns 1.
You have several assigment in a row .. which is your expected result ??
$field1name = $rowcount =mysqli_num_rows($result);
Instaed You should use a proper column alias for your count and then query, fecth, loop over the result and show
$query = "SELECT COUNT(`column_name`) my_count FROM `Table_name`";
$result = mysqli_query($conn, $query );
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo "Name: " . $row["my_count"]. "<br>";
}
} else {
echo "0 results";
}

mysqli_fetch_array only displays the first result

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;

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'];
.............
}

Use variable as ID and get table from mysql (edited)

I'm using a multiple select option form to get a table of venues. Each venue has an ID and this is what I used:
<?php
require("db_access.php");
if(isset($_POST['select3']))
{
$aVenues = $_POST['select3'];
if(!isset($aVenues))
{
echo("<p>You didn't select any venues!</p>\n");
}
else
{
$nVenues = count($aVenues);
echo("<p>You selected $nVenues venues: ");
for($i=0; $i < $nVenues; $i++)
{
echo($aVenues[$i] . " ");
}
echo("</p>");
$sql = "SELECT * FROM venues WHERE id IN (" . implode(",",$aVenues) . ")";
$comma_separated = implode(",", $aVenues);
echo $comma_separated;
}
}
?>
It results in this:
However I thought that the code would use those two numbers below and draw out a table with those id's I used :/ ? Am I missing something?
$array is used in implode(",", $array); but is not defined anywhere else that we can see. It is perhaps intended to be:
implode(",", $aVenues);
UPDATE
Per comments, it does not draw a table because you never actually query your database.
You build your SQL statement, but you need to execute it and fetch the result set.
// Make sure you actually have a database connection
$conn = mysql_connect('localhost', $username, $password);
mysql_select_db($database);
$sql = "SELECT * FROM venues WHERE id IN (" . implode(",",$aVenues) . ")";
$comma_separated = implode(",", $array);
echo $comma_separated;
// Execute query and fetch result rowset
$result = mysql_query($sql);
if ($result) {
$rowset = array();
while ($row = mysql_fetch_array($result)) {
$rowset[] = $row;
}
var_dump($rowset);
}
else echo mysql_error();

Categories