conne-6ren">
gpt4 book ai didi

php - mysql 结果存入 php 数组

转载 作者:行者123 更新时间:2023-11-29 19:08:30 24 4
gpt4 key购买 nike

我正在尝试将从 mysql 获得的结果转换为 php 数组谁能帮助我

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "women";
$conn = new mysqli($servername, $username, $password, $dbname);
$id=$_GET['id'];
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT DAY(ADDDATE(`dateDebutC`, `dureeC`)) AS MONTHS,
DAY(ADDDATE(ADDDATE(`dateDebutC`, `dureeC`),`dureeR`))AS DAYS
FROM normalW
where id = '$id'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
foreach($new_array as $array){
echo $row['DAYS'].'<br />';
echo $row['MONTHS'].'<br />';
}
} else {
echo "0 results";
}
$conn->close();
?>

问题已解决,谢谢大家

最佳答案

要回答您的问题,您必须首先声明新数组$new_array = array();

然后循环查询结果以填充数组

while ($row = $result->fetch()) {
$new_array[] = $row;
}

但正如评论之一提到的,您确实应该使用准备好的语句来保护自己免受 SQL 注入(inject)。

    $stmt = $mysqli->prepare("SELECT DAY(ADDDATE(`dateDebutC`, `dureeC`)) AS MONTHS, DAY(ADDDATE(ADDDATE(`dateDebutC`,  `dureeC`),`dureeR`)) AS DAYS FROM normalW where id = ?");

/* bind parameters i means integer type */
$stmt->bind_param("i", $id);

$stmt->execute();

$new_array = array();

while($row = $stmt->fetch()) {
$new_array[] = $row;
}

关于php - mysql 结果存入 php 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43297320/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com