Array declared:

$names = array("country_code", "postal_code", "place_name", "admin_name1", "admin_code1", "admin_name2", "admin_code2", "admin_name3", "admin_code3");    

for ($i = 0; $i < 9; $i++)
    $current = $names[$i];
    $results = query("SELECT * from places WHERE country_code LIKE ?", $piece);
    $results = query("SELECT * from places WHERE ? LIKE ?", $current, $piece);

But the first query would select data from the table whereas the second query wouldn't. Is there any reason why is that, and is it possible to fix it? By the way $piece is just the a part of the $_GET (such as US from Cambridge,+MA+US).

  • in a SQL query, question marks are placeholders for column values, not column name. if you want to parameterize your column name, you could either concatenate the variable that holds the column name to your query or use variable interpolation. see php.net/manual/en/language.types.string.php! – Kareem Nov 1 '15 at 8:54
  • Do you mean this one: $results = query("SELECT * from places WHERE" . $current . "LIKE ?", $piece); – Jack Lee Nov 1 '15 at 10:13
  • why don't you try? – Kareem Nov 1 '15 at 10:17
  • Haha I've tried it and it didn't work. I am trying $string = "SELECT * from places WHERE" . $current . "LIKE $piece" query=($string) and the browser keeps loading without responding. – Jack Lee Nov 1 '15 at 10:56
  • And it turns out: Fatal error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '%GB%' at line 1 in /home/jharvard/vhosts/pset8/includes/functions.php on line 49 – Jack Lee Nov 1 '15 at 11:06

I hope you have gotten past this by now, but I'll chip in my 2¢. You and the computer are not seeing eye-to-eye. $string is something like:

'SELECT * from places WHEREcountry_codeLIKE %GB%'

May not be what you meant, but it's what you said.

It's a bad idea to put additional print statements in search.php because the next thing you know nothing works. Been there, done that. Here's something I used to troubleshoot a very similar problem. Added code like this to search.php

$dbg = isset($_GET["dbg"]);
    if ($dbg)
        print(json_encode($your_data_here, JSON_PRETTY_PRINT));

Then browse to pset8/search.php?geo=xxxxx&dbg=1

Or maybe it's a simple as: $piece not quoted (to get '%GB%').

I don't know what all the ramifications are, but the query function might be improved by a simple var_dump($sql) before the call(s) to trigger_error.

| improve this answer | |

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .