-1

I have a php page which outputs all of the pages created (located in the database) each page links to a new page which will contain all of the content for that page.

I want to parse the name of the page into the URL so i can retrieve it and search through the database to find all of the records using that name within the database, I have been able to do this by parsing the rows ID however i want to do it with the pages name.

This is my code outputting all of the page links and storing the value of 'name' in the URL :

$res = $conn->query("SELECT * FROM pages ORDER BY id ASC");
while($row=$res->fetch_array())
{

    echo '<a href="page.php?name=' . urlencode($row['name']) . '">' . ucfirst($row['name']) . '</a>' . "<br>";

} 

Here is the page where i want to retreive the value of 'name' and search through the database for the record containing 'name' which is now stored in the $page variable

include_once 'db.php';

$page = urldecode($_GET['name']);

echo $page;

// LOAD UP THE CORRECT PAGE BY Page NAME 

$res = $conn->query("SELECT * FROM pages WHERE name = $page");
$row=$res->fetch_array();

When i echo the $page variable, it does show the correct name, so i dont know why i am receiving this error :

Fatal error: Uncaught Error: Call to a member function fetch_array() on boolean in /Applications/XAMPP/xamppfiles/htdocs/newpage/page.php:12 Stack trace: #0 {main} thrown in /Applications/XAMPP/xamppfiles/htdocs/newpage/page.php on line 12

Thankyou for any help

chris85
  • 23,846
  • 7
  • 34
  • 51
Bradley Cousins
  • 187
  • 6
  • 17

1 Answers1

3

Error means that you have error in query. Probably because of lack ' Strings in sql must be QUOTED like this:

$conn->query("SELECT * FROM pages WHERE name = '$page'");

ps: you should also escape values which you put into query. Read about sql injections

nospor
  • 4,190
  • 1
  • 16
  • 25
  • What a silly error of mine !, Thanks for that – Bradley Cousins May 27 '16 at 14:16
  • SQL injection links, http://php.net/manual/en/security.database.sql-injection.php, http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php, https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet – chris85 May 27 '16 at 14:19
  • Thanks for that, is this what you recommend i use : mysql_escape_string () – Bradley Cousins May 27 '16 at 14:22
  • I would use parameterized queries. Look at http://php.net/manual/en/mysqli.quickstart.prepared-statements.php. and/or see the previously linked thread, `How can I prevent SQL-injection in PHP?` – chris85 May 27 '16 at 14:24
  • you should stop using mysq_ lib because it is deprecated and removed in php7. You should start using mysqli_ lib or PDO and their prepared statements as mention chris85 – nospor May 27 '16 at 14:26