简体   繁体   English

使用PHP在MySql数据库中插入数据时遇到问题

[英]Having trouble inserting data in MySql database with PHP

This is just a testing page to make sure that I know how to insert data into the database. 这只是一个测试页面,以确保我知道如何将数据插入数据库。

This is my login page: 这是我的登录页面:

<?php 

$mysql_host = "[HOST REMOVED]";
$mysql_database = "a8700070_test";
$mysql_user = "a8700070_admin";
$mysql_password = "[PASSWORD REMOVED]";
?>

This is the code I have for the form. 这是我用于表单的代码。

<form action="db.php" method="post">

<input name="name" type="text">
<input name="age" type="text">
<input name="title" type="text">
<input name="person" type="text">
<input name="ok" type="text">
<input name="GO!" type="submit"> 



</form>

and this is the code I have that inserts it into the table. 这是我将其插入表中的代码。

<?php // 
require_once 'login.php';
$db_server= mysql_connect($mysql_host, $mysql_user, $mysql_password);

if (!$db_server) die("Unable to connect to MySQL: " . mysql_error());

mysql_select_db($mysql_database)  or die("Unable to select database: " . mysql_error());

$namer = $_POST["name"];
$age = $_POST["age"];
$tit = $_POST["title"];
$k = $_POST["ok"];
$pers = $_POST["person"];

echo "$namer";

$sql="INSERT INTO test (title,person,age,date,ok)
VALUES($namer,$age,$tit,$k,$pers)"



?>

you need to actually call your query with mysql_query like this: 您实际上需要使用mysql_query调用查询,如下所示:

mysql_query($sql);

You should also remember to escape your input to ensure a user wont abuse it with SQL injection . 您还应该记住转义输入,以确保用户不会通过SQL注入滥用它。

Your query should look like this: 您的查询应如下所示:

$sql = "INSERT INTO test (title,person,age,date,ok) VALUES('".mysql_real_escape_string($namer)."','".mysql_real_escape_string($age)."','".mysql_real_escape_string($tit)."','".mysql_real_escape_string($k)."','".mysql_real_escape_string($pers)."')";

If you're getting an error, you could print the actual error with mysql_error like this: 如果遇到错误,可以使用mysql_error像这样打印实际错误:

mysql_query($sql) or die(mysql_error());

You need to seperate the variables in your SQL query with single quotes and should properly escape them... 您需要使用单引号将SQL查询中的变量分开,并应正确地对它们进行转义...

$sql="INSERT INTO test (title,person,age,date,ok)
VALUES('".mysql_real_escape_string($namer)."','".mysql_real_escape_string($age)."','".mysql_real_escape_string($tit)."','".mysql_real_escape_string($k)."','".mysql_real_escape_string($pers)."')

And then actually run the query eg 然后实际运行查询,例如

$query = mysql_query($sql);

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

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