selecting multiple rows mysqli

2019-09-22 02:23发布

问题:

I wanted to change the below MySQL query to MySQLi(prepared statements) but I don't know how to do it because it has multiple rows to be selected. Can anyone point me the right way.

$check_added_files = mysql_query("select * from `vpb_uploads` where `username` = '".mysql_real_escape_string($username)."' and `firstname` = '' and `image_one` != '' and `image_two` != '' and `image_three` != '' and `image_four` != '' and `image_five` != ''");
        if(mysql_num_rows($check_added_files) == 1)
        {
            echo 'up_to_five_already';
        }

回答1:

The right way would be to change it to PDO

$sql = "select * from vpb_uploads where username=? and firstname=''
        and image_one != '' and image_two != '' and image_three != '' 
        and image_four != '' and image_five != ''";
$stm = $pdo->prepare($sql);
$stm->execute(array($username));
$files = $stm->fetchAll();


回答2:

Mysqli provides the Object Oriented Interface over the classical mysql api. It also supports transactions , prepared Statement, multiple statements.

You can take a look at this http://www.php.net/manual/en/mysqli-result.fetch-object.php if you want to fetch the rows as object

If you want to fetch the rows as associative array, then you can take a look at http://www.php.net/manual/en/mysqli-result.fetch-assoc.php



回答3:

It was pretty simple, I don't know why do I get a vote down every time I ask question.

$mysqli = new mysqli("localhost", "root", "", "database");
    if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
    }

 $username = $_SERVER['REMOTE_ADDR']; 
    $stmt = $mysqli->prepare("select * from `vpb_uploads` where `username` = ? and `firstname` = '' and `image_one` != '' and `image_two` != '' and `image_three` != '' and `image_four` != '' and `image_five` != ''");
    $stmt->bind_param('s', $username);
    $stmt->execute();
    $stmt->store_result();

    if ($stmt->num_rows == 1) {

    echo 'up_to_five_already';
    }


标签: php mysqli