Php mysql запросы переменные

Как в sql запрос вставить переменную php

Для того чтобы передать переменную в SQL запрос в PHP, можно использовать один из следующих вариантов:

  1. Использовать подготовленные запросы. Это позволяет избежать SQL инъекций и передавать переменные в запрос безопасным способом. Пример:
 $stmt = $pdo->prepare('SELECT * FROM users WHERE email = :email'); $stmt->execute(['email' => $email]); $user = $stmt->fetch(); 
  1. Сформировать строку запроса с помощью конкатенации строк и передать ее в функцию выполнения запроса. Пример:
 $sql = "SELECT * FROM users WHERE email = '" . $email . "'"; $result = mysqli_query($conn, $sql); $user = mysqli_fetch_assoc($result); 

Важно учитывать, что при использовании второго варианта возможна SQL инъекция, поэтому необходимо очищать переменные перед использованием их в запросе.

Для более детального изучения вопроса «SQL инъекции» рекомендуем просмотреть урок Безопасность при работе с внешними данными из курса PHP PDO: Работа с базой данных

Источник

How to include a PHP variable inside a MySQL statement

I’m trying to insert values in the contents table. It works fine if I do not have a PHP variable inside VALUES. When I put the variable $type inside VALUES then this doesn’t work. What am I doing wrong?

$type = 'testing'; mysql_query("INSERT INTO contents (type, reporter, description) VALUES($type, 'john', 'whatever')"); 

5 Answers 5

Answer recommended by PHP Collective

The rules of adding a PHP variable inside of any MySQL statement are plain and simple:

Читайте также:  Htaccess добавить index php

1. Use prepared statements

This rule covers 99% of queries and your query in particular. Any variable that represents an SQL data literal, (or, to put it simply — an SQL string, or a number) MUST be added through a prepared statement. No exceptions.

This approach involves four basic steps

  • in your SQL statement, replace all variables with placeholders
  • prepare the resulting query
  • bind variables to placeholders
  • execute the query

And here is how to do it with all popular PHP database drivers:

Adding data literals using mysqli

Current PHP version lets you to do the prepare/bind/execute in one call:

$type = 'testing'; $reporter = "John O'Hara"; $query = "INSERT INTO contents (type, reporter, description) VALUES(?, ?, 'whatever')"; $mysqli->execute_query($query, [$type, $reporter]); 

If your PHP version is old, then prepare/bind/execute has to be done explicitly:

$type = 'testing'; $reporter = "John O'Hara"; $query = "INSERT INTO contents (type, reporter, description) VALUES(?, ?, 'whatever')"; $stmt = $mysqli->prepare($query); $stmt->bind_param("ss", $type, $reporter); $stmt->execute(); 

The code is a bit complicated but the detailed explanation of all these operators can be found in my article, How to run an INSERT query using Mysqli, as well as a solution that eases the process dramatically.

For a SELECT query you can use the same method as above:

$reporter = "John O'Hara"; $result = $mysqli->execute_query("SELECT * FROM users WHERE name=?", [$reporter]); $row = $result->fetch_assoc(); // or while (. ) 

but again, if your PHP version is old, you will need to go through prepare/bind/execute routine and also add a call to get_result() method, in order to get a familiar mysqli_result from which you can fetch the data the usual way:

$reporter = "John O'Hara"; $stmt = $mysqli->prepare("SELECT * FROM users WHERE name=?"); $stmt->bind_param("s", $reporter); $stmt->execute(); $result = $stmt->get_result(); $row = $result->fetch_assoc(); // or while (. ) 
Adding data literals using PDO
$type = 'testing'; $reporter = "John O'Hara"; $query = "INSERT INTO contents (type, reporter, description) VALUES(?, ?, 'whatever')"; $stmt = $pdo->prepare($query); $stmt->execute([$type, $reporter]); 

In PDO, we can have the bind and execute parts combined, which is very convenient. PDO also supports named placeholders which some find extremely convenient.

2. Use white list filtering

Any other query part, such as SQL keyword, table or a field name, or operator — must be filtered through a white list.

Sometimes we have to add a variable that represents another part of a query, such as a keyword or an identifier (a database, table or a field name). It’s a rare case but it’s better to be prepared.

In this case, your variable must be checked against a list of values explicitly written in your script. This is explained in my other article, Adding a field name in the ORDER BY clause based on the user’s choice:

Unfortunately, PDO has no placeholder for identifiers (table and field names), therefore a developer must filter them out manually. Such a filter is often called a «white list» (where we only list allowed values) as opposed to a «black-list» where we list disallowed values.

So we have to explicitly list all possible variants in the PHP code and then choose from them.

$orderby = $_GET['orderby'] ?: "name"; // set the default value $allowed = ["name","price","qty"]; // the white list of allowed field names $key = array_search($orderby, $allowed, true); // see if we have such a name if ($key === false)

Exactly the same approach should be used for the direction,

$direction = $_GET['direction'] ?: "ASC"; $allowed = ["ASC","DESC"]; $key = array_search($direction, $allowed, true); if ($key === false)

After such a code, both $direction and $orderby variables can be safely put in the SQL query, as they are either equal to one of the allowed variants or there will be an error thrown.

The last thing to mention about identifiers, they must be also formatted according to the particular database syntax. For MySQL it should be backtick characters around the identifier. So the final query string for our order by example would be

$query = "SELECT * FROM `table` ORDER BY `$orderby` $direction"; 

Источник

Переменная в SQL запросе

@Zow, вы не пробовали книжки почитать? У вас очень банальные вопросы, которые говорят о том, что вы даже не пытались учиться.

3 ответа 3

 $id_ales = 1234; /*1*/ $result = mysql_query("INSERT INTO `$id_ales` (`id`, `type`) VALUES ('$id_chold', '$type')"); /*2*/ $result = mysql_query("INSERT INTO `".$id_ales."` (`id`, `type`) VALUES ('".$id_chold."', '".$type."')"); /*3*/ $result = mysql_query('INSERT INTO `'.$id_ales.'` (`id`, `type`) VALUES ("'.$id_chold.'", "'.$type.'")'); /*4*/ $result = mysql_query(sprintf('INSERT INTO `%s` (`id`, `type`) VALUES ("%s", "%s")',$id_ales,$id_chold,$type)); 

не надо огрызаться. @Sh4dow правильно сказал. Работа со строками описана во всех книжках по PHP

Автор, название, издательство / пруфлинк. Хоть повеселимся, что ли. Единственное, что я могу допустить, если условиться, что книжка нормальная, что она написана для крутейших профи, которые уже знают как работать со строками. Но вряд ли такую можно легко купить=)

@Zow, не знаю, как вам и сказать, но обратите внимание на страницы 81-91 (если у вас действительно англоязычное издание). На этих 11 страницах изложена глава «Working with Character Strings».

По-хорошему: во-первых, цифровое имя для таблицы (,то что у вас в запросе — не БД) — это плохо. А так читайте про конкатенацию и вообще строки в php.

$id_chold = intval($id_chold); // цифровое значение $type = mysql_real_escape_string($type); // строковое значение $result = mysql_query('INSERT INTO ' . $id_ales . ' (`id`, `type`) VALUES (\'' . $id_chold . '\', \'' . $type . '\')'); 

Если привыкнете писать так — у вас не будет проблем ни со вставкой переменных, ни с другими языками, ни с безопасностью в запросах.

Источник

Как вставить переменные в sql запрос на php?

Вопрос:
Как правильно оформить вставку переменных в этот запрос?

Оценить 1 комментарий

А точки-то зачем? для прайса можно взять between, если это числа. Попробуйте написать сначала запрос или в консоли, или в чем-то типа phpmyadmin, если он есть.

FanatPHP

Только. Через. Плесхолдеры.
Любой, кто отвечает иначе — тупой нуб, застрявший в прошлом веке и так и не осиливший даже азы программирования.

Соответственно, тебе нужна библиотека, которая поддерживает плейсхолдеры. Хотя старушку mysql ext можно заставить, но для новичка лучше всего подойдет PDO.

$sql = "SELECT * FROM mytable WHERE city = ? AND price BETWEEN ? AND ? AND type = 'Продать'"; $stmt = $pdo->prepare($sql); $stmt->execute([$_POST['city'], $_POST['area'], $_POST['price']-50, $_POST['price']+50]); $data = $stmt->fetchAll();

Как соединяться с БД и вообще про PDO читай здесь: phpfaq.ru/pdo

А твоя ошибка вызвана опечаткой и неправильной обработкой ошибок.
Во-первых, у тебя в какой-то из запросов передается пустая строка — скорее всего, из-за опечатки
Во-вторых, если бы в РНР было включено нормальное отображение ошибок, то РНР тебе бы сам ругнулся на эту опечатку.
В-третьих, если бы ошибки mysql обрабатывались по-человечески, то РНР тоже указал бы на тот конкретный запрос, который оказался пустым. И ты бы не хватался вместо него за первый попавшийся.

Источник

Оцените статью