2014-02-10 56 views
1

我正在使用一個簡單的html表單和PHP將字符串插入到mySQL數據庫中,這對於短字符串來說工作得很好,確實不適合長字符串。如何使用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

你能發佈你得到的錯誤和你的表格描述? – Jayaram

+0

另外,如果你想獲得新的iserted行的ID,你應該使用'mysql_insert_id'函數 –

+0

哇,夥計們!非常感謝您回答如此之快並且非常樂於助人! – lifelover

回答

0

必須逃脫你的字符串,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

+0

非常感謝你Marek!它對我來說非常合適!感謝您的注射建議,我會盡量在將來儘可能小心......再次感謝! – lifelover

+0

沒問題。請接受我的回答;)瞭解SQL注入問題非常重要。最短的文本打破你以前的代碼是一個雙引號'''' –

+0

明白了,謝謝你Marek! – lifelover

相關問題