1

This is bizarre, I'm changing some code from mysql to mysqli functions cause of php 5.5+, in these two basic examples, mysql_query had no ' single quote nor ` backtick and worked fine.

$sql = "SELECT * FROM `".$table."`"; // requires: ` ` or fails
$result = mysqli_query($con,$sql);

$sql = "SHOW TABLES LIKE '".$table."'"; // requires: ' ' or fails
$result = mysqli_query($con,$sql);

Can someone explain why?

EDIT: I guess the essence of my question is that: Both functions worked fine without any kind of quotes with mysql_query, and both failed mysqli_query without some kind of quotes. Meaning I will have to fiddle around with half my query's when changing from mysql_ to mysqli_

ChrisAdmin
  • 982
  • 1
  • 12
  • 32
  • 1
    What´s your table name in $table? What about reserved words? While you use non-reserved table names, there is no reason to quotes. – pavel Oct 18 '14 at 09:57
  • 1
    I don't think you need any quotes – RST Oct 18 '14 at 09:58
  • `$sql = "SELECT * FROM `".$table."`";` If this query need ` ` this than we need to know your table name – arif_suhail_123 Oct 18 '14 at 10:00
  • possible duplicate: [2122721/what-are-the-differences-between-backtick-and-single-quote](https://stackoverflow.com/questions/2122721/what-are-the-differences-between-backtick-and-single-quote-can-i-use-if-stateme) – Ryan Vincent Oct 18 '14 at 10:22
  • Well both functions worked fine without any kind of quotes with mysql_query, and both failed mysqli_query without some kind of quotes. Meaning I will have to fiddle around with half my query's when changing from mysql_ to mysqli_ – ChrisAdmin Oct 20 '14 at 01:24

1 Answers1

3

In your first select statement you are trying to select a table by it's name, hence it will accept the name either with ` or without them, but now with single or double quotes. These should work :

 $sql = "SELECT * FROM `table_name`";
 $sql = "SELECT * FROM table_name";

In the second case you need to pass in a string to be compared by the like statement hence you need to surround it either with single ' or double " quotes:

$sql = "SHOW TABLES LIKE 'string'";
$sql = "SHOW TABLES LIKE \"string\"";

Edit:

Check out this previous answer on SO as well: Using backticks around field names

Edit 2:

Since we (me and in comments) suggested that backticks are somehow optional, keep in mind that as a best practise use them whenever you can since although it will allow you to pass most queries without them, some queries using MySql reserved words would break when containing mysql reserved words

Community
  • 1
  • 1
Kypros
  • 2,997
  • 5
  • 21
  • 27