The other page that is the index page shows the catalog of the pizzashop. Each pizza is a hyperlink that passes the id to this page.
The core of my question is in the code that starts with the foreach loop. I would like to simply read out of the database based on the SELECT query at hand.
I know it is weird to put the query IN the loop but for now it is the only way I figured out how to loop through all the ids that are in the SESSION array.
I tried many things to output the return that the query is supposed to give, I fiddled around with the mysqli_stmt thing, all giving me numerous types of errors.
<?php
session_start();
require 'pizza_sc_fns.php';
require 'header.php';
#$pizzaId = $_GET['pizza_id'];
if (!isset($_SESSION['order']))
{
$_SESSION['order'] = array();
$_SESSION['items'] = 0;
$_SESSION['totalprice'] = 0.00;
}
if (isset ($_SESSION['order'][$pizzaId]))
{
echo $_SESSION['order'][$pizzaId]++;
echo "\$_SESSION['order'][\$pizzaId] is SET \n";
}
else
{
echo $_SESSION['order'][$pizzaId] = 1;
}
$conn = connect2db();
foreach ($_SESSION['order'] as $pizzaItem)
{
$query = "SELECT pizza_name FROM pizzas WHERE pizza_id = $pizzaItem";
$res = #$conn->query($query);
echo $res->fetch_assoc();
echo "<hr />";
//$query = mysqli_prepare($conn, "SELECT * FROM pizzas WHERE pizza_id=$pizzaItem");
//echo var_dump($query)."<br />";
//$stmt_exec = mysqli_stmt_fetch($query);
//print $pizzaItem."<br />";
}
?>
Destroy session >>
You are going to need to use a loop but you don't need to run the query for every iteration. You can use the in clause.
Your code would be something like
$query = 'Select pizza_name from pizzas where id in (';
foreach($_SESSION['order'] as $pizza_id) {
$query.= mysql_real_escape_string($pizza_id).', ';
}
$query= substr($query, 0, -2); //Get rid of the trailing comma and space
$query .= ')';
And you can run the query.
I would recommend that you use prepared statements though I'm not sure how to use them for an in statement.
Related
// This gets all the users that are active
// The limit is completely random, it is set to 2 for this example
$sql = <<<SQL
SELECT *
FROM `accounts`
WHERE active = 1
LIMIT 2
SQL;
if(!$getaccounts = $db->query($sql)){
die('There was an error running the query [' . $db->error . ']');
}
while ($row = $getaccounts->fetch_assoc()) {
$getid = $row["id"].',';
$getid = substr($getid, 0, -1);
$getusername = $row["username"];
$getpassword = $row["password"];
echo $getid;
echo $getusername."<br>";
echo $getpassword."<br>";
}
I know this hasn't been prepared but I am not using it for anything other than personal use.
I cannot understand why this is not getting rid of the last comma?
The output may be something like "32,14,"
And I want to get rid of the last comma by using the "substr" function.
But the output that that I get from $getid is "3214" (It gets rid of all the commas instead of just the last one.
I need it to output "32,14" but it's not working?
Could someone please tell me where I am going wrong?
If I do rtrim, it does the same thing and gets rid of all the commas! I am going to update something in the database using the ids, and that is why I need to get rid of the last comma
And I know this code is not secure, I am not using it for anything other than personal use and I was hoping someone could help me figure this out, I have been attempting it for days, it seems really simple and I bet I am missing something really stupid!
You have a XY Problem.
You want to concat all the id's into a comma-seperated string.
Here's a much easier solution by adding the items to an array and then implode().
<?php
// rest of your code
$ids = Array();
while ($row = $getaccounts->fetch_assoc()) {
$ids[] = $row["id"];
$getusername = $row["username"];
$getpassword = $row["password"];
echo $getusername."<br>";
echo $getpassword."<br>";
}
echo "ids: " . implode(",",$ids);
You should write code like..
$getid = "";
while ($row = $getaccounts->fetch_assoc()) {
$getid .= $row["id"].',';
}
$getid = rtrim($getid,',');
$q = " UPDATE accounts SET active = '0' WHERE id IN ($getid) ";
I am trying to run a query off multiple array variables and display the results in a table.
The user selects 1 or more records, which includes BOL and CONTAINER. These selections are put in their own arrays and they are always an equal amount.
<?php
$bolArray = explode(',', $_POST['BOL']);
$containerArray = explode(',', $_POST['CONTAINER']);
$count = count($bolArray); // to get the total amount in the arrays
I use a FOR loop to separate each value from the 2 arrays:
for($i = 0; $i < $count; $i++)
{
$bol = $bolArray[$i];
$container = $containerArray[$i];
}
Here is the part where I'm stuck and probably where I am messing up.
I need to take each variable from the FOR loop and run query using both variables.
First, I'll start the table:
echo "<table><thead><tr><th>BOL</th><th>Container</th></thead><tbody>";
Here is where I tried a FOREACH loop:
foreach($containerArray as $container) // I am not sure if I am using this FOREACH correctly
{
And now, the query. Please take note of the variables from the first FOR loop:
$preQuery = "SELECT * FROM mainTable WHERE CONTAINER = '".$container."' AND BOL = '".$bol."'";
$preRes = mysql_query($preQuery) or die(mysql_error());
$preNum = mysql_num_rows($preRes);
I use a WHILE loop with a mysql_fetch_assoc:
while($preRow = mysql_fetch_assoc($preRes))
{
echo '<tr>'
echo '<td>'.$preRow[BOL_NUMBER].'</td>';
echo '<td>'.$preRow[CONTAINER_NUMBER].'</td>';
echo '<td>'.$preRow[ANOTHER_COLUMN].'</td>';
echo '</tr>'
}
}
echo '</tbody></table>';
?>
The query actually works. Problem is, it only returns 1 record, and it's always the last record. The user could select 4 records, but only the last record is returned in the table.
I tried to use the same query and paste it inside the first FOR loop. I echoed out the query and it displayed the same amount of times as the number of array values, but will only return data for the last record.
I do not understand what I am doing wrong. I just want to display data for each value from the array.
Edit
Here is what the code looks like when I throw the query in the first FOR loop:
echo "<table class='table table-bordered'><thead><tr><th>BOL</th><th>Container</th></tr></thead><tbody>";
for($i = 0; $i < $count; $i++)
{
$bol = $bolArray[$i];
$container = $containerArray[$i];
$preQuery = "SELECT BOL_NUMBER, CONTAINER_NUMBER FROM `intermodal_main_view` WHERE BOL_NUMBER = '". $bol ."' AND CONTAINER_NUMBER = '".$container."'";
$preRes = mysql_query($preQuery) or die();
$preNum = mysql_num_rows($preRes);
while($preRow = mysql_fetch_assoc($preRes))
{
echo '<tr>';
echo '<td>'.$preRow[BOL_NUMBER].'</td>';
echo '<td>'.$preRow[CONTAINER_NUMBER].'</td>';
echo '</tr>';
}
}
echo "</tbody></table>";
I think you can use "IN" if your POST vars are comma separated.
$preQuery = "
SELECT * FROM mainTable
WHERE CONTAINER IN ($_POST['CONTAINER'])
AND BOL IN ($_POST['BOL'])
";
$preRes = mysql_query($preQuery) or die(mysql_error());
$preNum = mysql_num_rows($preRes);
Then go to your while loop....
This would omit the need for creating an array and looping it.
Also, you need to switch to PDO for your query, and switch to parameter binding. It will take all of an hour to learn.
What I have is a custom admin page within Wordpress where the user can add names/titles/mp3's which all gets entered into the database. On the same page, I also have it select all the entries from the database and list them with checkboxes next to them and I'm trying to get it to delete the checked entries from the database using an array. This what I have so far:
$songs = $_POST['song'];
$num = count($songs);
for($i=0; $i < $num; $i++){
$sql = "DELETE FROM song_list WHERE title = '".$songs[]."'";
echo $sql;
var_dump($songs);
}
When I dump $songs, it has all the correct data, but when I try to pull it and add it to the query, I keep getting nothing. It's not an associative array, so I tried $songs[0] and $songs[1], but I get nothing.
Any insight would be appreciated, thank you.
EDIT:
var_dump
array(3) { ["Forget You"]=> string(2) "on" ["DJ Got Us Falling in Love"]=> string(2) "on" ["Blurred Lines"]=> string(2) "on" }
Also, I tried adding $i ($songs[$i]). It just comes out as title = ''
Your missing the array index:
$songs[$i]
Turns into:
$songs = $_POST['song'];
$num = count($songs);
for($i=0; $i < $num; $i++){
$sql = "DELETE FROM song_list WHERE title = '".$songs[$i]."'";
echo $sql;
}
An more elegant way is to use a foreach loop:
$songs = $_POST['song'];
foreach($songs as $song) {
$sql = "DELETE FROM song_list WHERE title = '".$song."'";
echo $sql;
}
An even more elegant way is to use prepared statements (with PDO):
// Prepare statement
$stmt = $dbh->prepare('DELETE FROM song_list WHERE title = :song');
$songs = $_POST['song'];
foreach($songs as $song) {
// Bind and execute
$stmt->bindParam(':song', $song);
$stmt->execute();
}
Just to make it much simpler and shorter - one-liner :)
$sql = "DELETE FROM song_list " .
"WHERE title IN ('" . implode("','", $_POST['song']) . "')";
Things to note:
Be aware of SQL injection attacks - never ever concatenate user input strings ($_GET, $_POST etc.) directly into SQL!
Deleting by title is very bad solution, because if you'll have in title for example symbol ', then your SQL will break. That's why in SQL id fields are invented :)
Adding $i to your array and you will get the value at the given place.
But you can write your code like this :
if(isset($_POST['song']) {
foreach($_POST['song'] as $key => $title) {
$sql = "DELETE FROM song_list WHERE title = '".$title."'";
echo $sql;
}
}
the foreach doesn't seem to work correctly in which the last value selected is working but not all.
The array is selected from here:
<fieldset>
<legend>status:</legend>
<?php foreach ($statuss as $status): ?>
<div><label for="status<?php hscout($status['id']);
?>"><input type="checkbox" name="statuss1[]"
id="status<?php hscout($status['id']); ?>"
value="<?php hscout($status['id']); ?>"<?php
if ($status['selected'])
{
echo ' checked="checked"';
}
?>/><?php hscout($status['description']); ?></label></div>
<?php endforeach; ?>
</fieldset>
The index is as follows:
if (isset($_POST['statuss1']))
{
foreach ($_POST['statuss1'] as $status1)
{
$a = mysqli_real_escape_string($link, $status1);
$sql = "SELECT b FROM C WHERE d ='$a'";
$result = mysqli_query($z, $sql);
if (!$result)
{
$error = 'Still not working you.....';
include 'error.html.php';
exit();
}
$selected1s = array();
while ($row = mysqli_fetch_array($result))
{
$selected1s[] = $row['b'];
}
}
}
the $selected1s[] works only if one variable is selected. If multiple variables are selected, the last variable is parsed through.
Every time through the foreach loop that fetches the selected items, you say $selected1s = array(), which clears out the array you're using to accumulate them.
Take the line that says $selected1s = array(); and move it to before the foreach loop, if you just want to get this code working.
There's a way to build one query that gets all the rows at once, though. That typically beats the pants off doing a whole bunch of queries for one item each.
$selected1s = array();
if (!empty($_POST['statuss1'])) {
// Create a function that SQL-escapes and quotes an ID...
// (Note: requires PHP 5.3+)
$sqlify = function($id) use ($link) {
return "'" . mysqli_real_escape_string($link, $id) . "'";
};
// and apply it to the array to get back a list of SQL-ready values
$ids = array_map($sqlify, $_POST['statuss1']);
// string them together as a comma-separated list
$ids_sql = implode(',', $ids);
// and say `d IN (the list)`
$sql = "SELECT b FROM c WHERE d IN ($ids_sql)";
... do the query, fetch results into $selected1s
}
(This is the part where i'd normally advocate prepared statements and tell you to use them. Which you should, in most cases. For IN queries or the equivalent OR queries, though, they tend to suck.)
I am trying to pass id to second page which I am selecting from another table but the below code isn't working. When I do var_dump I can see that the values are what I want but the rows for main query don't show up(The title and image aren't being displayed).
I have two queries in which the one is inside the other one. Can someone help me out? The main query works fine if I get rid of the while loop of the second query.
$paginate = new pagination($page, "SELECT * FROM table1 where title != '' ORDER BY id desc" , $options);
}
}
catch(paginationException $e)
{
echo $e;
exit();
}
if($paginate->success == true)
{
$result = $paginate->resultset->fetchAll();
foreach($result as $row)
{
$dx = $row['image_one'];//image_one from main query
//second query
$item = $mydb->prepare("select * from table2 where imageone = ?");
$item->bind_param('s', $dx);
$item->execute();
$item_res = $item->get_result();
while($row = $item_res->fetch_assoc()){
$rx = $row['id'];
var_dump($rx);
} //the rows below aren't being displayed
$path = 'images/';
echo "<a href='second.php?title=".urlencode($row['title'])." &item=".$row['id']."&id=".$rx."'>"."<img src='".$path."".$row['image_one']."'/></div>"."</a>";
}
Try this:
echo "<a href='second.php?title="'.urlencode($row['title']).'" &item="'.$row['id'].'"&id="'.$rx.'"'>"."<img src='"'.$path.'"".$row['image_one']."'/></div>"."</a>";
use ' ' around var name
You are reassigning $row in your while loop once it exits $row is null.
Try this instead:
while($item_row = $item_res->fetch_assoc()) {
$rx = $item_row['id'];
}
Also, instead of nested queries you should try using a join.