简体   繁体   中英

Using a 'config.php' file with mysqli

I was recently told to stop using mysql_query() and instead switch to mysqli() . Needless to say, I'm having difficulties making these changes in my code. I'd love to fix what I currently have, however I'm also looking for the most efficient (read least typing) way of looping through the example below.

In my config.php file

<?php
    $host = 'mysql.host.com';
    $user = 'userName';
    $password = 'password';
    $database = 'database';
    $link = new mysqli();
    $link->connect($host, $user, $password, $database);
    if (mysqli_connect_errno()) {
        exit('Connect failed: '. mysqli_connect_error());
    }
?>

In my index.php

$i = 0;
$getFundsQuery = "SELECT * FROM fund";
$getFundsResult = $link->query($getFundsQuery);
while($i < $getFundsResult->num_rows){
    echo "<option value = '".$getFundsResult['fundID']."'>".$getFundsResult['name']."</option>";
    $i++;
}

The immediate problem is that no data is being returned. And as stated above, I'm also looking for the method that would yield the least typing for looping through the results

First of all you can omit the $link->connect(..) with:

$mysqli = new mysqli($host, $user, $password, $database);

Second, loop your results like this:

while ( $row = $getFundsResult->fetch_object() ) {
    echo "<option value = '" . $row->fundID ."'>" . $row->name . "</option>";

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM