Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP/mySQL: mysql_query with SELECT, FROM, and WHERE

I am trying to set $nextPageID and $nextPageTitle with the following code. Unfortunately they are not getting set.

$pageCategoryID = 1;
$nextPageOrder = 2;

$fetchedNextPageData = mysql_query("
  SELECT pageID, pageCategoryID, 'order', title 
  FROM pages 
  WHERE pageCategoryID='$pageCategoryID' AND 'order'='$nextPageOrder'
") or die(mysql_error());

            while ($nextPageArray = mysql_fetch_array($fetchedNextPageData)) {
                $nextPageID = $nextPageArray['pageID'];
                $nextPageTitle = $nextPageArray['title'];
            }

My table pages contains a row with pageID = 2, pageCategoryID = 1, order = 2, title = Next Page, plus 4 other columns with data I don't need for this query.

This code has been simplified for testing purposes. It will be sanitized after I get it working.

Any thoughts on what I can do to get this bit of code working?

like image 522
Mark Rummel Avatar asked Jan 19 '23 04:01

Mark Rummel


2 Answers

you are overwriting the variable for each record, maybe create an array like

 $data = array();
 while ($nextPageArray = mysql_fetch_assoc($fetchedNextPageData)) {
   $data[] = array('id' => $nextPageArray['pageID'], 
            'title' => $nextPageArray['title']);
 }
like image 193
Gabriel Avatar answered Jan 30 '23 06:01

Gabriel


Forget about PHP right now. This is your SQL query:

SELECT pageID, pageCategoryID, 'order', title 
FROM pages 
WHERE pageCategoryID='1' AND 'order'='2'

In SQL, as in many other languages, you use quotes to type literal strings. Since the 'order' string will never equal the '1' string, your query will always return zero rows, no matter the other values.

If order is a column name, you cannot single-quote it.

Now, given that ORDER is a reserved word, you'll have to use backticks around it. You can also type integers as integers (there's no need to quote them):

SELECT pageID, pageCategoryID, `order`, title 
FROM pages 
WHERE pageCategoryID=1 AND `order`=2
like image 44
Álvaro González Avatar answered Jan 30 '23 06:01

Álvaro González