while mysql\u fetch\u assoc to array

i5desfxk  于 2021-06-25  发布在  Mysql
关注(0)|答案(2)|浏览(297)

我正在尝试将while转换为数组
我有mysql查询:

$shots = mysql_query("SELECT name, ext FROM my_images WHERE item_id=$idnumber") or die(mysql_error());
while($row = mysql_fetch_assoc($shots)) {
 echo "http://www.example.com/images/item/";
 echo $row["name"];
 echo '_thb.';
 echo $row["ext"]; 
 echo '<br>';
}

它给了我:

http://www.example.com/images/item/image1_thb.jpg
http://www.example.com/images/item/image2_thb.jpg
http://www.example.com/images/item/image3_thb.jpg

所以它工作得很好。
我需要把它放到:

$files_to_zip = array(
    'http://www.example.com/images/item/image1_thb.jpg',
    'http://www.example.com/images/item/image2_thb.jpg',
    'http://www.example.com/images/item/image3_thb.jpg',
);

我该怎么做?谢谢

a5g8bdjr

a5g8bdjr1#

你可以用 array_push() .

while($row = mysql_fetch_assoc($shots)) {
   array_push($a, "http://www.example.com/images/item/".$row['name']."_thb.".$row['ext']);
}

print_r($a);

我不建议使用 mysql_ 因为它被弃用了

ukqbszuj

ukqbszuj2#

您应该使用pdo连接到数据库,因为它更安全:http://php.net/manual/en/book.pdo.php
以下教程非常好:http://wiki.hashphp.org/pdo_tutorial_for_mysql_developershttphttp://crewow.com/php-mysql-simple-select-using-pdo-in-bootstrap.php
我想你需要这样的东西:http://php.net/manual/en/pdostatement.fetchall.php

<?php
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();

/* Fetch all of the remaining rows in the result set */
print("Fetch all of the remaining rows in the result set:\n");
$result = $sth->fetchAll();
print_r($result);
?>

结果如下:

Fetch all of the remaining rows in the result set: 

    Array (
        [0] => Array
            (
                [name] => apple
                [0] => apple
                [colour] => red
                [1] => red
            )
        [1] => Array
            (
                [name] => pear
                [0] => pear
                [colour] => green
                [1] => green
            )
        [2] => Array
            (
                [name] => watermelon
                [0] => watermelon
                [colour] => pink
                [1] => pink
            )
    )

相关问题