mysql - 使用 mysqli 而不是 mysql 访问数据库

标签 mysql phpmyadmin

    please find below a script in php that that fetch data from my database company, the database is in phpMyadmin

我知道有安全的方法来获取数据。我的问题是 我可以使用 mysqli 来代替 mysql_query 来改进下面的代码吗?

    <?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 

最佳答案

只需将所有mysql替换为mysqli

      $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();

关于mysql - 使用 mysqli 而不是 mysql 访问数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17283245/

相关文章:

java - 使用 JCalendar 使用复杂的 SQL 查询来检查日期/房间的可用性

mysql - 更新了 rails 3 迁移,但结果在 take :db migrate 后不显示

mysql - 查询按范围限制对记录进行分组

mysql - 在 MySQL 中使用 COUNT(*) 与单个值

MySQL 数据库中的表连接?

mysql - #1062 - key '87' 的重复条目 'PRIMARY'

PHP session 不存储/保存 - php-fpm/nginx/phpmyadmin/centos6

php - 从 cocoa 应用程序中获取 MySql 数据库 - PHP 桥接

c# - 登录loginform并在form 2中看到

mysql - 如何通过phpmyadmin创建触发器?