2013-09-28 81 views
0

什麼是我想要做的是:PHP:可以從數據庫取回數據,但不能插入

插入數據成兩列,並顯示在同一個PHP頁面更新值的表。我能夠獲取數據並顯示它,但無法插入任何數據。請指導我。

文件被命名爲mypage.php

到目前爲止我的代碼:

<?php 
$con=mysqli_connect("localhost","test","test","test"); 

// Check connection 
if (mysqli_connect_errno($con)) 
    { 
    echo "Failed to connect to mysqli: " . mysqli_connect_error(); 
    } 
    else 
    { 

    if(isset($_POST['url']) && isset($_POST['desc'])) 
    { 
     $url=$_POST['url']; 
     $desc=$_POST['desc']; 
     $sql= "INSERT INTO urldesc ". 
       "(url,desc) ". 
       "VALUES ('".$url."', '".$desc."')"; 
     echo $sql; 
     echo $url; 
     echo $desc; 
     mysqli_query($con, $sql); 
     //mysqli_query($con,"INSERT INTO urldesc (url, desc) VALUES ('". $_POST['url'] ."', '". $_POST['desc'] ."')"); 
    } 
    } 

?> 

<html> 
    <body> 
    <form action="mypage.php" method='post'> 
     <input type="text" name='url' /> 
     <input type="text" name='desc' /> 
     <input type="submit" /> 
    </form> 
     <table border=1> 
      <th>URL</th> 
      <th>Description</th> 
      <?php 
      $values=mysqli_query($con,"select * from urldesc"); 
      if(! $values) 
      { 
       die('Could not get data: ' . mysqli_error()); 
      } 
      while($row = mysqli_fetch_array($values)) 
      { 
       echo "<tr><td width='200px'><center>".$row['url']."</center></td><td width='600px'><center>".$row['desc']."</center></td></tr>"; 
      } 
      mysqli_close($con); 
      ?> 
     </table> 
    </body> 
</html> 
+0

你嘗試過什麼運行得到由「回聲$ SQL」迴盪在phpMyAdmin查詢? – Jinandra

回答

0

更改下面的語句

$sql= "INSERT INTO urldesc ". 
      "(url,desc) ". 
      "VALUES ('".$url."', '".$desc."')"; 

$sql= "INSERT INTO urldesc ". 
      "(`url`,`desc`) ". 
      "VALUES ('".$url."', '".$desc."')"; 
+0

完美的作品!謝謝 – Avinash

+0

@Avinash:馬克是那麼正確的答案。 – Jinandra

0

您給定的參數來mysqli_qurey格式不正確。您使用mysqli_query($con, $sql)但它應該是mysqli_query($sql, $con)

<?php 
$con=mysqli_connect("localhost","test","test","test"); 

// Check connection 
if (mysqli_connect_errno($con)) 
    { 
    echo "Failed to connect to mysqli: " . mysqli_connect_error(); 
    } 
    else 
    { 

    if(isset($_POST['url']) && isset($_POST['desc'])) 
    { 
     $url=$_POST['url']; 
     $desc=$_POST['desc']; 
     $sql= "INSERT INTO `urldesc` ". 
       "(`url`,`desc`) ". 
       "VALUES ('".$url."', '".$desc."')"; 
     echo $sql; 
     echo $url; 
     echo $desc; 
     mysqli_query($sql, $con); 
     //mysqli_query($con,"INSERT INTO urldesc (url, desc) VALUES ('". $_POST['url'] ."', '". $_POST['desc'] ."')"); 
    } 
    } 

?> 
+0

我得到這個:警告:mysqli_query()預計參數1是在mysqli的C中給出,字符串:第22行 – Avinash

+0

\ XAMPP \ XAMPP \ htdocs中\測試\ mypage.php檢查你的mysqli連接。你是否成功連接到mysql?檢查你的'$ con' –