gpt4 book ai didi

PHP::难以理解如何引用 mysql 选择数组中的特定行...?

转载 作者:行者123 更新时间:2023-11-30 22:32:46 26 4
gpt4 key购买 nike

我只是没有在这里建立联系,我没有得到帮助我启发自己的搜索结果。

我正在从 mysql 中提取数据到一个数组中。但是我完全想念稍后如何引用特定行。

try {
$conn = new PDO('mysql:host=localhost;dbname=FermentorDB', $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);



$chamberstate = $conn->query('SELECT * FROM ChamberState' . $conn->quote($mac));


foreach($chamberstate as $row) {
$chamber = $row['Chamber'];
$schedule = $row['Schedule'];
$runningnow = $row['RunningNow'];
$temp = $row['ChangingTemp'];
$array = array($chamber,$schedule,$runningnow,$temp);


}


} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();

好的,所以所有数据都在数组中。但是,我该如何打印 $schedule where $chamber == 1 呢?

我因为没有得到这个而感到很愚蠢......

最佳答案

您接近原始代码,但每次循环时 $array 变量都被覆盖。如果您需要访问整个页面中的值,您应该能够使用这样的方法来实现。

<?php
try {
$conn = new PDO('mysql:host=localhost;dbname=FermentorDB', $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$chamberstate = $conn->query('SELECT * FROM ChamberState' . $conn->quote($mac));

/* Populate this array for later use */
$chambers=array();

foreach( $chamberstate as $row ) {
$chamber = $row['Chamber'];
$schedule = $row['Schedule'];
$runningnow = $row['RunningNow'];
$temp = $row['ChangingTemp'];

/* This will overwrite any values in the $array variable with each iteration through the loop */
/*
$array = array( $chamber, $schedule, $runningnow, $temp );
*/

$chambers[]=array( 'chamber'=>$chamber, 'schedule'=>$schedule, 'running'=>$runningnow, 'temp'=>$temp );
}


/* later, when you need to access the various values, you can reference via the index */
echo $chambers[ 1 ]['chamber'];

/* or */
echo $chambers[ 23 ]['schedule'];


} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
?>

关于PHP::难以理解如何引用 mysql 选择数组中的特定行...?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33426140/

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