简体   繁体   English

我的MySQL查询有什么问题?

[英]What is wrong with my MySQL query?

So, I have a form that posts to my php file using ajax, and succeeds. 因此,我有一个使用ajax发布到我的php文件的表单,并且成功。 But the following query doesn't insert anything. 但是以下查询不会插入任何内容。 Can someone help me understand what I'm doing wrong? 有人可以帮助我了解我在做什么错吗?

My php file: 我的php文件:

<?php

include 'connect.php' ;

$type = mysql_real_escape_string($_POST['type']);

$title = mysql_real_escape_string($_POST['title']);

$content = mysql_real_escape_string($_POST['content']);

if ($type == 'Just Text') {

    mysql_query("INSERT INTO articles (title, type, thisisaninteger, content) VALUES ('".$title."', '".$type."', 0, '".$content."')")or die("MySQL Error: " . mysql_error());

}

?>

My connect.php: 我的connect.php:

<?php

$dbhost = "localhost"; 
$dbname = "example";
$dbuser = "test"; 
$dbpass = "test"; 

mysql_connect($dbhost, $dbuser, $dbpass) or die("MySQL Error: " . mysql_error());  
mysql_select_db($dbname) or die("MySQL Error: " . mysql_error());

?>  

If you aren't receiving any errors and the INSERT just doesn't happen, it is most likely because the if statement fails to be true. 如果您没有收到任何错误并且没有发生INSERT ,则很可能是因为if语句失败。 Verify that $type actually matches Just Text . 验证$type确实与Just Text匹配。

You should also be inserting values using prepared statements , and use PDO or MySQLi - this article will help you decide which. 您还应该使用预处理语句插入值,并使用PDOMySQLi- 本文将帮助您确定哪一个。

first, echo "something" after the if statement and recall the data with your ajax post. 首先,在if语句后回显“ something”,并使用ajax帖子重新调用数据。 you can find out if your if statement is working, then try formatting your variables like so 您可以找出if语句是否有效,然后尝试像这样格式化变量

mysql_query("INSERT INTO articles (title, type, thisisaninteger, content) VALUES ('$title', '$type', 0, '$content')")or die("MySQL Error: " . mysql_error());

I just want to throw in an official vote/recommendation in favor of switching to a parameterized SQL statement , too. 我也只想发表正式的投票/建议,以支持切换到参数化的SQL语句 In spite of the use of mysql_real_escape_string, schlepping a SQL statement together via string concatenation is neither necessary nor a good idea. 尽管使用了mysql_real_escape_string,通过字符串串联将SQL语句合并在一起既不是必要的,也不是一个好主意。 Honestly, I find a prepared statement much, much easier to read than the typical string-concatenation exercise, as well: 坦白地说,我发现准备好的语句比典型的字符串连接练习容易得多,也很容易阅读:

$stmt = $dbh->prepare("SELECT * FROM users WHERE USERNAME = ? AND PASSWORD = ?");
$stmt->execute(array($username, $password));

Alright, it was a stupid mistake on my side. 好吧,这是我这边的一个愚蠢的错误。 There were columns I didn't include and they were not being assigned a value. 有一些我没有包括的列,并且它们没有被赋值。 Thanks everyone for helping out. 感谢大家的帮助。

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

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