php/MySQL Query Loop only using first value - php

I'm writing an online shop, and I've come across an issue with a function which I'm hoping someone can help me with. The function is designed to determine if the product exists in alternate formats and link to those from the sidebar. For example, a product may exist in DVD, Blu-Ray and Digital Download.
This is my function code:
function formatExists($format, $pid) {
global $conn; global $dbname; global $loginid;
mysql_select_db($dbname, $conn);
// Get author and description of the requested product
$query = "SELECT description, author FROM products WHERE productid = $pid";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)) {
$author = $row['author'];
$description = $row['description'];
}
// Find other products with the same description & author in requested format
$query = "SELECT productid FROM products WHERE format = $format AND description = '$description' AND author = '$author'";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)) {
$rpid = $row['productid'];
}
if($rpid) {
return $rpid;
} else {
return 0;
}
}
I've written a loop in another part of the code, which gets all of the formats from the database, then runs the above function on them to try to find out which formats the product is available in:
$query = "SELECT formatid, description, postage FROM formats";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)) {
$id = $row['formatid'];
$desc = $row['description'];
$post = $row['postage'];
... STUFF ...
}
When '... STUFF ...' was '$bodycontent .= $id';" it echoed every format ID in the database, this is the behavior I expected. However, when I changed it to:
$pid = formatExists($id, $productid);
if($pid) {
$query = "SELECT price FROM products WHERE productid = $pid";
$result = mysql_query($query);
$pricedata = mysql_fetch_array($result, MYSQL_ASSOC);
$pprice = $pricedata['price'];
$bodycontent .= "<span>";
if($pid != $productid) {
$bodycontent .= "<a href='$siteroot/index.php?page=product&id=$pid'>";
}
$bodycontent .= "$desc - &dollar;$pprice";
if($postage) {
$bodycontent .= " + P&P";
}
if($pid != $productid) {
$bodycontent .= "</a>";
}
$bodycontent .= "</span>";
}
It stopped operating in the desired fashion, and just started returning the response for the first format ID.
If I manually change 'formatExists($id, $productid)' to 'formatExists(2, $productid)' then the price and link update, so the function is working correctly. For some reason, however, it's not running once for each category, it's just running once in my loop.
Any help will be much appreciated.

the function you are using is wrong !!! i mean -> mysql_fetch_array
you should change mysql_fetch_array with mysql_fetch_assoc
to see the true result.

Related

display array of items from DB php/MySQL

I am unsure how to display the items field. I want to display two tables of data; one that has all the items from a user and one with all the items to teh user. All I've been able to output is the item_id's(I pasted the html below). How to get all the item info from these ids, which is in the item table, and populate the HTML?
trans table
item table
$from = 1;
$sql = $db->prepare("SELECT * FROM test WHERE from_id = :id");
$sql->bindValue(':id', $from);
$sql->execute();
while($row = $sql->fetch())
{
$t =$row['items'];
$u =$row['to_id'];
$trans .= "<tr><th>Items</th><th>To</th><th>Status</th></tr><tr><td>$t</td>
<td>$u</td></tr>";
}
HTML DISPLAY
Try this!
<?php
$from = 1;
$sql = $db->prepare("SELECT * FROM test WHERE from_id = :id");
$sql->bindValue(':id', $from);
$sql->execute();
while($row = $sql->fetch())
{
$t =$row['items'];
$u =$row['to_id'];
$itemIDs = #explode(",", $t);
$items = array();
foreach($itemIDs as $ID){
$sqlItem = $db->prepare("SELECT itemname FROM itemtable WHERE itemid = :itemid");
$sqlItem->bindValue(':itemid', $ID);
$sqlItem->execute();
$itemname ='';
while($rowItems = $sqlItem->fetch())
{
$itemname .=$rowItems['itemname'];
}
$items[$t] = $itemname;
}
$trans .= "<tr><th>Items</th><th>To</th><th>Status</th></tr><tr><td>$items[$t]</td> <td>$u</td></tr>";
}
below is my code for testing,
<?php
$from = 1;
$sql = mysqli_query($db,"SELECT * FROM test WHERE from_id = '$from'");
while($row = mysqli_fetch_array($sql))
{
$t =$row['items'];
$u =$row['to_id'];
$itemIDs = #explode(",", $t);
$itemname ='';
foreach($itemIDs as $ID){
$sqlItem = mysqli_query($db, "SELECT itemname FROM itemtable WHERE item_id = '$ID'");
while($rowItems = mysqli_fetch_array($sqlItem))
{
$itemname .= $rowItems['itemname'].', ';
}
$items[$u] = $itemname;
}
$trans .= "<tr><th>Items</th><th>To</th><th>Status</th></tr><tr><td>$items[$u]</td> <td>$u</td></tr>";
}
echo "<table>".$trans."</table>";
?>
Note : change my queries with ur need
in ur while loop
while($row = $sql->fetch())
{
$items_array = array();
$items_array = explode(",",$row["items"]);
foreach($items_array as $key => $value)
{
//modify ur query according to ur need
$query3 = "SELECT item_name
FROM item_table
WHERE item_id =".$value." ";
$result3 = mysql_query($query3);
$row3 = mysql_fetch_assoc($result3);
$item_name .= $row3['subcategory_name'].", ";
}
}
now ur array will contains item_id,
use foreach loop in ur while loop and get info of Item from item table with item_id from expolode function
Within while you will have to fire new query that will get the information of items.
For eg :
"SELECT * FROM item_info_table WHERE id IN (id1,id2, id3)"
It will return you the item information corresponding to the id's.
The data is not normalized. Get it to normalize and you'll have a much better and cleaner solution.

function call inside a function in php not working

This code is a function calling a function in php. The function call is never called.
function saveSubject(){
$result = mysql_query("select * from term where description='".$_POST['term']."'");
$row = mysql_fetch_array($result, MYSQL_NUM);
global $term;
$term = $row[0];
$x=1;
while(isset($_POST['subCode'.$x])and isset($_POST['subTitle'.$x]) and isset($_POST['subUnit'.$x])){
$code = $_POST['subCode'.$x];
$title = $_POST['subTitle'.$x];
$unit = $_POST['subUnit'.$x];
$query = "INSERT INTO subject(subcode, description, units, termid)
VALUES('".$code."','".$title."',".$unit.",".$term.")";
$result = mysql_query("SELECT * from subject where subcode='".$code."'");
if(mysql_num_rows($result) > 0){
$message = "Subject Code : ".$code;
prompt($message);
}else{
mysql_query($query);
savePre($code, $x);
}
$x++;
}
}
function savePre($code, $y){
$pre = mysql_query("SELECT subject.subcode from subject left join term
on term.termid=subject.termid
left join curriculum on term.termid = curriculum.curriculumid
where term.courseid =".$_POST['course']);
while($row = mysql_fetch_array($pre, MYSQL_NUM)){
$c = $row[0].$y;
if(isset($_POST[$c])){
$result = mysql_query("Select * from pre_requisite where pre_requisites=".$row[0]."and subject=".$code);
if(mysql_num_rows($result) > 0){
$message = "";
}else{
mysql_query("INSERT into pre_requisites(pre_requisite, subject)
values (".$row[0].", ".$code.")");
}
}
}
}
Calling function savePre() in saveSubjec() but the calling is not working. I cannot find out what is wrong. Please help!
Simple...
You code is
$query = "INSERT INTO subject(subcode, description, units, termid)
VALUES('".$code."','".$title."',".$unit.",".$term.")";
$result = mysql_query("SELECT * from subject where subcode='".$code."'");
if(mysql_num_rows($result) > 0)
{
$message = "Subject Code : ".$code;
prompt($message);
}else{
mysql_query($query);
savePre($code, $x);
}
from above code you can imagine that you are inserting record to database and then selecting that record using subcode match where condition so it will always return 1 as output so your else condition will never get execute.
That's the reason why you are not able to call savePre function.
You want to define savePre() function above the saveSubject() function. Use this.
function savePre($code, $y)
{
$pre = mysql_query("SELECT subject.subcode from subject left join term
on term.termid=subject.termid
left join curriculum on term.termid = curriculum.curriculumid
where term.courseid =".$_POST['course']);
while($row = mysql_fetch_array($pre, MYSQL_NUM))
{
$c = $row[0].$y;
if(isset($_POST[$c]))
{
$result = mysql_query("Select * from pre_requisite where pre_requisites=".$row[0]."and subject=".$code);
if(mysql_num_rows($result) > 0){
$message = "";
}else{
mysql_query("INSERT into pre_requisites(pre_requisite, subject)
values (".$row[0].", ".$code.")");
}
}
}
}
function saveSubject()
{
$result = mysql_query("select * from term where description='".$_POST['term']."'");
$row = mysql_fetch_array($result, MYSQL_NUM);
global $term;
$term = $row[0];
$x=1;
while(isset($_POST['subCode'.$x])and isset($_POST['subTitle'.$x]) and isset($_POST['subUnit'.$x]))
{
$code = $_POST['subCode'.$x];
$title = $_POST['subTitle'.$x];
$unit = $_POST['subUnit'.$x];
$result = mysql_query("SELECT * from subject where subcode='".$code."'");
if(mysql_num_rows($result) > 0){
$message = "Subject Code : ".$code;
prompt($message);
}
else
{
$query = "INSERT INTO subject(subcode, description, units, termid)
VALUES('".$code."','".$title."',".$unit.",".$term.")";
mysql_query($query);
savePre($code, $x);
}
$x++;
}
}

MYSQL Results; no records found statement [duplicate]

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
Display Data From MYSQL; SQL statement error
I have the code below displaying data from a MYSQL database (currently looking into sql injection issue) I need to insert an error message when no results are found...not sure where to position this! I have tried the code if( mysql_num_rows($result) == 0) {
echo "No row found!" but keep on gettin syntax errors, does anyone know the correct position in the code for this?
--
require 'defaults.php';
require 'database.php';
/* get properties from database */
$property = $_GET['bedrooms'] ;
$sleeps_min = $_GET['sleeps_min'] ;
$availability = $_GET['availability'] ;
$query = "SELECT * FROM `properties` WHERE bedrooms = '{$bedrooms}' AND sleeps_min = '{$sleeps_min}' AND availability = '{$availability}'";
$row=mysql_query($query);
$result = do_query("SELECT * FROM `properties` WHERE bedrooms = '{$bedrooms}' sleeps_min = '{$sleeps_min}' AND availability = '{$availability}'", $db_connection);
while ($row = mysql_fetch_assoc($result))
{
$r[] = $row;
}
?>
I have found few errors in your code that in line
$query = "SELECT * FROM `properties` WHERE bedrooms = '{$bedrooms}' AND sleeps_min = '{$sleeps_min}' AND availability = '{$availability}'";
$row=mysql_query($query);
You use bedrooms = '{$bedrooms}' but $bedrooms is not variable in whole cod it must be $preopery. I have made a few changes in your code given below please try it.
<?php
require 'defaults.php';
require 'database.php';
/* get properties from database */
/*if get $_GET['bedrooms'] value else ''*/
if (isset($_GET['bedrooms'])) {
$property = $_GET['bedrooms'];
} else {
$property = '';
}
/*if get $_GET['sleeps_min'] value else ''*/
if (isset($_GET['sleeps_min'])) {
$sleeps_min = $_GET['sleeps_min'];
} else {
$sleeps_min = '';
}
/*if get $_GET['availability'] value else ''*/
if (isset($_GET['availability'])) {
$availability = $_GET['availability'];
} else {
$availability = '';
}
$query = "SELECT * FROM `properties` WHERE bedrooms = '" . $property . "' AND sleeps_min = '" . $sleeps_min . "' AND availability = '" . $availability . "'";
$result = mysql_query($query) or die(mysql_error());
if ($result) {
while ($row = mysql_fetch_assoc($result)) {
$r[] = $row;
}
}
?>
Do var_dump($GET_) to debug whether you are getting valid strings. If any of these are blank, the query will try to match blank values instead of NULL. You should prevent this by doing:
if(!$_GET['bedrooms'] || $_GET['bedrooms'] == ''){
$property = 'NULL';
}//repeat for all three
$query = "SELECT * FROM `properties` WHERE 'bedrooms' = '$bedrooms' AND 'sleeps_min' = '$sleeps_min' AND 'availability' = '$availability'";
Instead of:
while ($row = mysql_fetch_assoc($result)) {
$r[] = $row;
}
You can simply do:
$r = mysql_fetch_array($query);
But enclose that in a conditional to see if your query found anything:
if(mysql_affected_rows() > 0){
//your code here will execute when there is at least one result
$r = mysql_fetch_array($query);
}
else{//There was either nothing or an error
if(mysql_affected_rows() == 0){
//There were 0 results
}
if(mysql_affected_rows() == -1) {
//This executes when there is an error
print mysql_error(); //not recommended except to debug
}
}

Data insert problem within foreach loop

The problem is that only some of the XML data is being Inserted into the my mysql database. 10 results are supposed to be entered into the database but it varies between 2 and 8 results. I have no idea why it is doing this and I have tried adding a sleep function to slow the script down, but the data that is inserted into the data base is never as much as when I echo it out on screen. Any help would be much appreciated..
function post_to_db($xml,$cat_id){
if ($xml->Items->Request->IsValid == 'True'){
$xml = $xml->Items->Item;
foreach($xml as $item){
$asin = (string)$item->ASIN;
$title = (string)$item->ItemAttributes->Title;
$content = (string)
$item->EditorialReviews->EditorialReview->Content;
$sku = (string)$item->ItemAttributes->SKU;
$brand = (string)$item->ItemAttributes->Brand;
$feature = (string)$item->ItemAttributes->Feature;
$model_no = (string)$item->ItemAttributes->Model;
$review = (string)$item->ItemLinks->ItemLink[5]->URL;
$check = "SELECT * FROM `products` WHERE `asin` = '$asin'";
$checked = mysql_query($check);
$numrows = mysql_num_rows($checked);
if ($numrows == 0){
$query = "INSERT INTO `products`".
"(`cat_id`,`asin`,`sku`,`brand`,".
"`model_no`,`title`,`content`,`feature`) ".
"VALUES".
"('$cat_id','$asin','$sku','$brand',".
"'$model_no','$title',".
"'$content','$feature')";
$result = mysql_query($query);
$post_id = mysql_insert_id();
$review_page[] = array($post_id=>$review);
}
}
}
return $review_page;
}
My guess would be some of your variables from XML are creating an invalid query (do they contain quotes?)
Instead of this for each variable:
$asin = (string)$item->ASIN;
Do this instead:
$asin = mysql_real_escape_string((string)$item->ASIN);
If the problem still persists, change your mysql_query line to this for debugging:
$result = mysql_query($query) or die(mysql_error());

Web page not loading with PHP-MySQL code while outputting JSON

I am using the code below to get information from a database and make it into JSON (it may be wrong).
Unfortunately it won't load in my web browser, it just says it's loading but it doesn't finish. Please can you tell me what I am doing wrong.
$query = mysql_query("SELECT * FROM Posts ORDER BY date DESC") or die(mysql_error());
$array = array();
while ($row = mysql_fetch_assoc($query)) {
$array[] = $row;
$postID = $row['id'];
while ($ra = mysql_fetch_assoc(mysql_query("SELECT * FROM Comments WHERE postID = '$postID'"))) {
$array['comments'] = $ra;
}
while ($rd = mysql_fetch_assoc(mysql_query("SELECT * FROM Likes WHERE postID = '$postID'"))) {
$array['likes'] = $rd;
}
}
echo json_encode($array);
You are executing mysql_query in the infinite loop:
on each iteration you query the database, and fetch the first row. Change it to
$res = mysql_query("SELECT * FROM Comments WHERE postID = '$postID'");
if (!$res)
{
// handle error
}
while ($ra = mysql_fetch_assoc($res))
{
....
}
And the same for your second query.

Categories