PHP INSERT into创建数据库错误

jac*_*cob 0 php mysql insert

我正在尝试创建一个函数,它将通过表单插入数据库中的项目(并将执行相同的编辑).我有表单和PHP - 当我运行该函数时,我得到正确的数据库名称以及变量名称以及我输入的值,但是我看到数据库错误?任何帮助都会很棒(我还是比较新的PHP,并拔掉一些头发)

配置文件:

$hostname = 'localhost';
$username = 'DEFINED';
$password = 'DEFINED';
$database = 'DEFINED';
$table = 'recipes';

require('../config.php');  
$link = mysql_connect($hostname,$username,$password);
mysql_select_db($database,$link);

/* Get values and submit */
$rid = mysql_real_escape_string($_POST['rid']);
$name = mysql_real_escape_string($_POST['name']);
$category = mysql_real_escape_string($_POST['category']);
$tags = mysql_real_escape_string($_POST['tags']);
$search_tags = mysql_real_escape_string($_POST['search_tags']);
$description = mysql_real_escape_string($_POST['description']);
$description2 = mysql_real_escape_string($_POST['description2']);
$recipeAbout = mysql_real_escape_string($_POST['recipeAbout']);
$ingredients_1 = mysql_real_escape_string($_POST['ingredients_1']);
$directions_1 = mysql_real_escape_string($_POST['directions_1']);

$query = "INSERT INTO $table (name, category, tags, search_tags, description,description2, recipeAbout, ingredients_1,directions_1) VALUES ('$name','$category','$description','$description2' $tags','$search_tags','$description','$recipeAbout','$ingredients_1','$directions_1')";

echo $query;
Run Code Online (Sandbox Code Playgroud)

Fun*_*ner 5

除了你之后添加的'$description2' $tags'=>中缺少的逗号'$description2', $tags',并且由Ryan发出信号:还有一个缺失的引用,所以将其更改为 '$description2', '$tags'并拥有2x '$description'变量,删除一个.

VALUES 
('$name','$category','$tags','$description','$description2', '$search_tags','$recipeAbout','$ingredients_1','$directions_1')";
Run Code Online (Sandbox Code Playgroud)

但是,查询最重要的部分是,一旦修复了语法错误,就必须使用mysql_query()未使用的=> mysql_query()这就是为什么没有插入数据的原因.

  • mysql_query() 是必不可少的部分.

将以下内容添加到您的代码中:

if(mysql_query($sql,$link)){
echo "Success";
}

else{
echo "Error" . mysql_error();
}
Run Code Online (Sandbox Code Playgroud)

另外,使用准备好的语句,或与准备语句PDO.

  • 您正在使用已弃用的库并打开SQL注入 ..

另外,请确保已将$table您希望输入数据的表格分配到表格中.它没有显示在你的问题中.

您也没有显示HTML表单包含的内容.确保您使用的是POST方法,并且所有元素都是以没有拼写错误的方式命名的.

错误报告添加到文件的顶部,这将有助于查找错误.

<?php 
error_reporting(E_ALL);
ini_set('display_errors', 1);
Run Code Online (Sandbox Code Playgroud)

旁注:错误报告应该只在暂存中完成,而不是生产.


编辑:和使用mysqli_

作为快速测试,请尝试以下操作并使用您自己的替换下面一行中的值.

<?php 
$link = mysqli_connect("host","username","password","database") 

or die("Error " . mysqli_error($link)); 

$table = "recipes";

$name = mysqli_real_escape_string($link,$_POST['name']);
mysqli_query($link,"INSERT INTO `$table` (`name`) VALUES ('".$name."')")

or die(mysqli_error($link));

?>
Run Code Online (Sandbox Code Playgroud)

如果仍然无效,那么您需要检查数据库,表,列名称,包括类型和列长度.