我构建了一个字符串数组,我正在尝试查询mySQL表。我想找到与我的单词'AND'分隔的项目列表匹配的所有行。我已经尝试了下面的代码,但没有得到任何结果。如何使用implode改进我的代码以执行正确的查询?
感谢您的帮助。
$conditions = array(
'Monday',
'Tuesday',
'Wednesday'
);
$connection = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
if (mysqli_connect_errno())
{
die("Database connection failed: " . mysqli_connect_error() . " (" . mysqli_connect_errno() . ")");
}
$query = "SELECT * FROM match_tracker ";
// append the conditions
$query.= "WHERE " . implode(" AND ", $conditions);
$result = mysqli_query($connection, $query);
if ($result)
{
echo "Results positive. ";
}
if (!$result)
{
echo "Empty results.";
die("database query failed.");
答案 0 :(得分:4)
您需要确保正确引用implode()
中的值:
$items = "day = '" . implode("' AND day = '", $conditions) . "'"; // day = 'Monday' AND day = 'Tuesday' AND day = 'Wednesday'
$query.= "WHERE " . $items;
您在上面遗忘的一件事是要测试的列,例如我在day
条件中添加的WHERE
列。
如果您想要从周一,周二或周三发生事情的表格中获取数据,那么您可以这样做:
$days = "('" . implode("', '", $conditions) . "')"; // ('Monday', 'Tuesday', 'Wednesday')
$query .= "WHERE day IN" . $days;
答案 1 :(得分:0)
按照您的代码,您的SQL查询应如下所示:"SELECT * FROM match_tracker WHERE Monday AND Tuesday AND Wednesday"
。这是你想要的sql字符串吗?如果你希望有更有意义的东西,你必须通过关联数组。下面的内容会更合适:
$conditions = array(
'Monday' => '1',
'Tuesday' => '4',
'Wednesday' => '3'
);
$connection = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
if (mysqli_connect_errno())
{
die("Database connection failed: " . mysqli_connect_error() . " (" . mysqli_connect_errno() . ")");
}
$query = "SELECT * FROM match_tracker WHERE true";
// append the conditions
foreach($conditions AS $key => $value)
{
$query .= "AND $key = '". mysqli_real_escape_string($connection, $value). "'";
}
$result = mysqli_query($connection, $query);
if ($result)
{
echo "Results positive. ";
}
else if (!$result)
{
echo "Empty results.";
die("database query failed.");
}
我希望这会有所帮助。