我正在使用一个简单的html格式和PHP将字符串插入到mySQL数据库中,这对于短字符串工作正常,而不是长字符串。
使用 phpmyadmin 我可以插入所有长度的字符串,它只适用于html文件和PHP。
会欣赏各种帮助,希望更多地了解这个话题......
提前感谢你们,如果问题很简单,那就很抱歉......
到目前为止,我发现有两个非常相似的问题......不幸的是他们无法帮助:
INSERTing very long string in an SQL query - ERROR
How to insert long text in Mysql database ("Text" Datatype) using PHP
在这里你可以找到我的html格式:
<html>
<body>
<form name="input" action = "uploadDataANDGetID.php" method="post">
What is your Name? <input type="text" name="Name"><br>
Special about you? <input type="text" name="ThatsMe"><br>
<input type ="submit" value="Und ab die Post!">
</form>
</body>
</html>
这里是名为uploadDataANDGetID.php的PHP脚本:
<?php
$name = $_POST["Name"];
$text = $_POST["ThatsMe"];
$con = mysql_connect("localhost", "username", "password") or die("No connection established.");
mysql_select_db("db_name") or die("Database wasn't found");
$q_post = mysql_query("INSERT INTO profiles VALUES (null, '{$name}' ,'{$text}')");
$q_getID =mysql_query("SELECT ID FROM profiles WHERE Name = '{$name}' AND ThatsMe = '{$text}'");
if(!$q_post) // if INSERT wasn't successful...
{
print('[{"ID": "-3"}]');
print("uploadDataAndGetID: Insert wasn't successful...");
print("about ME: ".$text);
}
else // insertion succeeded
{
while ($e=mysql_fetch_assoc($q_getID))
$output[]=$e;
//checking whether SELECTion succeeded too...
$num_results = mysql_num_rows($q_getID);
if($num_results < 1)
{
// no such profile available
print('[{"ID": "-1"}]');
}
else
{
print(json_encode($output));
}
}
mysql_close();
?>
谢谢你们!
答案 0 :(得分:2)
使用更新的方式连接到MySQL并使用预准备语句http://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php
答案 1 :(得分:1)
你必须使用mysql_real_escape_string
来逃避你的字符串,如下所示:
$name = mysql_real_escape_string($_POST['Name']);
$text = mysql_real_escape_string($_POST["ThatsMe"]);
$q_post = mysql_query('INSERT INTO profiles VALUES (null, "' . $name . '" ,"' . $text . '")');
还阅读了SQL injection