How to insert variables in such a line instead of? (Question marks)? I rummaged a lot of sites, I can not figure it out. I know that in C ++ you can. For example:

$a = 'SELECT * FROM ? WHERE id = ?'; $b = какая-то_функция($a, 'table', 5); 

It is necessary to get a string like this:

 SELECT * FROM table WHERE id = 5 
  • habrahabr.ru/post/137664 just leave it here - ArchDemon
  • and what do you use mysqli or pdo - Naumov
  • I'm using mysqli - Vlad

2 answers 2

If the question is precisely the substitution of a variable into a string, you can use the sprintf () function

And if you need it to form queries to the DBMS, then it is better to use PDO

Example from documentation:

 $sth = $dbh->prepare('SELECT name, colour, calories FROM fruit WHERE calories < ? AND colour = ?'); $sth->execute(array(150, 'red')); $red = $sth->fetchAll(); 

And if you use mysqli and do not want to change it, then use mysqli :: prepare ()

Example from documentation:

 $link = mysqli_connect("localhost", "my_user", "my_password", "world"); $city = "Amersfoort"; if ($stmt = mysqli_prepare($link, "SELECT District FROM City WHERE Name = ?")) { /* связываем параметры с метками */ mysqli_stmt_bind_param($stmt, "s", $city); /* запускаем запрос */ mysqli_stmt_execute($stmt); /* связываем переменные с результатами запроса */ mysqli_stmt_bind_result($stmt, $district); /* получаем значения */ mysqli_stmt_fetch($stmt); printf("%s находится в округе %s\n", $city, $district); /* закрываем запрос */ mysqli_stmt_close($stmt); } 

    so you can =)

     $a = 'SELECT * FROM '.$table.' WHERE id = '.$id.'; 

    or more difficult but here through prepare, etc.

     "INSERT INTO `messages` (`time`, `message`, `uid`) VALUES(?,?,?)"); 

    documentation on mysqli_prepare on php.net

    • one
      You should never do that. PDO or Mysqli - ArchDemon
    • Try to write more detailed answers. Explain what your decision is based on. - Nicolas Chabanovsky