How to include a PHP variable inside a MySQL inser

2018-12-31 08:41发布

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')");

11条回答
春风洒进眼中
2楼-- · 2018-12-31 08:56

The best option is prepared statements. Messing around with quotes and escapes is harder work to begin with, and difficult to maintain. Sooner or later you will end up accidentally forgetting to quote something or end up escaping the same string twice, or mess up something like that. Might be years before you find those type of bugs.

http://php.net/manual/en/pdo.prepared-statements.php

查看更多
墨雨无痕
3楼-- · 2018-12-31 09:00

Here

$type='testing' //it's string

mysql_query("INSERT INTO contents (type, reporter, description) VALUES('$type', 'john', 'whatever')");//at that time u can use it(for string)


$type=12 //it's integer
mysql_query("INSERT INTO contents (type, reporter, description) VALUES($type, 'john', 'whatever')");//at that time u can use $type
查看更多
君临天下
4楼-- · 2018-12-31 09:03

I know there has been a few answers to this question but I thought I would add that if you follow the following syntax, I have never had an issue with the error again. No question which table you are using and which columns you are appending.

$query    = "INSERT INTO contents (type, reporter, description) 
         VALUES('".$type."', '".$reporter."', '"$whatever."')";
查看更多
栀子花@的思念
5楼-- · 2018-12-31 09:04

to avoid SQL injection the insert statement with be

$type = 'testing';

$stmt = $con->prepare("INSERT INTO   contents (type, reporter, description) VALUES (?, ?, ?)");
         $stmt->bind_param("sss", $type , 'john', 'whatever');
         $stmt->execute();
    $stmt->close();
查看更多
十年一品温如言
6楼-- · 2018-12-31 09:07

The text inside $type is substituted directly into the insert string, therefore MySQL gets this:

... VALUES(testing, 'john', 'whatever')

Notice that there are no quotes around testing, you need to put these in like so:

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

I also recommend you read up on SQL injection, as this sort of parameter passing is prone to hacking attempts if you do not sanitize the data being used:

查看更多
梦寄多情
7楼-- · 2018-12-31 09:10

You have to write the variable in single or double quotes, then braces and then the variable name (example: $abc) inside.

Example:

SELECT * FROM log WHERE id = '{$id}';
查看更多
登录 后发表回答