How to only show ID's not already in another table - php

I am trying to display records from a categories table that don't exist in another table. This works to a certain extent whereby if there are 3 records in the sp_cats table, the display from $stmt2 will show all records except 1 where it should be all except 3. So, it isn't looping through for some reason.
$stmt = $link->prepare("SELECT `sp_cat_id` FROM `sp_cats` WHERE `sp_id` = ?");
$stmt->bind_param("i", $_GET['id']);
$stmt->execute();
$result = $stmt->get_result();
$numRows = $result->num_rows;
if($numRows > 0) {
while($row = $result->fetch_assoc()){
$spCats = $row['sp_cat_id'];
echo $spCats . "<br/>";
}
}
$stmt->close();
echo "<br>";
$stmt2 = $link->prepare("SELECT `cat_id`FROM `categories` WHERE `cat_id` != ?");
$stmt2->bind_param("i", $spCats);
$stmt2->execute();
$result2 = $stmt2->get_result();
$numRows2 = $result2->num_rows;
if($numRows2 > 0){
while($row2 = $result2->fetch_assoc()){
$cat_id = $row2['cat_id'];
echo $cat_id . "<br/>";
}
}
$stmt2->close();

See this while() loop here,
while($row = $result->fetch_assoc()){
$spCats = $row['sp_cat_id'];
...
}
The problem is, in each iteration of while() loop you're overwriting $spCats value. Besides, you don't have to use two different queries, you can do everything in just one query, like this:
$stmt = $link->prepare("SELECT `cat_id`FROM `categories` WHERE `cat_id` NOT IN (SELECT `sp_cat_id` FROM `sp_cats` WHERE `sp_id` = ?)");
$stmt->bind_param("i", $_GET['id']);
$stmt->execute();
$result = $stmt->get_result();
$numRows = $result->num_rows;
if($numRows > 0){
while($row = $result->fetch_assoc()){
$cat_id = $row['cat_id'];
echo $cat_id . "<br/>";
}
}
$stmt->close();

Related

Display Last userID in php from MySQL

I am trying to echo last userID stored in MySQL. But it is not shown. No error is displayed.
I tried:
$stmti = $reg_user->runQuery("SELECT * FROM tbl_users");
$rowi = $stmti->fetch(PDO::FETCH_ASSOC);
$tf = $rowi['userID'];
echo $tf;
/* NOTE: This works only with mysqli
change the parameters "host","username","password","db_name" with your
own ones
*/
$link = mysqli_connect("host","username","password","db_name");
$query = " SELECT *
FROM tbl_users";
$rows = array();
$result = mysqli_query($link, $query);
while($row = mysqli_fetch_array($result,MYSQLI_ASSOC))
$rows[] = $row;
$lastID = 0;
for ($i = 0 ; $i < count($rows) ; $i++)
$lastID = $i;
echo $rows[$lastID]["userID"];
try this :
$sth = $reg_user->prepare("SELECT MAX(userID) as userID FROM tbl_users");
$sth->execute();
$result = $sth->fetch(PDO::FETCH_ASSOC);
$tf= ($result['userID']);
echo $tf;

Select * from table not working SQL

I am trying to select all records from a table and then output them below, however I am only able to get the most recent output out.
The table structure is Id, Start, End, DistanceDirections and Date
I am using the code below to get them and then output each Start as a H1 on the page. As mentioned I am only getting the last value out not all as I would expect, I have also tried to be more specific which can be seen in the code below that and it didn't have an effect on the result.
$sql = "SELECT * FROM `searchdata`";
$stmt = $conn->prepare($sql);
$stmt->execute();
foreach($stmt as $row) {
$htmlResult = "<h1>" . $row['Start'] . "</h1>";
}
Here is the other try:
$sql = "SELECT * FROM `searchdata` WHERE DistanceDirections = 'distance'";
$stmt = $conn->prepare($sql);
$stmt->execute();
foreach($stmt as $row) {
$htmlResult = "<h1>" . $row['Start'] . "</h1>";
}
Is there something simple I am missing?
You're only executing the query, you'll also need to fetch the rows.
$sql = "SELECT * FROM `searchdata`";
$stmt = $conn->prepare($sql);
$stmt->execute();
$result = $stmt->fetchAll();
$htmlResult = "";
foreach($result as $row) {
$htmlResult .= "<h1>" . $row['Start'] . "</h1>";
}
echo $htmlResult;
More info:http://php.net/manual/en/pdostatement.fetchall.php

MySQL Prepared Statement, write multiple rows

So far I have used prepared statements to get ONE row from a database. But how do I write multiple rows onto the page. Looked online and people only seem to be showing how to get the one row.
if ($count_sets->num_rows > 0) {
$query = "SELECT id,jpg,udate,imageset FROM images WHERE dodelete = ? AND udate = ? AND imageset = ?";
if ($stmt = $mysqli->prepare($query)) {
//echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
$stmt->bind_param("isi",$deleted,$session_date,$imageset);
$stmt->execute();
$stmt->store_result();
//Get result
$stmt->bind_result($result_id,$result_jpg,$result_date,$result_imageset);
//Number of rows returned
$count_rows = $stmt->num_rows;
}
} else {
echo "No images to process, do an upload first!";
}
$folder = str_replace("/", "", $session_date);
if ($count_rows > 0) {
echo "hel<br />";
echo $result_jpg[0];
}
Found some example code:
$db = new mysqli("host","user","pw","database");
$stmt = $db->prepare("SELECT * FROM mytable where userid=? AND category=? ORDER BY id DESC");
$stmt->bind_param('ii', intval($_GET['userid']), intval($_GET['category']));
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($column1, $column2, $column3);
while($stmt->fetch())
{
echo "col1=$column1, col2=$column2, col3=$column3 \n";
}
$stmt->close();
It's the following part I didn't know how to do.
while($stmt->fetch())
{
echo "col1=$column1, col2=$column2, col3=$column3 \n";
}

SQL query not showing more than 1 row

This is the entire code the error must be in query 3 or 4. As you can see query 3 just gets info to build query 4 which should return the results.
I've got query 1 & 2 working ok which have the correct data showing.
<?php
session_start();
//printf('<pre>%s</pre>', print_r($_SESSION, true));
require('includes/config.inc.php');
require('includes/session.php');
//WORKING
DB_Connect();
$query = "SELECT * FROM food_delivery_orders_items WHERE food_delivery_orders_items.type = 'product' AND food_delivery_orders_items.order_id=".$_SESSION['pdf_quote']['id']."";
$result = mysql_query( $query) or die(mysql_error());
while($row = mysql_fetch_array($result))
{
$hash = $row['hash'];
$foreignid = $row['foreign_id'];
$qty = $row['cnt'];
}
$query2 = "SELECT * FROM food_delivery_products WHERE food_delivery_products.id = ".$foreignid."";
$result2 = mysql_query( $query2) or die(mysql_error());
while($row = mysql_fetch_array($result2))
{
$name = $row['name'];
$description = $row['description'];
}
//---------------------------------------------------------------------------------------------------------------
$query3 = "SELECT * FROM food_delivery_orders_items WHERE food_delivery_orders_items.type = 'extra' AND food_delivery_orders_items.order_id=".$_SESSION['pdf_quote']['id']."";
$result3 = mysql_query( $query3)or die(mysql_error()) ;
while($row = mysql_fetch_array($result3))
{
$foreignidextra = $row['foreign_id'];
$qtyextra = $row['cnt'];
}
$query4 = "SELECT * FROM food_delivery_extras WHERE food_delivery_extras.id = ".$foreignidextra."";
$result4 = mysql_query( $query4) or die(mysql_error());
while($row = mysql_fetch_array($result4))
{
$nameextra = $row['name'];
}
echo $nameextra;
echo $qtyextra;
DB_Disconnect();
//$products = implode(", ",$_SESSION['pdf_quote']['product_arr']);;
//print $products
?>
print $row; is only valid inside the loop if you want to print all of them. Otherwise it will print only the last $row. Make it
while($row = mysql_fetch_array($result3))
{
$foreignidextra = $row['foreign_id'];
$qtyextra = $row['cnt'];
print $row;
}
its because you are printing the $row after the while loop gets executed
So it only prints the final result set
Use something like this instead:
$query3 = "SELECT * FROM food_delivery_orders_items WHERE food_delivery_orders_items.type = 'extra' AND food_delivery_orders_items.order_id=".$_SESSION['pdf_quote']['id']."";
$result3 = mysql_query( $query3) ;
while($row = mysql_fetch_array($result3))
{
$foreignidextra = $row['foreign_id'];
$qtyextra = $row['cnt'];
print_r($row);
}
you can also use the var_dump($row); instead of print_r($row);
this will output all the values stored in the $row array each time the loop iterates

Why am I receiving only the first value for each element of the array?

I am not able to figure out why all of my results are repetitions of the first values it returns.
This code returns the same ID and formatted date repeated over and over again; however, I was expecting it to read a value and then transform that value for each entry in the DB. Here is my code:
<?php
include('../includes/conn.inc.php');
$stmt = $mysql->prepare("SELECT id, endDate FROM TABLE ORDER BY id");
$stmt->execute();
$stmt->bind_result($id, $endDate);
while($row = $stmt->fetch()) {
$dataRow[] = array('id'=>$id,'endDate'=> $endDate);
};
foreach($dataRow as $i) {
$newEndDate = date('Y-m-d',strtotime($endDate));
$sql = 'UPDATE TABLE SET startDate = ? WHERE id= ? ';
$stmt = $mysql->stmt_init();
if ($stmt->prepare($sql)) {
$stmt->bind_param('si',$newEndDate, $id);
$OK = $stmt->execute();}
if ($OK) {
echo $id . " " . $newEndDate . "done <br/>";
} else {
echo $stmt->error;
}
$stmt->close();
};
In your foreach you are always using the last values that were set from the last $stmt->fetch()
Try:
foreach($dataRow as $i) {
$newEndDate = date('Y-m-d',strtotime($i['endDate']));
$id = $i['id'];
$sql = 'UPDATE TABLE SET startDate = ? WHERE id= ? ';
$stmt = $mysql->stmt_init();
if ($stmt->prepare($sql)) {
$stmt->bind_param('si',$newEndDate, $id);
$OK = $stmt->execute();
}
if ($OK) {
echo $id . " " . $newEndDate . "done <br/>";
} else {
echo $stmt->error;
}
$stmt->close();
};
use get_result();
$dataRow = array()
$stmt = $mysql->prepare("SELECT id, endDate FROM TABLE ORDER BY id");
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_array()) {
$dataRow[$row['id']] = $row['endDate'];
}
and you don't populate your $endDate in the second loop
foreach($dataRow as $i => $endDate){
$newEndDate = date('Y-m-d',strtotime($endDate));
... // rest of your code

Categories