0

谢谢各位,搞定了,原来是在js中一个单词拼写不正确,总是很简单

这是我将数据写入本地服务器上的数据库的脚本,它目前只写入 2 个字段,而不是别名字段,我做错了什么吗?我已经三次检查了 html 表单和数据库字段中的名称。

<?php
  // 1. Create connection to database

  mysql_connect('localhost','root','') or die('Could not connect to mysql: <hr>'.mysql_error());

  // 2. Select database

  mysql_select_db("trialdb") or die('Could not connect to database:<hr>'.mysql_error());

  // 3. Assign variables (after connection as required by escape string)

$alias = $_POST['alias'];
$name = $_POST['name'];
$email = $_POST['email'];

  // 4. Insert data into table

  mysql_query("INSERT INTO user_data (alias, name, email) VALUES ('$alias', '$name', '$email')"); 
  Echo 'Your information has been successfully added to the database.';  
  print_r($_POST);
  mysql_close()
?>
4

2 回答 2

0

首先,您应该始终检查POST变量是否正确发送:

if (
    !isset($_POST['alias']) or
    !isset($_POST['name']) or
    !isset($_POST['email'])
) // something is wrong

其次,您不想将用户输入直接注入到 sql 查询中。您应该首先执行一些转义(或者甚至更好地用PDOmysqlimysql_*替换已弃用的驱动程序并使用准备好的语句):

$alias = mysql_real_escape_string($_POST['alias']);
$name = mysql_real_escape_string($_POST['name']);
$email = mysql_real_escape_string($_POST['email']);

第三,您可能希望在打印成功消息之前检查查询是否正确执行:

$res = mysql_query("INSERT INTO user_data (alias, name, email) VALUES ('$alias', '$name', '$email')"); 

echo ($res) 
    ? 'Your information has been successfully added to the database.' 
    : 'Your information couldn't be added to the database';
于 2013-04-02T08:15:48.440 回答
0

你可以试试

<?php

$conn = mysql_connect('localhost','root','') or die('Could not connect to mysql: '.mysql_error());

mysql_select_db("trialdb", $conn) or die('Could not connect to database:'.mysql_error());

$alias = $_POST['alias'];
$name = $_POST['name'];
$email = $_POST['email'];

mysql_query("INSERT INTO user_data (`alias`, `name`, `email`) VALUES ('$alias', '$name', '$email')", $conn); 

echo 'Your information has been successfully added to the database.';  

print_r($_POST); 

mysql_close();

?>
于 2013-04-02T08:18:01.440 回答