PHP/mysql:使用数组查询 MySQL 并在数组中获取结果

Posted

技术标签:

【中文标题】PHP/mysql:使用数组查询 MySQL 并在数组中获取结果【英文标题】:PHP/mysql: querying MySQL with an array and getting results in an array 【发布时间】:2011-03-31 03:38:23 【问题描述】:

我有一个数组,$scans。我想用该数组中的所有值查询 mysql 并将我的结果返回到一个数组中。例如,扫描中的样本数据为:

E1234
E2244
E3654

MYSQL 表PARTS 有字段part, size, length, plate, side, type

我想以$output["E1234"][0] 结束该部分的大小结果,1 为长度,等等,我希望数组可以通过 MYSQL 查询进行排序。 (通过SIDE desc, PLATE asc订购)。

现在,我只是单步执行$SCANS 数组并在查询后进行查询,但我无法对所有结果进行正确排序。

这可能吗?这就是我现在正在做的事情,但显然由于每个查询都返回一行然后输出,所以没有可排序性。我希望能够执行一个查询,对数组中的结果进行排序,然后在排序后输出该数据。

    foreach ($scans as $currentscan) 
        $partselect = substr(mysql_real_escape_string($currentscan), 0, 5);

        $query = "SELECT french, length, plate, side, type FROM parts WHERE part = '$partselect' ORDER BY side DESC, plate ASC LIMIT 1";
        $result = mysql_query($query);
        #echo 'query is '.$query.'   <br>';
        $error = mysql_error();
        $num_rows = mysql_num_rows($result);
        if ($num_rows == 0) 
            echo 'BAD PART: '.$currentscan.' '.$partselect.' error is '.$error.'<br \>
            ';
         else 
            $row = mysql_fetch_array($result);
            print $partselect.' is a '.$row['french'].'/'.$row['length'].' - '.$row['type'].' - '.$row['plate'].'('.$row['side'].')<br \>';
        
    ;

编辑:这是代码,因为它现在遵循一些建议:

$scans = explode("\n",$_POST['scans']);

foreach ($scans as $currentscan) 
   if ($currentscan[0] == "E")  //this is a cheap trick to ignore a bad scan inherent in the scanning mechanism
   $partselect = substr(mysql_real_escape_string($currentscan), 0, 5);
   $tempQuery .= 'part = "'.$partselect.'" OR ';

   ;
;//end foreach 
$tempQuery = substr($tempQuery, 0, -3); //remove last OR (fixed substr to 0,-3 to scrip final OR - stephen) 
$tempQuery .= ") ORDER BY side DESC, plate ASC LIMIT 1"; //add on end of query 
$query = "SELECT french, length, plate, side, type FROM parts WHERE ".$tempQuery;
$result = mysql_query($query);
echo $result;
while($row = mysql_fetch_array($result))
   print $row['french']." / ".$row['length']; //just doing something pointless to verify data was pulled.

结果是:

警告:mysql_fetch_array():提供的参数不是第 35 行 /home/foo/bar/sort.php 中的有效 MySQL 结果资源

第 35 行是 while($row = mysql_fetch_array($result))

最终编辑:

它有效。

//DECLARED CONSTANTS//

if (!$_POST)  // Have scans been entered? If not, display the form.
print '
<html>
<body>
Scans:
<form action="index.php" method="post">
<textarea rows="20" cols="6" name="scans" id="scans">
</textarea>
<br />
<input type="submit" value="Submit" />
</body>
</html>
';
 else  //Scans have been entered. Start scan processing logic

//==openDB==//
mysql_connect(SQLSERVER, SQLUSER, SQLPASSWORD) or die("Can not connect to DB server.");
mysql_select_db(DATABASE) or die("Can not connect to Database.");
//==openDB==//

$scans = explode("\n",$_POST['scans']); // Explode posted scans into scans array

foreach ($scans as $currentscan)  // step through each scan
   if ($currentscan[0] == "E")  //Cheap check for real part numbers.
   $partselect = substr(mysql_real_escape_string($currentscan), 0, 5); // Strip off the extraneous data from the scan
   $count$partselect++; //Count instances of particular parts. ideally this would be in an array in the form of $count[$partnumber] so I can easily display that data at the end. each part needs to be displayed every time it's scanned.
   $tempQuery .= 'part = "'.$partselect.'" OR '; //Starts building query

   ;
;//end foreach 
$tempQuery = substr($tempQuery, 0, -3); //remove last OR 

$tempQuery .= ") ORDER BY side DESC, plate ASC"; //add on end of query 
$query = "SELECT part, french, length, plate, side, type FROM parts WHERE (".$tempQuery; //Form beginning of query
$result = mysql_query($query);// execute query
while($row = mysql_fetch_array($result)) // step through results
   for ($i = 0; $i < $count$row['part']; $i++)  //if a part was scanned $count$row['part'] times, display it that many times
   print $row['part']." ".$row['french']." / ".$row['length']." ".$row['plate']."(".$row['side'].")<br>";  //data parsing goes here. this will be expanded.
   ;// close for loop
;//close while loop        
;//close else

?>

【问题讨论】:

Stephen 您想查看已构建的查询。这可能并不完全正确。在迭代之前,检查 num_rows 以查看是否有结果。 【参考方案1】:
<?php
// Make a MySQL Connection
$query = "SELECT * FROM example"; 

$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result) or die(mysql_error());
echo $row['name']. " - ". $row['age'];

?>

感谢http://www.tizag.com/mysqlTutorial/mysqlfetcharray.php

如果您期望多个结果,您也可以这样做:

<?php
// Make a MySQL Connection
$query = "SELECT * FROM example"; 

$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result))
   echo $row['name']. " - ". $row['age'];



?>

为您的评论添加代码:

foreach ($scans as $currentscan) 
   $partselect = substr(mysql_real_escape_string($currentscan), 0, 5);
   $tempQuery .= "(part = ".$partselect." OR";
//end foreach 
$tempQuery = substr($tempQuery,-2); //remove last OR 
$tempQuery .= ") ORDER BY side DESC, plate ASC LIMIT 1"; //add on end of query 
$query = "SELECT french, length, plate, side, type FROM parts WHERE ".$tempQuery;
$result = mysql_query($query);
while($row = mysql_fetch_array($result))
   //do something with row in result set... 

【讨论】:

这不是我真正想要的。更新了代码示例以更加清晰。 @stephen 我更新了你的代码,首先为 $scans 数组中的所有项目构建了查询,然后在结果集之后循环...... 这似乎可行,但 substr 语法似乎不正确,因为在那之后,$tempQuery = "R"(R 和一个空格。) @stephen 更新了 for 循环,它需要一个 .= 对于 tempquery 而不是一个 = 这就是为什么你得到那个坏值的原因。 编辑了原始帖子,其中包含我正在运行的代码及其引发的错误。去阅读mysql_fetch_array【参考方案2】:

您应该做的是在 PHP 中构造一个 WHERE 子句,它允许您选择具有任何部件号的所有行。像这样的:

$whereExpr = array();
for ($i = 0; $i < count($scans); $i++) 
  $whereExpr[] = "part = \"$scans[$i]\"";


$whereExpr = implode(" OR ", $whereExpr);

$query = "SELECT * FROM `parts` WHERE $whereExpr ORDER BY <whatev>";

$result = array();
while ($row = mysql_fetch_array) 
    $result[ $row['part'] ] = $row;

【讨论】:

哦。这会创建一个巨大的查询。我喜欢这个。试试看。 如果这是用户为 $whereExpr 生成的内容,我会小心的,因为您正在打开数据库以进行 SQL 注入:en.wikipedia.org/wiki/SQL_injection 是的,当然你应该使用mysql_real_escape_string之类的。这只是一些快速拼凑起来的示例代码。 此代码用于内部数据库应用程序,不会公开使用,但是会进行转义。【参考方案3】:

MySQL Fetch Array Function

查看您的更新/编辑后,您可以使用 IN 子句

// Represents your $scans array
$arr = array('Hello','World!','Beautiful','Day!');

foreach ($arr as $currentscan) 
    $partselect[] = substr(mysql_real_escape_string($currentscan), 0, 5);


$inExpr = implode("','",$partselect);

$query = "SELECT french, length, plate, side, type FROM parts WHERE part IN('$inExpr') ORDER BY side DESC";

$result = mysql_query($query);

while($row = mysql_fetch_array($result)) 
    print $partselect.' is a '.$row['french'].'/'.$row['length'].' - '.$row['type'].' - '.$row['plate'].'('.$row['side'].')<br \>';

【讨论】:

以上是关于PHP/mysql:使用数组查询 MySQL 并在数组中获取结果的主要内容,如果未能解决你的问题,请参考以下文章

PHP MySQL查询仅输出一个二元素数组

从数据数组(php,mysql)编写循环sql查询

如何从 php mysql 查询中为 jQuery 自动完成准备多维数组?

哪个更快/更高效——大量的小 MySQL 查询或一个大的 PHP 数组?

php mysql 查询字符串数组

从循环查询 PHP MYSQL JSON 合并数组