gpt4 book ai didi

javascript - 如何创建多个jquery表单字段并插入mysql数据库,而不使用mysql_real_escape_string

转载 作者:行者123 更新时间:2023-11-29 12:09:10 25 4
gpt4 key购买 nike

我需要使用按钮创建动态文本字段(它只是添加一行新的动态文本字段)。然后我需要将数据插入到数据库中。我从别人的问题中借用了一个我需要完成的示例,问题是,它使用 mysql_real_escape_string ,它现在已被折旧。我对此很陌生,所以你能告诉我我会用什么来代替 mysql_real_escape_string 吗?

$(function(){
$('p#add_field').click(function(){
counter += 1;
$('#container').append(
'<strong>Hobby No. ' + counter + '</strong><br />'
+ '<input id="field_' + counter + '" name="dynfields['+counter+'][name]' + '" type="text" /><br />' +
+ '<input id="field_' + counter + '" name="dynfields['+counter+'][surname]' + '" type="text" /><br />' +
+ '<input id="field_' + counter + '" name="dynfields['+counter+'][age]' + '" type="text" /><br />' +
+ '<input id="field_' + counter + '" name="dynfields['+counter+'][gender]' + '" type="text" /><br />');

});
});
</script>
if (isset($_POST['submit_val'])) {
if ($_POST['dynfields']) {
foreach ( $_POST['dynfields'] as $key=>$fieldArray ) {

$keys = array_keys($fieldArray);
$values = array_map("mysql_real_escape_string",$fieldArray);

$query = mysql_query("INSERT INTO my_hobbies (".implode(',',$keys).") VALUES ('".implode('\',\'',$values)."')", $connection );
}
}

echo "<i><h2><strong>" . count($_POST['dynfields']) . "</strong> Hobbies Added</h2></i>";

mysql_close();
}

最佳答案

您的问题与 jQuery 和表单无关。强烈建议防止 SQL 注入(inject),这是一种攻击者通过将 SQL 命令发布到您的表单中将 SQL 命令注入(inject)到您的数据库查询中的攻击。这就是为什么任何来自不受信任的来源(例如 html 表单)的数据都应该被清理或至少转义。

Here很好地解释了 SQL 注入(inject)是什么以及它是如何工作的。

至于你的问题:你可以使用mysqli_real_escape_string

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}

$mysqli->query("CREATE TEMPORARY TABLE myCity LIKE City");

$city = "'s Hertogenbosch";

/* this query will fail, cause we didn't escape $city */
if (!$mysqli->query("INSERT into myCity (Name) VALUES ('$city')")) {
printf("Error: %s\n", $mysqli->sqlstate);
}

$city = $mysqli->real_escape_string($city);

/* this query with escaped $city will work */
if ($mysqli->query("INSERT into myCity (Name) VALUES ('$city')")) {
printf("%d Row inserted.\n", $mysqli->affected_rows);
}

$mysqli->close();
?>

关于javascript - 如何创建多个jquery表单字段并插入mysql数据库,而不使用mysql_real_escape_string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30981073/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com