mysqli_query inputs via variable

2020-05-08 07:12发布

问题:

I'm trying to add information to a MySQL table using the following PHP code. (The input the name and text from an HTML5 basic web form.) Probably a syntax issue?

<?php
include "dbinfo.php"; //contains mysqli_connect information (the $mysqli variable)
//inputs
$name = $_GET["name"];
$text = $_GET["text"];

$sqlqr = 'INSERT INTO `ncool`.`coolbits_table` (`name`, `text`, `date`) VALUES ("$name", "$text", CURRENT_TIMESTAMP);'; //the query. I'm pretty sure that the problem is a syntax one, and is here somewhere.

mysqli_query($mysqli,$sqlqr); //function where the magic happens.
?>

No error is thrown. A blank screen results, and a row with "$name" and "$text" is added to the MySQL table.

回答1:

This is how your code should look (with added SQL Injection protection):

<?php
include "dbinfo.php"; //contains mysqli_connect information (the $mysqli variable)
//inputs
$name = mysqli_real_escape_string($_GET['name']);
$text = mysqli_real_escape_string($_GET['text']);

$sqlqr = "INSERT INTO `ncool`.`coolbits_table` (`name`, `text`, `date`) VALUES ('" . $name . "', '" . $text . "', CURRENT_TIMESTAMP);";

mysqli_query($mysqli,$sqlqr); //function where the magic happens.
?>

Take a look at what I've done. Firstly I've escaped the user input you're retrieving into the $name and $text variables (this is pretty much a must for security reasons) and as others have suggested you should preferably be using prepared statements.

The problem is that you weren't surrounding string values with single quotes ('), which is a requirement of the SQL syntax.

I hope this helps to answer your question.



回答2:

First of all: you should use mysqli prepared statements to prevent SQL injection attacks. It is not safe to use user input within a query without proper escaping. Prepared statements are useful to prevent this.

Second: you should learn how string quoting works in PHP, single quoted strings and double quoted strings are different

I would recommend to read the PHP documentation about string quoting.



回答3:

   $sqlqr = 'INSERT INTO `ncool`.`coolbits_table` (`name`, `text`, `date`) VALUES ("'.$name.'", "'.$text.'", CURRENT_TIMESTAMP)';

Keep your vars outside the quotes.