简体   繁体   English

从表单获取数据并提交到mysql数据库后出现问题

[英]Having problems after getting data from form and submiting to mysql database

When i retreive data from form and when i need to submit that data in mysql database, I get some errors. 当我从表单检索数据并且需要在mysql数据库中提交该数据时,出现一些错误。 I know that the problem is in ' and " characters 我知道问题出在'"字符

My php code for submiting data : 我的PHP代码提交数据:

$sql = 'INSERT INTO news (id,name)
VALUES ("$id","$name")';

Variable $name is retreived from form. 从表单检索变量$name $name= $_POST["name"];

So, if variable $name has value of 因此,如果变量$name值为

<p>
<span style="color: rgb(68, 68, 68); font-family: 'Open Sans', sans-serif; font-size: 16px; line-height: 26.672px;">1. Some text for example</span><br>
</p>

How I can query that text when there are problems between ' and " '"之间存在问题时,如何查询该文本

The difference between using single quotes and double quotes in php is that if we use single quotes in echo statement then it is treated as a string. 在php中使用单引号和双引号之间的区别在于,如果我们在echo语句中使用单引号,则将其视为字符串。 If we use variables inside single quotes then it will output as it is variable name. 如果我们在单引号内使用变量,则它将作为变量名输出。

$sql = "INSERT INTO news (id,name)
VALUES ($id,'$name')";

Since $name is a string, its better to write the code in this manner. 由于$name是字符串,因此最好以这种方式编写代码。

I know that the problem is in ' and " characters. // from question 我知道问题出在'和“字符。//来自问题

I hope ,now you know where the problem is . 我希望,现在您知道问题出在哪里了。


Update 更新资料

Now as our friends said in the comment section , to avoid sql injection , One of several ways is by using prepared Statements with mySQLi 现在,正如我们的朋友在评论部分中所述,为避免sql注入 ,几种方法之一是通过将准备好的Statements与mySQLi一起使用
Using Above method your code will be like below . 使用Above方法,您的代码将如下所示。

$name = $_GET['username'];
$id = $_GET['id'];

if ($stmt = $mysqli->prepare("INSERT INTO tbl_users (id, name) VALUES (?, ?)")) {

    // Bind the variables to the parameter as strings. 
    $stmt->bind_param("ss", $id, $name);

    // Execute the statement.
    $stmt->execute();

    // Close the prepared statement.
    $stmt->close();

}

For more check here 这里 查看更多
Great references by RiggsFolly , RiggsFolly的大量参考资料
SQL injection that gets around mysql_real_escape_string() SQL注入绕过mysql_real_escape_string()
http://bobby-tables.com/ http://bobby-tables.com/
really awesome , thanks RiggsFolly 真的很棒,谢谢RiggsFolly

how about this ? 这个怎么样 ?

if($stmt = mysqli_prepare($con,"INSERT INTO news(id,name) values (?,?)") ){     //$con = mysqli_connect(...
        mysqli_stmt_bind_param($stmt,'ss',$id,$name); // id and name as string
        mysqli_stmt_execute($stmt);
        mysqli_stmt_close($stmt);
    }
    mysqli_close($con);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM