2013-06-24 22 views
0
please find below a script in php that that fetch data from my database company, the database is in phpMyadmin 

我知道有安全的方式來獲取數據。我的問題是 我可以使用mysqli來取代mysql_query而改進下面的代碼嗎?使用mysqli而不是mysql訪問數據庫

<?php 
     get results from database. Can I improve the code below using mysqli to fetch instead of mysql_query in the following line?. 

       $result = mysql_query("SELECT * FROM customer") 
         or die(mysql_error()); 
    tables begins here with the customer id and customer name 
       echo "<table >"; 
       echo "<tr>    
          <th>ID</th> the customer id 
          <th>Name</th> the customer name 
          </tr>"; 

       // loop through results of database query, displaying them in the table 
    the table below display the columns in html using mysql fetch array. all data is displayed. 

    while($row = mysql_fetch_array($result)) { 

         // echo out the contents of each row into a table 
    my purpose is embed the php in html in another way using msqli 
         echo "<tr>"; 
         echo '<td>' . $row['CustomerID'].'</td>'; 
         echo '<td>' . $row['Name']. '</td>'; 
         echo "</tr>"; 
       } 
         echo "</table>"; 
     ?> 
my purpose is embed the php in html in another way using msqli 

回答

0

只需更換所有mysqlmysqli

 $result = mysqli_query("SELECT * FROM customer"); 

     while($row = mysqli_fetch_array($result)) { 

如果你想保持它的簡單

還是不喜歡這樣......

/*Your connection info goes here...*/ 
$mysqli = new mysqli("localhost", "my_user", "my_password", "world"); 

if (mysqli_connect_errno()) { 
    printf("Connect failed: %s\n", mysqli_connect_error()); 
    exit(); 
    } 

    $query = "SELECT * FROM customer"; 

    if ($result = $mysqli->query($query)) { 

    echo "<table ><tr><th>ID</th><th>Name</th></tr>"; 

    /* fetch results by row */ 
    while ($row = $result->fetch_row()) { 
    echo "<tr><td>' . $row['CustomerID'].'</td><td>' . $row['Name']. '</td></tr>'; 
    } 

    /* free the result set */ 
    $result->close(); 
} 

/* close the connection */ 
$mysqli->close(); 
+0

喜做了一些修改$ mysqli = new mysqli(「localhost」,「my_user」,「my_password」,「我的數據庫」,「我的數據庫」); –

+0

無法選擇數據庫<?php // $ mysqli = new mysqli('localhost','root','password','database','tablename'); // if(mysqli_connect_errno()){ // printf(「連接失敗:%s \ n」,mysqli_connect_error()); // exit(); //} $ query =「SELECT * FROM customer where CustomerID ='1'」; 如果($導致= $ mysqli->查詢($查詢)){ 回聲 「

」; ($ row = $ result-> fetch_row()){ echo'​​'。 $行[ '客戶ID']「。​​'。 $行[ '名稱']。 ''; } $ result-> close(); } $ mysqli-> close();?> –

+0

你確定你已經啓動了mysqli_ *,檢查你的PHP.ini文件 – KyleK

相關問題
ID名稱