我有一个MySQL数据库(testDB),其中包含一个表(info),其中有几列,id和name。该表有5行数据。
目标是检索整个列name
并将其值存储到数组中。问题是,它只在$ res变量中存储了两个结果(查询的结果),它实际上是两次回应它们(???)
PS:请暂时忽略$ q,这将是用户输入生成的文件的查询字符串(在输入框中)
<?php
class engine {
public function userInput() {
$q = $_GET['q'];
$con = mysqli_connect("localhost","root","","testDB");
if(!$con) {
echo "Impossible to connect: " . mysqli_errno();
} else {
$this->connectMe($con,$q);
}
}
private function connectMe($con,$q) {
$sql = "SELECT `name` FROM `info`"; // will select the entire column `name` on the `info` table
$qry = mysqli_query($con,$sql); // parameter1 is the connection , parameter 2, the sql command
$res = mysqli_fetch_array($qry); // stores the query results into an array
foreach ($res as $value) { // loops through the array and assigns each element to $value
$this->findMatches($value,$q); // parse each element of the array and $q to findMatches function
}
}
private function findMatches($value,$q) {
echo "Array value: " . $value . " random query " . $q . "<br/>";
} // WHY U NO output more than one result !!!???
}
$start = new engine(); // creates the object above
$start->userInput(); // calls the method userInput
?>
答案 0 :(得分:3)
事实并非如此:
$res = mysqli_fetch_array($qry); // stores the query results into an array
mysqli_fetch_array
取一行,你必须把它放在一个循环中:
while($res = mysqli_fetch_array($qry)){
//doSomething
}
答案 1 :(得分:1)
mysqli_fetch_array()
会返回双键数组。 e.g。
SELECT foo, bar FROM ...
会给你
$result = array(
'foo' => 'foo value',
0 => 'foo value',
'bar' => 'bar value',
1 => 'bar value'
);
您可以在代码中使用var_dump($res)
轻松验证这一点。
你可能想要
mysqli_fetch_array($qry, MYSQLI_ASSOC) // field name keys only
mysqli_fetch_array($qry, MYSQLI_NUM) // numerica keys only
代替。
答案 2 :(得分:0)
用这个改变foreach:
while($res = mysqli_fetch_array($qry)) {
$this->findMatches($value, $q)
}