SQL Insert and Submit

2019-08-18 05:53发布

问题:

When I execute this query it returns false, which means the query is wrong. Can you figure out why?

$string1 = 'wee';
$string2 = 'wee'; 
$string3 = 'wee'; 
$string4 = 'wee';  

if (isset($_POST['submit'])) {  

    $query = "INSERT INTO data (book, title, content, author)
              VALUES ($string1, $string2, $string3, $string4)";          
    mysql_query($query, $con);    
}

However, when I put something that is like the following, it returns true and inserts correctly:

$query = "INSERT into data (book, title, content, author)
          VALUES ('wee', 'wee', 'wee', 'wee')";

And another question: when I submit, it seems that the query is returning twice when executed which means two records with one query. Does anyone understand that?

If you need more information, just ask.

Thanks in advance.

回答1:

Although this question seems answered, you should not be using user input directly in queries as this opens holes for vulnerabilities like SQL Injection (and that's bad mmmay)

If you look at the mysql page on php.net (mysql_query) the page says it is recommended you use an abstraction layer like PDO (pdo-mysql)

Using PDO will allow you to bind parameters to your sql queries to bypass the security implications of using user input in your queries.

If you don't bind parameters to your queries, you're gonna have a bad time.



回答2:

Your field data type is string or varchar so you need to put '' or "" around them.

Change your query as below

$query = "INSERT into data (book, title, content, author)VALUES ('".$string1."', '".$string2."',     
         '".$string3."', '".$string4."')";

To resolve submit issue, please post your html code