Input fields based on how many results in SELECT command - php

Is there an appropriate way to get input forms based on how many results there are from your SELECT? I have this, but when it gets posted to the next page only the last result appears.
<?php
$query = sprintf("SELECT promocost FROM Items, Promotions, Vendor_Prices, Vendors
WHERE Items.itemid = Promotions.itemid AND
Vendors.vendorid = Promotions.vendorid AND
Vendor_Prices.vendorid = Vendors.vendorid AND
Vendor_Prices.itemid = Items.itemid AND
promoid = '$promoid'");
$result =mysql_query($query);
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}
while($row = mysql_fetch_assoc($result)) {
$models = $row['promocost'];
echo "<input type='text' name='promocost[]'/>";
}
?>
EDIT:
Took out unnecessary variable.
<?php
$query = sprintf("SELECT promocost FROM Items, Promotions, Vendor_Prices, Vendors
WHERE Items.itemid = Promotions.itemid AND
Vendors.vendorid = Promotions.vendorid AND
Vendor_Prices.vendorid = Vendors.vendorid AND
Vendor_Prices.itemid = Items.itemid AND
promoid = '$promoid'");
$result =mysql_query($query);
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}
while($row = mysql_fetch_assoc($result)) {
echo "<input type='text' name='promocost[]'/>";
}
?>

Related

PHP: Loop looping through result set

I am having a huge issue looping through results, These two queries work hand in hand to check if a restaurant is open today. My problem is i have restaurants, id 1-5(more in the future). But the loop seems to only get restaurant id 5. I have read many posts on here and it seems like i am doing the right thing. But i cannot seem to loop to get the other restaurant id's.
I am blocked now, newbie who is very open to any suggestions or advise.
$sel = "SELECT Rest_Details.Resturant_ID,Delivery_Pcode.Pcode,Delivery_Pcode.Restaurant_ID
FROM Rest_Details INNER JOIN Delivery_Pcode
ON Delivery_Pcode.Restaurant_ID=Rest_Details.Resturant_ID
WHERE Delivery_Pcode.Pcode LIKE'$searchP'";
$res = $dbc->query($sel);
if (!$res) {
echo "invalid query '" . mysqli_error($dbc) . "\n";
}
$i=1;
while ($row_res = $res->fetch_array()) {
$rest_ = $row_res['Resturant_ID'];
$i++;
}
date_default_timezone_set("Europe/London");
$daynum = jddayofweek(unixtojd());
$query = "SELECT *
FROM Opening_hrs WHERE
Restaurant_ID = $rest_
AND Day_of_week = $daynum";
$run_qu = $dbc->query($query);
if ($run_qu->num_rows > 0) {
while ($row_qu = $run_qu->fetch_assoc()) {
$message = "open" . $row_qu["Open_time"] . "</br>";
}
} else {
$message = $message . "close" . $row_qu["Closing_time"] . "</br>";
}
You could either output whatever you want to within your loop or build-up an output string because the value of $rest_ will always be the last value in the loop and i don't think that's what you want... Again you are doing the same with $message. And I am willing to bet that this is what you want to do:
<?php
date_default_timezone_set("Europe/London");
$sel = "SELECT Rest_Details.Resturant_ID,Delivery_Pcode.Pcode,Delivery_Pcode.Restaurant_ID
FROM Rest_Details INNER JOIN Delivery_Pcode
ON Delivery_Pcode.Restaurant_ID=Rest_Details.Resturant_ID
WHERE Delivery_Pcode.Pcode LIKE'$searchP'";
$res = $dbc->query($sel);
if (!$res) {
echo "invalid query '" . mysqli_error($dbc) . "\n";
}
$i=1;
while ($row_res = $res->fetch_array()) {
$rest_ = $row_res['Resturant_ID'];
$i++; // <== YOU DON'T NEED THIS VARIABLE....
// GET THE DATES WITHIN THE LOOP...
$daynum = jddayofweek(unixtojd());
$query = "SELECT *
FROM Opening_hrs WHERE
Restaurant_ID = $rest_
AND Day_of_week = $daynum";
$run_qu = $dbc->query($query);
if ($run_qu->num_rows > 0) {
while ($row_qu = $run_qu->fetch_assoc()) {
$message = "open" . $row_qu["Open_time"] . "</br>";
}
} else {
$message = $message . "close" . $row_qu["Closing_time"] . "</br>";
}
}
I think this is what you are trying to do.
// $searchP should be checked to prevent SQL injection.
$sel = "SELECT Rest_Details.Resturant_ID, Delivery_Pcode.Pcode,
Delivery_Pcode.Restaurant_ID
FROM Rest_Details INNER JOIN Delivery_Pcode
ON Delivery_Pcode.Restaurant_ID = Rest_Details.Resturant_IDW
WHERE Delivery_Pcode.Pcode LIKE '$searchP'";
$res = $dbc->query($sel);
if (!$res) {
echo "invalid query '" . mysqli_error($dbc) . "\n";
}
// set these once as they don't change
date_default_timezone_set("Europe/London");
$daynum = jddayofweek(unixtojd());
// $i=1; - not required, never used
// loop over the original results
while ($row_res = $res->fetch_array()) {
$rest_ = $row_res['Resturant_ID'];
//$i++; not used
// check for a match
$query = "SELECT * FROM Opening_hrs
WHERE Restaurant_ID = $rest_
AND Day_of_week = $daynum";
$run_qu = $dbc->query($query);
if ($run_qu->num_rows > 0) {
// at least one match
while ($row_qu = $run_qu->fetch_assoc()) {
$message = "open" . $row_qu["Open_time"] . "<br />";
$message .= "close" . $row_qu["Closing_time"] . "<br />";
}
} else {
// no matches
$message = "No results for <i>$daynum</i>.";
}
}
It should be possible to get the details in a single query, but I would need to see your SQL tables for that (and you did not ask for that too :]).
Also, it is <br> or <br />, not </br>.

PHP array implode keys and values to function

I'm not too familiar with PHP arrays, I have the following code that generates query to output the results needed.
$allstore = $_POST['store'];
function createSelect($allstore)
{
if (empty($allstore))
return "";
$querySelect = "";
$queryJoin = "";
$baseTable = "";
foreach ($allstore as $store => $value) {
if (!$querySelect) {
$baseTable = $store;
$querySelect = "SELECT " . $store . ".item_no, " . $store . ".actual_price, " . $store . ".selling_price, " . $store . ".qty as " . $store;
} else {
$querySelect .= ", " . $store . ".qty as " . $store;
$queryJoin .= "
INNER JOIN " . $store . " ON " . $baseTable . ".item_no = " . $store . ".item_no";
}
}
$querySelect .= " FROM " . $baseTable;
$query = $querySelect . $queryJoin;
return $query;
}
//Stores to be shown
$allstore = ['s_M9' =>0 , 's_M10' =>1];
$query = (createSelect($allstore));
$result = mysql_query($query);
//rest of code...
As you can see above, at the very top there is $allstore = $_POST['store']; Which collects values based from previous form POST method that has checkbox with the name=store[] .
Now According to the function shown, if I create my own keys and values like this
$allstore = ['s_M9' =>0 , 's_M10' =>1];
the output shows exactly what i'm looking for. But the problem goes on how to let $allstore implode those stores s_M9, s_M10 based on what the user has selected on the previous page ( checkbox )? I mean, the user can select either one of the stores or Both stores . How can I implode the checked results between those brackets without inserting them manually?
Thank You
Edit :
<?php
echo "<form action='somewhere.php' method='POST'>";
$query = "SELECT * from stores_list ORDER BY short Asc";
$result = mysql_query($query);
if(mysql_num_rows($result)>0){
$num = mysql_num_rows($result);
for($i=0;$i<$num;$i++){
$row = mysql_fetch_assoc($result);
echo "<input type=checkbox name=store[] value={$row['short']} style='width:20px; height:20px;'>{$row['short']}";
}
}
else{
//No Stores Available
echo "No Stores Found !";
}
echo "</td><input type='submit' value='Search'/></form>";
$allstore = [];
if (!empty($_POST['store'])) {
foreach ($_POST['store'] as $value) {
$allstore[$value] = 1; // or 0, it doesn't matter because your function adds all the keys
}
}
$query = (createSelect($allstore));
$result = mysql_query($query);
And of course you have to take care of your createSelect function to avoid SQL Injections, please read here

PHP, Mysql query different tables in one function

function getDepartmentAndCondition($dep, $userid, $cond) {
$result = mysql_query("SELECT * FROM department WHERE ID='$dep'");
while($row = mysql_fetch_array($result))
{
$DepConInfo['Department'] = $row['Department'];
}
$userName = mysql_query("SELECT * FROM users WHERE FacebookID = '$userid'") or die ("<hr>error in SQL query: " . mysql_error() . "<hr>");
while($row = mysql_fetch_array($username)) {
$DepConInfo['Name'] = $row['name'];
}
$result2 = mysql_query("SELECT * FROM condition WHERE ID= '$cond' ")
or die("<hr>error in SQL query: " . mysql_error() . "<hr>");
while($row2 = mysql_fetch_array($result2))
{
$DepConInfo['Condition'] = $row2['Condition'];
}
return $DepConInfo;
}
$dep, $userid, and $cond are all ints. the first one $DepConInfo['Department'] is returning the right string, but the other two fail with the error
Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in ...
ok I rewrote the function
function getCondition($cond) {
$query = "SELECT * FROM condition WHERE ID = '$cond' ";
$sql = mysql_query($query);
if (!$sql) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}
while($row2 = mysql_fetch_array($sql))
{
$condition = $row2['Name'];
}
return $condition;
}
but I'm still getting an error:
Invalid query: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'condition WHERE id = '1'' at line 1 Whole query: SELECT * FROM condition WHERE ID = '1'
the table "condition" has two columns "ID" and "Name".
while($row = mysql_fetch_array($username)) {
PHP is case-sensitive: you have $username with wrong caps - should be $userName
Additionally, based on your naming convention in the first and third queries
$DepConInfo['Name'] = $row['name'];
is probably incorrect and should be capitalized as $row['Name']
function getDepartment($dep) {
$sql = "SELECT * FROM department WHERE ID = '$dep'";
$result = mysql_query($query);
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
$row = mysql_fetch_row($result);
$department = $row['Department'];
}
return $department;
}
function getName($userid) {
$sql = "SELECT * FROM users WHERE FacebookID = '$userid'";
$result = mysql_query($sql);
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
$row = mysql_fetch_row($result);
$user_name = $row['Name'];
}
return $username;
}
function getCondition($cond) {
$sql = "SELECT * FROM condition WHERE id = '$cond'";
$result = mysql_query($sql);
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
$row = mysql_fetch_row($result);
$condition = $row['Condition'];
}
return $condition;
}
$department = getDepartment($dep);
$username = getName($userid);
$condition = getCondition($cond);
I'm writing this from my head so I did not test it, but it should work or at least get you on your way. If not let me know. Mind capitalization using caps in your dbase table and column names can make things more confusing. Use $sql to store your query, use $result to store the result. This is more descriptive. Good luck!

querying multiple rows from stored results

i'll try my best to explain the situation but i'm fairly new to php and mysql so im a tad rusty.
What im specificity trying to achieve is a query resulting in the echo of "codes" that a customer has purchased.
My problem lies when a customer orders more then one item, each customer is given an order number (in the example: 1081) which links to a order_list db which lists which products they have purchased. So in this example 1081 ordered 3 products (1,11,14) this is shown in the database as..
od_id | pd_id
----------------
1081 | 1
1081 | 11
1081 | 14
So when i successfully query 1081 it brings back 3 rows of results. This is fine for this example and the quantity query but i only get one result back on the final sql query when i need all three results.
Here is my test code so far:
//Get order IDS
$sqlid = "SELECT pd_id FROM tbl_order_item WHERE od_id = 1081";
$result = mysql_query($sqlid);
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $sqlid;
die($message);
}
while($row = mysql_fetch_assoc($result)) {
$ids[] = $row['pd_id'];
}
foreach ($ids as $id) {
echo $id . "<br />";
}
//Get order Qtys
$sqlqty = "SELECT od_qty FROM tbl_order_item WHERE od_id = 1081";
$result = mysql_query($sqlqty);
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $sqlqty;
die($message);
}
while($row = mysql_fetch_assoc($result)) {
$qtys[] = $row['od_qty'];
}
foreach ($qtys as $qty) {
echo $qty . "<br />";
}
//Get Order Codes
$sqlcode = "SELECT od_code FROM tbl_order_code WHERE pd_id = $id LIMIT $qty";
$result = mysql_query($sqlcode);
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $sqlcode;
die($message);
}
while($row = mysql_fetch_assoc($result)) {
$codes[] = $row['od_code'];
}
foreach ($codes as $code) {
echo $code . "<br />";
}
The current results on the page are this:
1 //Three results from "pd_id" (What the customer ordered)
11 //
14 //
1 //Three results from "od_qty" (How many the customer ordered
1 //
2 //
YYXY-YYXY-YYXY-YYXW //The first code result with two codes as there was 2 qty for product 14
YYXY-YYXY-YYXY-YYXX //
my test page you can view the above here.
I hope i made sense, basically i need the final "$sqlcode" query to process all the rows from the previous query not just the first.
Thanks!
Key:
pd_id //product id
tbl_order_item //ordered items table
od_id //order id
od_qty //quantity of each product
od_code //order codes
tbl_order_code //codes table each code is related to the pd_id
wrap the last sql in a foreach so that it gets executed for each $id
you should really read up on sql joins, as could do this entire script as one $sql stmt
foreach ($ids as $id) {
$sqlcode = "SELECT od_code FROM tbl_order_code WHERE pd_id = $id LIMIT $qty";
$result = mysql_query($sqlcode);
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $sqlcode;
die($message);
}
while($row = mysql_fetch_assoc($result)) {
$codes[] = $row['od_code'];
}
}
here is an attempt at doing it with a join (if that helps any)
// query data
$order_id = 1081;
$sql = "SELECT tbl_order_item.pd_id, tbl_order_item.od_qty, tbl_order_code.od_code FROM tbl_order_item JOIN tbl_order_code ON
tbl_order_code.pd_id=tbl_order_item.pd_id
WHERE tbl_order__item.od_id = $order_id";
$result = mysql_query($sql);
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $sql;
die($message);
}
while($row = mysql_fetch_assoc($result)) {
printf("Order ID: %s - Product ID: %s - Qty: %s - Code: %s<br />", $order_id, $row['pd_id'], $row['od_qty'], $row['od_code']);
}

iterate through fb:random

does anyone know how i would fill data from mysql database in fb:random and iterate through it, to pick a random quote?
fb:random
$facebook->api_client->fbml_setRefHandle('quotes',
'<fb:random>
<fb:random-option>Quote 1</fb:random-option>
<fb:random-option>Quote 2</fb:random-option>
</fb:random>');
mysql data:
$rowcount = mysql_result($result, 0, 0);
$rand = rand(0,$rowcount-1);
$result = mysql_query("SELECT cQuotes, vAuthor, cArabic, vReference FROM thquotes LIMIT $rand, 1", $conn)
or die ('Error: '.mysql_error());
$row = mysql_fetch_array($result, MYSQL_ASSOC);
if ( !$row ) {
echo "Empty";
}
else{
$fb_box = "<p>" . h($row['cArabic']) . "</p>";
$fb_box .= "<p>" . h($row['cQuotes']) . "</p>";
$fb_box .= "<p>" . h($row['vAuthor']) . "</p>";
$fb_box .= "<p>" . h($row['vReference']) . "</p>";
}
Generally, what I do when I want to pick up a random quote or other piece of data is I select all of the ids in the database, feed them into an array, and then choose at random from the array. Then use the id to pick out the one you want.
For example:
$sql = "SELECT `id` FROM `quotes`;";
$result = mysql_query($sql);
$count = mysql_num_rows($result);
$id = rand(1, $count);
$sql = "SELECT `text`,`author` FROM `quotes` WHERE `id`='$id' LIMIT 1;";
$result = mysql_query($sql);
$quote = mysql_fetch_assoc($result);

Categories