Going from php mysql_* to mysqli


Going from php mysql_* to mysqli

很多人一直告诉我不要再使用mysql_*,而是使用mysqli或PDO。

首先,我选择了Mysqli,因为它看起来很相似。

然而,我在转换我的网站时遇到了一个问题。

我似乎找不到类似于这样获取数据的方法:mysql_result($result, $i, 'COL 2')

下面的代码就是现在的样子,但是我似乎找不到像使用mysql_*那样获取数据的方法。

我是这样做的:

<?php 
    $sql="SELECT * FROM items"; 
    $result=mysqli_query($GLOBALS["___mysqli_ston"], $sql); 
     for ($i = $start; $i < $end; $i++) { 
        if ($i == $total_results) { 
            echo ' 
            <div class="col-sm-12 col-lg-12 col-md-12"><h4>Der er ingen produkter at vise</h4></div> 
            '; 
            break; 
        } 
        echo ' 
        <div class="col-sm-4 col-lg-4 col-md-4" style="min-height:425px;"> 
                        <div class="thumbnail"> 
                            <img src="'.mysql_result($result, $i, 'COL 25').'" alt="" style="max-height:300px;"> 
                            <div class="caption"> 
                                <h4 class="pull-right">'.mysql_result($result, $i, 'COL 20').' point</h4> 
                                <h4 style="color:rgb(220,145,27)">'.mysql_result($result, $i, 'COL 2').'</h4> 
                                <p>Vare nr.: '.mysql_result($result, $i, 'COL 14').'</p> 
                            </div> 
                            <div class="buy"> 
                                <form action="" method="POST" name="buy"> 
                                    <!--- <select name="variant" class="form-control"> 
                                        <option>small</option> 
                                    </select><br> --> 
                                    <button class="btn btn-m center-block" type="submit" style="color:white;background-color:rgb(220,145,27);">Køb</button> 
                                </form> 
                            </div> 
                        </div> 
                    </div> 
        '; 
    }; 
    ?> 

简单地说,mysql_result没有等价物,这意味着您必须重组代码。可以使用whileforeach循环遍历所有行。

<?php
$mysqli = $GLOBALS["___mysqli_ston"];
$sql = "SELECT * FROM items";
if ($result = mysqli_query($mysqli, $sql)) {
    // Query passed, let's continue
    if (mysqli_num_rows($result) > 0) {
        // We have results! Continue
        while ($row = mysqli_fetch_array($query)) {
            echo '<img src="'.$row[24].'" alt="" style="max-height:300px;"><div class="caption"> 
                <h4 class="pull-right">'.$row[20].' point</h4> 
                <h4 style="color:rgb(220,145,27)">'.$row[2].'</h4> 
                <p>Vare nr.: '.$row[4].'</p> 
                </div> ';
        }
    } else {
        echo "No results";
    }
} else {
    echo "Query failed";
}
?> 

您也可以使用$row['columname'],这样在读取代码时更容易获得实际要输出的内容。

如果你对使用mysqli_result一筹莫展,你可以创建自己的函数,它的作用大致相同(来自PHP.net的评论)。(就我个人而言,我会选择上面的例子)。

function mysqli_result($res, $row, $field=0) { 
    $res->data_seek($row); 
    $datarow = $res->fetch_array(); 
    return $datarow[$field]; 
}

无论如何,我强烈建议您不要在全局变量中传递数据库连接,而是包括数据库参数并为每个脚本创建连接。