I need to return data from 2 separate tables at the same time. The info I need from the 2nd table is determined by what is returned from the first table. Here's what I'm working with..
$query = "SELECT * FROM pending WHERE paymentid = '".$_GET['vnum']."'";
$result = mysql_query($query);
$num = #mysql_num_rows($result);
$linkid = $res['paymentid'];
if ($num==0) {
echo "Hello, ".$_SESSION['Fname']."<br />There was an error, I cannot find this payment in the records.";
} else {
$picquery = mysql_query("SELECT * FROM _uploads_log WHERE linkid = '".$linkid."'");
$numb = #mysql_num_rows($picquery);
if ($numb==0) {
echo "there is no picture"; }
else {
echo "<img src=\"".$res['log_filename']."\" width=\"100\">"; }
I don't understand how to return the results as an array, if $res[] returns the results for the first query, then what returns the results for the second one?
or is there a better way to do this entirely?
Thank you
You need to do a join, but in order to still get results from your first query even if there is no picture (I assume that's why you split it up) you want a left join.
select * from pending left join _uploads_log on pending.paymentID=$_GET['vnum'] and _uploads_log.linkid = pending.paymentID
(note: php markings removed for readability - you'll have to add them back in)
This should (untested since I don't have your tables) return the full row for your vnum variable and also include the picture data if there is one.
Related
I'm trying to get specific rows in table 1 (stellingen). I want to store these rows to specify the rows im interested in for the second table (stelling). So lets say table 1 has 5 rows where stelling ID matches REGIOID = 5. These IDS from stelling ID I want to use to fetch the data from the second table. see the code to see what I tried. I'm not managing to find a way in order too make this happen.
So maybe too be clearer because people always say im not clear:
There are two tables. they both have a matching column. Im trying to tell the second table I want data but only if it matches the data of the first table. Like a branch of a tree. Then, I want to output some data that's in the second table.
I've tried something like this before:
SELECT
*
FROM
table2
LEFT JOIN
table1 ON
table1.ID = table2.table1_id
I've tried to create a while loop to get the data before(after the first if statement and the last += was for the variable $amountofstellinge):
$amountOfStellinge = 0;
while ($amountOfStellinge<5){
mysqli_data_seek($result, $amountOfStellinge);
Here is the code what it looks like now, its wrong, i've been messing with t a lot, but maybe it shows you what I'm trying to achieve better.
if($result = mysqli_query($con, "SELECT * FROM stellingen WHERE REGIOID=1;")) {
$row = mysqli_fetch_assoc($result);
$stellingid= $row["Stelling_ID"];
//checking.. and the output is obviously not what I want in my next query
printf($stellingid);
//defining the variable
$Timer=0;
$sql1="SELECT * FROM stelling WHERE stelling_iD=$stellingid ORDER BY Timer DESC;";
$records2 = mysqli_query($con, $sql1);
$recordscheck = mysqli_num_rows($records2);
//max 5 data
if ($recordscheck < 5){
while ($stelling = mysqli_fetch_assoc($records2)){
//At the end, i would like to only have the data that is most recent
$Timer = date('d F', strtotime($stelling['Timer']));
echo "<p><div style='color:#ED0887'>".$Timer.":</div><a target = '_blank' style='text-decoration:none' href='".$stelling['Source']."'>".$stelling['Title']."</a></p>";
}}
$recordscheck+=1; } // this is totally wrong
EDIT:
I've tried this, #noobjs
$Timer=0;
$sql1="SELECT
*
FROM
stelling
LEFT JOIN
stellingen
ON
stelling.ID = stellingen.stelling_id
WHERE
stellingen.REGIOID=1
ORDER BY stelling.Timer LIMIT 5 DESC ;";
$records2 = mysqli_query($con, $sql1);
printf($records2);
while ($stelling = mysqli_fetch_assoc($records2)){
$Timer = date('d F', strtotime($stelling['Timer']));
echo "<p><div style='color:#ED0887'>".$Timer.":</div><a target = '_blank' style='text-decoration:none' href='".$stelling['Source']."'>".$stelling['Title']."</a></p>";
}
with this error:
Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given in
EDIT for more clarification
Here is some sample data
The expected results is:
every page has uses data from a different REGIOID. I expect the page to show data from the table stelling(Table 1). Accordingly to the REGIOID (Table2)
if i understand right:
SELECT
*
FROM
stelling
LEFT JOIN
stellingen
ON
stelling.stellingID = stellingen.stelling_id
WHERE
stellingen.REGIOID=1
ORDER BY stelling.Timer DESC LIMIT 5 ;
I have a query that requests an ID (the PK) and an order number and throws them into an array. I then loop through the returned data in the array and run two more queries to find the number of times the order number shows up in the database and to get the invoice numbers that belong to that order number. The problem I'm seeing with this setup is that it is taking a while (around 9 seconds) to return the compiled data array. Is there a faster way to get the returned results I'm looking for?
I've tried to find some articles online and came across mysqli_multi_query. Is this the better route to make multiple queries to gather the type of data I am trying to get?
<?php
require 'config.php';
$sql = "SELECT id,internal_order_number FROM orders GROUP BY internal_order_number ORDER BY created_date desc LIMIT 0 ,50";
$query=mysqli_query($mysqli, $sql);
if (!$query) {
throw new Exception(mysqli_error($mysqli)."[ $sql]");
}
$data = array();
while( $row=mysqli_fetch_array($query) ) { // preparing an array
$nestedData=array();
$nestedData['line_id'] = $row["id"];
$nestedData['internal_order_number'] = $row["internal_order_number"];
$data[] = $nestedData;
}
$compiled_data = array();
// Loop through data array with additional queries
foreach($data as $line){
$new_data = array();
// Get item counts
$item_counts = array();
$get_count = " SELECT internal_order_number FROM orders WHERE internal_order_number = '".$line['internal_order_number']."' ";
$count_query=mysqli_query($mysqli, $get_count);
while ($counts=mysqli_fetch_array($count_query)){
if (isset($item_counts[$counts['internal_order_number']])) {
$item_counts[$counts['internal_order_number']]++;
} else {
$item_counts[$counts['internal_order_number']] = 1;
}
}
$product_count = $item_counts[$line['internal_order_number']];
// Get invoice numbers
$invoice_array = array();
$get_invoices = " SELECT invoice_number FROM orders WHERE internal_order_number = '".$line['internal_order_number']."'";
$invoice_query=mysqli_query($mysqli, $get_invoices);
while ($invoice=mysqli_fetch_array($invoice_query)){
if(!in_array($invoice['invoice_number'], $invoice_array)){
$invoice_array[] = $invoice['invoice_number'];
}
}
$invoices = implode(", ",$invoice_array);
$new_data['order_number'] = $line['internal_order_number'];
$new_data['count'] = $product_count;
$new_data['invoices'] = $invoices;
$compiled_data[] = $new_data;
}
mysqli_close($mysqli);
print_r($compiled_data);
?>
What, why are you doing basically the same query 3 times. You first one selects them all, you second query requires the same table making sure the first tables order number == the tables order number and the last just grabs the invoice number...?
Just do one query:
SELECT internal_order_number, invoice_number FROM table WHERE ...
Then loop through it and do what you need. You don't need 3 queries...
I've a table that has three columns id, points, rank. Timely I update data for all fields so points go up and down but old rankings remains same, so I'm trying to find out a way that entitles each id its deserving rank based on points earned.
I've got more than 2000 rows in this table. I wish to do it in php5+ with mysqli? I think I've a solution but it times out even with 1200 seconds timeout setting and memory gets exhausted.
I think my solution works accurately but any of the loops needs some doctor. Here my rough target is 'update' query to go accurate that takes all points in desc order, and awards id a rank against the points earned:
<?php
require_once $_SERVER['DOCUMENT_ROOT'].'/includes/db.inc.php';
$a2= mysqli_query($link, "SELECT COUNT(*) as count FROM p1");
$b2 =mysqli_fetch_array($a2);
$count = $b2['count'];
$i=1;
while($i<=$count){
$a1= mysqli_query($link, "SELECT points FROM p1 ORDER BY points DESC LIMIT $i");
if(!$a1){
echo mysqli_error($link);
}
while($po = mysqli_fetch_array($a1)){
$ross[] = $po;
}
foreach($ross as $pot){
$points=$pot['points'];
}
$a5a= mysqli_query($link, "SELECT id FROM p1 WHERE points = '$points'");
while($popo = mysqli_fetch_array($a5a)){
$idi=$popo;
}
foreach($idi as $idm){
$id=$idm['id'];
$rank = $i;
$update = mysqli_query($link,"UPDATE p1 SET rank = '$rank' WHERE points = '$points' AND id ='$id'");
}
if(!$update){
echo "Error updating Rank".mysqli_error($link);
} else {
echo "Succuessul for where id = '$id' and points = '$points' set rank = '$rank'<br/>";
}
$i++;
}
?>
I have replaced my original answer with much leaner and shorter code, you can of course include modification to the rank counter if consecutive users have same points but you can figure this yourself
This code have just one loop and is conserving memory and your DB as well
<?php
require_once $_SERVER['DOCUMENT_ROOT'].'/includes/db.inc.php';
$a = mysqli_query($link, "SELECT id, points, rank FROM p1 ORDER BY points DESC "); // lets get users in new ordering
$rank = 1; // new ranks
while($line = mysqli_fetch_array($a)){
if ($rank != $line["rank"]) { //if old rank is different we will hit db with new value
echo "updating id ".$line["id"]." from rank ".$line["rank"]." to rank ".$rank." <br>";
if(!mysqli_query($link,"UPDATE p1 SET rank = '".mysqli_real_escape_string($link,$rank)."' WHERE id ='".mysqli_real_escape_string($link,$line["id"])."'")) {
echo "Error updating Rank".mysqli_error($link);
}
}else { //if its the same we just leave the message for now
echo "ignoring id ".$line["id"]." previous rank ".$line["rank"]." , new rank ".$rank." <br>";
}
$rank++; // next user so lets increment the counter
}
?>
Recently went through same kind of issue and found a simple solution like below after struggling a lot. I would like to clear it out that, it depends on your input and expected result as well which you didn't mention in your post.
if (preg_match('/"'.<value>.'"/i' , json_encode(<your array>))) {
echo "Match";
} else {
echo "Doesn't match";
}
Please replace values accordingly when trying! Thanks for reading it.
The following answer code takes all points, and relevant ids and sets high to low ranks against high to low points respectively. However, it does not assign same rank for same points holder id as it keeps rolling with Rank+1 until end. That could be done, but isn't presently required.
<?php
require_once $_SERVER['DOCUMENT_ROOT'].'/includes/db.inc.php'; //connection to the DB
$a1= mysqli_query($link, "SELECT id, points FROM p1 ORDER BY points DESC"); //Selecting High to low all points
if(!$a1){
echo mysqli_error($link);
}
while($po = mysqli_fetch_array($a1)) {
$rose[] = $po;
}
$rank=0;//set rank 0
foreach($rose as $ro) { //splitting each row of array with unlimited rows
$points=$ro['points'];
$id=$ro['id'];
$rank++; //adding 1 each time foreach loops repeats itself until no row left
$update = mysqli_query($link,"UPDATE player1 SET rank = '$rank' WHERE points = '$points' AND id ='$id'"); //sending update command
if(!$update) { //echoing out what the hell this code is f******
echo "Error updating Rank".mysqli_error($link);
} else {
echo "Succuessul for where id = '$id' and points = '$points' set rank = '$rank'<br/>";
}
}
?>
I have a search results page which displays items from a MySQL database (table1). The code I am using to the display the results is:
if (!empty($data)) {
foreach ($data as $item) {
echo '<div class="item">';
if (strlen($item['item_desc']) > 10) {
if (strlen($item['item_link']) > 10) {
echo '<a href="/item.php?id='.$item['item_id'].'">';
} else {
echo 'No Results Found';
}
}
}
}
The images for each search result are stored in a separate table (table2). I am trying to use the code below to count the number of images in table2 for each result and display the number against each result on the search results page, but it returns a 0 value?
$result=mysql_query("SELECT count(*) as total from table2 where id = '" .$item['item_id']. "'");
$query=mysql_fetch_assoc($result);
echo $query['total'];
I am missing some data about your database structure but I can imagine you store your image id as an integer and you are requesting the count with the id being a string.
So, if I'm true this may help. Remove the quotes around the php variable with the item_id
"SELECT count(*) as total from table2 where id = " .$item['item_id'];
you can try this..
$str=$item['item_id'];
mysql_query("SELECT count(*) as total from table2 where id = '$str'");
There is a mysql function to count rows outputted from your mysql query, it is mysql_num_rows(). From what I can understand about your database your code could be this:
$item_id = $item['item_id'];
$result = mysql_query("SELECT * FROM table2 where id = '$item_id'");
$count = mysql_num_rows($result);
echo $count;
This will output how many records match your query.
I'm coding in PHP/MySQL and have the following query to fetch products and product group data:
SELECT products.id,products.name,product_groups.id,product_groups.name
FROM products
INNER JOIN product_groups
ON products.id=product_groups.id
WHERE products.name LIKE '%foobar%'
ORDER by product_groups.id ASC
So this query fetches products and orders them by product group. What I would like to have is to display product_groups.name just once for each product grouping. So even if I have ten shoe products, the group name "Shoes" is only displayed once.
I'm using the following PHP to print out the results:
while ($data = mysql_fetch_array($result))
If you want it done in the MySQL query, it is honestly more trouble than it's worth. For one, the syntax is really wonky (as I recall) to have a group name listed at the top of each grouping. And the results are still treated as rows, so the group name will be treated like a row with all the other columns as Null, so you won't really save any time or effort in the PHP script as it has to do an if statement to catch when it hits a group name instead of the group data.
If you want it done by the PHP while loop, Johan is on the right track. I use the following for a similar situation:
$result = $sql->query($query);
$prev_group = "";
while($data = $result->fetch_assoc()){
$curr_group = $data['group'];
if ($curr_group !== $prev_group) {
echo "<h1>$curr_group</h1>";
$prev_group = $curr_group;
}
else {
echo $data;
.....
}
Obviously the echo data would be set up to echo the parts of the data the way you want. But the $prev_group/$curr_group is set up so that the only time they won't match is when you are on a new group and thus want to print a header of some sort.
while($data = mysql_fetch_assoc($result)){
if($data['product_groups.name'] != $groupname){
echo "Groupname: ".$data['product_groups.name']."<br />";
$groupname = $data['product_groups.name'];
}
echo "ID: ".$data['products.id']."<br />";
echo "Name: ".$data['products.name']."<br />";
}
Maybe you can do like this!?