PHP / mySQL: mysql_query with SELECT, FROM and WHERE

I am trying to set $nextPageID and $nextPageTitle following code. Unfortunately, they are not installed.

 $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 pages table contains a row with pageID = 2, pageCategoryID = 1, order = 2, title = Next page and 4 more columns with data that I do not need for this query.

This code has been simplified for testing purposes. It will be disinfected after I earn it.

Any thoughts on what I can do to make this bit of code work?

+4
source share
3 answers

Forget PHP right now. This is your SQL query:

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

In SQL, like in many other languages, you use quotation marks to enter literals. Since the string 'order' will never be equal to the string '1 ', your query will always return zero rows, regardless of other values.

If order is the name of a column, you cannot quote it.

Now, given that order is a reserved word , you will have to use inverse elements around it. You can also enter integers as integers (no need to quote them):

 SELECT pageID, pageCategoryID, `order`, title FROM pages WHERE pageCategoryID=1 AND `order`=2 
+3
source

you rewrite the variable for each record, perhaps create an array like

  $data = array(); while ($nextPageArray = mysql_fetch_assoc($fetchedNextPageData)) { $data[] = array('id' => $nextPageArray['pageID'], 'title' => $nextPageArray['title']); } 
+5
source

In the WHERE clause of your query, try removing quotes in order and using back ticks instead:

 `order`='$nextPageOrder' 

And try to avoid using keywords for table and column names! Was there.

+1
source

Source: https://habr.com/ru/post/1383107/


All Articles