MySQL Error: query not giving correct data - php

I do a mySQL query to get some data and then (for the purpose of debugging) print it out. In this particular sample there are 5 rows of data and each room_id in the database table has a value. However the print-out only shows the room_id of the first row.
$query_rooms = "SELECT room_id FROM lh_rooms WHERE hid = '$hid'";
$rooms = mysql_query($query_rooms, $MySQL) or die(mysql_error());
$row_rooms = mysql_fetch_assoc($rooms);
$numrows = mysql_num_rows($rooms);
$i = 0;
while ($i < $numrows) {
$room_id=$row_rooms['room_id'][$i];
echo $i." - ".$room_id."<br><br>";
++$i;
}
0 - 2
1 -
2 -
3 -
4 -
Can someone explain what is happening

You are fetching multiple rows.
So, you need to loop over the result set instead of fetching just one time.
Corrected code:
$query_rooms = "SELECT room_id FROM lh_rooms WHERE hid = '$hid'";
$rooms = mysql_query($query_rooms, $MySQL) or die(mysql_error());
$i=0;
while($row_rooms = mysql_fetch_assoc($rooms)) {
$room_id=$row_rooms['room_id'];
echo $i." - ".$room_id."<br><br>";
++$i;
}
Note: Never use mysql_, they are deprecated and will be removed in the upcoming versions. Use mysqli_ or PDO instead.

Try like this
$query_rooms = "SELECT room_id FROM lh_rooms WHERE hid = '$hid'";
$rooms = mysql_query($query_rooms, $MySQL) or die(mysql_error());
$i = 0;
while ($row_rooms = mysql_fetch_assoc($rooms)) {
$room_id=$row_rooms['room_id'];
echo $i." - ".$room_id."<br><br>";
$i++;
}
You are looping $i instead of looping the $row_rooms.

Related

Not able to extract all values of a column in mysql

I am having problem extracting values from a mysql table:
I need to get all values of picname column from a table where uid condition is satisfied.
Now i have two rows where this condition is satisfied but i am getting output only for 1st case. I am not able to get the second row's value. 1st rows value repeats again for second time.
$i = 0;
for($i;$i<2;$i++)
{
$s = "SELECT picname FROM uploaded_data WHERE uid='$uid'";
$que = mysql_query($s,$db);
while($num = mysql_fetch_array($que))
{
echo $name ['picname'];
}
}
Thank You
it should not give you any result you do not have
$name
should be:
$i = 0;
for($i;$i<2;$i++)
{
$s = "SELECT picname FROM uploaded_data WHERE uid='$uid'";
$que = mysql_query($s,$db);
while($num = mysql_fetch_array($que))
{
echo $num['picname'];
}
mysql_free_result($que);
}

How to populate an array from data in a table

I'm writing a very simple seating plan arranger for my sister. All it is, is a database with a list of people attending and each has a table number assigned ($tano)
My PHP is as follows:
$con = mysql_connect('localhost', $dbuser, $dbpass) or die(mysql_error());
$db = mysql_select_db($dbname, $con) or die(mysql_error());
// Get current table no
$tableno = $_GET["t"];
// Current table -> array
$t = array();
$i = 0;
$result = mysql_query('SELECT * FROM plan WHERE tano = $tableno ORDER BY fname');
while($row = mysql_fetch_array($result)) {
$t[$i] = $row;
$i++;
}
// Get other tables (Seats Remaining)
for ($i = 1; $i <= 40; $i++) {
$result = mysql_query("SELECT * FROM plan WHERE 'tano' = $i");
$seatsremaining = 10-mysql_num_rows($result);
if ($seatsremaining == 0) {$d[$i] = "Table ".$i." (No Seats Remaining)";}
else if ($seatsremaining == 1) {$d[$i] = "Table ".$i." (1 Seat Remaining)";}
else if ($seatsremaining >= 2) {$d[$i] = "Table ".$i." (".$seatsremaining." Seats Remaining)";}
}
?>
You can see the rest of the HTML code on www.greenbottleblue.com
The array is not populated and there's an annoying SQL error:
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in /home/greenbot/public_html/index.php on line 18
The table structure is:
In your first query, you are missing quotes around your value:
$result = mysql_query('SELECT * FROM plan WHERE tano = $tableno ORDER BY fname');
This should be:
$result = mysql_query("SELECT * FROM plan WHERE tano = '$tableno' ORDER BY fname");
In your second query, you are using quotes instead of backticks around the column name:
$result = mysql_query("SELECT * FROM plan WHERE 'tano' = $i");
This should be:
$result = mysql_query("SELECT * FROM plan WHERE `tano` = $i");
You should note that your code assumes that the query completed successfully instead of checking. For debugging purposes, you can add:
... or die(mysql_error());
to the end of each of your mysql_query(...) statements to get details about the attempted queries. You should develop a logging strategy for such errors in production code.
Additionally, be aware that using unfiltered user input $tableno = $_GET["t"]; opens the door for SQL injection attacks. Consider updating your code to use parameterized PDO queries, or at least filter your incoming data.

Is there a more efficient way to do this

function countBrand($brand_id, $brand_name) {
$sql = "SELECT brand FROM coupons WHERE expire >= CURRENT_DATE AND brand='".$brand_id."'";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
echo '<li>'.$brand_name.'</li>';
}
function brandCount() {
$sql = "SELECT DISTINCT brand,brand_id,brand_name FROM coupons,coupons_brand WHERE brand=brand_id AND expire >= CURRENT_DATE ORDER BY brand_name";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
$num = mysql_num_rows($result);
echo '<h3>'.$num.' Brands</h3>';
echo '<ul>';
$i = 0;
while ($i < $num) {
$brand_id = mysql_result($result, $i, "brand_id");
$brand_name = mysql_result($result, $i, "brand_name");
countBrand($brand_id, $brand_name);
$i++;
}
echo '</ul>';
}
It works perfectly and gives me the results I am looking for. I am not as strong with sql statements as I would like to be. Is there a way I could do this that would be more efficient, it seems very slow.
Basically, it counts how many brands have coupons, then coupons how many coupons each brand has..
I also, on the same page, do this for categories. There are a few thousand categories and maybe 20,000 coupons.
there are a few php optimisations you could do, but they probably wont save you much time, compared to adding an index to mysql on the correct columns
i have commented some php optimisations below, maybe of interest to you anyway
given the simple nature of the functions, it is not necessary to have 2 functions, and that would save the timecost of calling countBrand(), (although it is a pretty minimal time saving)
function countBrand($brand_id, $brand_name) {
$sql = "SELECT brand FROM coupons WHERE expire >= CURRENT_DATE AND brand='".$brand_id."'";
$result = mysql_query($sql) || die (mysql_error()); // always check for errors
list($brand) = mysql_fetch_row($result);
// fetch row, returns a more concise array then mysql_fetch_array
// $row = mysql_fetch_array($result);
// use commas rather then . when concatenating echo statements
// dots force concatenation before output
echo '<li>',$brand,'</li>';
}
function brandCount() {
$sql = "SELECT DISTINCT brand,brand_id,brand_name FROM coupons,coupons_brand WHERE brand=brand_id AND expire >= CURRENT_DATE ORDER BY brand_name";
$result = mysql_query($sql) || die(mysql_error()); // always check for errors
// $row = mysql_fetch_array($result); // not sure why this is needed
$num = mysql_num_rows($result);
// use commas rather then . when concatenating echo statements
// dots force concatenation before output
echo '<h3>',$num,' Brands</h3>';
echo '<ul>';
// fetch all cols at once, rather then using lots of separate calls to mysql_result
// use mysql_fetch_row as it returns just the ordered values (vs mysql_fetch_assoc, and mysql_fetch_array)
//
while(list($brand, $brand_id, $brand_name) == mysql_fetch_row($result)) {
countBrand($brand_id, $brand_name);
}
// replaced with while loop above
// $i = 0;
// while ($i < $num) {
// $brand_id = mysql_result($result, $i, "brand_id");
// $brand_name = mysql_result($result, $i, "brand_name");
// countBrand($brand_id, $brand_name);
// $i++;
}
echo '</ul>';
}
those enhancements will only give you a minor speed increase
the biggest speed increase you will get is if you call the database less.
currently you select each brand, and then go back and count each brand individually
without knowing the structure of you tables this sql is difficult for me to write, so it is a guess, but it should point you in the right direction
SELECT brand, brand_id, brand_name, COUNT(*) as brandcount
FROM coupons
JOIN coupons_brand ON brand=brand_id
WHERE expire >= CURRENT_DATE
GROUP BY brand, brand_id, brand_name
ORDER BY brand_name
mysql_fetch_array($result,MYSQL_ASSOC);
SELECT SQL_CACHE brand FROM
Profiling query

Select statement within a while statement

First, I coded this, which looks inside a table, gets the last 10 entries, and displays them. The output is as expected, a list of the 10 last entries in the database.
$query = "SELECT dfid FROM downloads_downloads ORDER BY did DESC limit 10";
$dlresult = mysql_query( $query );
$i=0;
$num = mysql_num_rows ($dlresult);
while ($i < $num) {
$dfid= mysql_result($dlresult,$i,"dfid");
echo "<b>filenumber:</b> $dfid <br>";
++$i;
}
But I don't just need the filenumber. I need the actual filename and url from another table. So I added a select statement inside the while statement, using the file number.
But for some reason, this code only displays one filename instead of 10. I know, from the above code, it's getting all 10 file numbers.
$query = "SELECT dfid FROM downloads_downloads ORDER BY did DESC limit 10";
$dlresult = mysql_query( $query );
$i=0;
$num = mysql_num_rows ($dlresult);
while ($i < $num) {
$dfid= mysql_result($dlresult,$i,"dfid");
$query2 = "SELECT file_name, file_name_furl FROM downloads_files WHERE file_id = '$dfid'";
$dlresult2 = mysql_query( $query2 );
$dlfile_name= mysql_result($dlresult2,$i,"file_name");
$dlfile_name_furl= mysql_result($dlresult2,$i,"file_name_furl");
echo "filenumber: $dfid <br>"; //Shows 10, as expected.
echo "filename: $dlfile_name - $dlfile_name_furl <br>"; //Shows only 1?
++$i;
}
I can manually execute the sql statement and retrieve the file_name and file_name_furl from the table. So the data is right. PHP isn't liking the select within the while statement?
Looks like you're only going to ever have 1 row, in your 2nd select statement, because you are just selecting one row, with your where statement.
So, you're only going to ever have row 0 in the 2nd statement, so its only finding row 0 on the first loop. try instead:
$dlfile_name= mysql_result($dlresult2,0,"file_name");
$dlfile_name_furl= mysql_result($dlresult2,0,"file_name_furl");
However, insrtead of making 11 separate queries, try using just one:
$link = new mysqli(1,2,3,4);
$query = "SELECT downloads_downloads.dfid, downloads_files.file_name, downloads_files.file_name_furl FROM downloads_downloads LEFT OUTER JOIN downloads_files ON downloads_files.file_id = downloads_downloads.dfid ORDER BY downloads_downloads.dfid DESC limit 10;
$result = $link->query($query) ;
if((isset($result->num_rows)) && ($result->num_rows != '')) {
while ($row = $result->fetch_assoc()) {
echo "filenumber: $row['dfid'] <br>";
echo "filename: $row['file_name'] - $row['file_name_furl'] <br>";
}
Read up on mysql joins http://www.keithjbrown.co.uk/vworks/mysql/mysql_p5.php
I'm not sure if this is syntax correct, but it gives you the right idea =)

Checking to see if a MySQL row is populated

I have a page that writes to a MySQL table. The table has a set amount of rows (24).
I have an $id variable that's set by a rand() function. I basically want to pull the row at that $id, so if $id was 3, I want to pull the third row. Then, I want to check if there is a price set at that row (indicating that the row is being used). If there is no price, I want to keep $id at the value it has been set at and proceed with the query. If there is a price, I want to re-randomize the $id variable, and check again if that row is used up. When it finds an empty row, proceed with the query.
My solution semi-works, but it seems to have a <10% chance of overwriting a used row, for some reason. I want it to never overwrite a used row.
Here's my code:
mysql_select_db("delives0_booklet", $con);
$query = "SELECT * FROM booklet WHERE id = '$id'";
$res = mysql_query($query,$con);
$newId = $id;
while($row = mysql_fetch_array($res))
{
if($row['price'] != 0)
{
do{
$newId = rand(1, 24);
}while($newId == $id);
}
}
$id = $newId;
mysql_query("UPDATE booklet SET price = '$price', advertiser = '$advertiser', image = '$image', monthsRemaining = '$monthsRemaining', availability = 1 WHERE id = '$id'");
Edit
I had the idea to do this. I loop through the table and I put the 'id' of each unfilled spot into an array. Then I pick randomly from that array. However, there seems to be a bug that I can't find, since the array keeps showing as having nothing in it, even after the loop is run, and $i is the correct figure.
mysql_select_db("delives0_booklet", $con);
$query = "SELECT * FROM booklet";
$res = mysql_query($query,$con);
$i = 0;
$isEmpty = array();
while($row = mysql_fetch_array($res))
{
if($row['price'] == 0)
{
$isEmpty[i] = $row['id'];
$i = $i + 1;
}
}
echo $i . " unfilled spots.";
$n = 0;
while($n<$i)
{
echo $isEmpty[$n];
$n = $n + 1;
}
if($i > 0)
{
$id = $isEmpty[rand(0, $i)];
}
if($i == 0)
{
echo 'All spots have been filled.';
}
I think it is a top level logic problem. Because you populate with random ids, you can get duplicate ids, and so when you update "WHERE id = '$id'" you may be picking up rows already populated.
I don't know your goal, but perhaps using an auto-increment id, and dropping rows that you want to get rid of, is the way to go. A rolling set of rows (24 at a time) but with ever increasing ids, would prevent mistaking one for the other.
If I understand the problem correct, this should work:
SELECT *
FROM booklet
WHERE price = 0 OR price IS NULL
ORDER BY RAND()

Categories