选择其中id是变量一部分的行

时间:2018-11-04 08:38:28

标签: php mysql

我想选择nreturned是变量一部分的行:

id

我期望$rx = '1-2-3-4'; $st = $db->query("select id, img from abc where id in ('" . $rx . "') order by date desc"); echo $st->rowCount(); // 1 是因为4id23的行。

4 个答案:

答案 0 :(得分:2)

这里是如何使用准备好的语句来确保安全性,获取行数并迭代数据行。

代码(在本地主机上测试成功)

$config = ['localhost', 'root', '', 'dbname'];
$rx = '1-2-3-4';
$values = explode('-', $rx);
$count = sizeof($values);
$placeholders = implode(',', array_fill(0, $count, '?'));
$param_types = str_repeat('i', $count);

if (!$conn = new mysqli(...$config)) {
    echo "MySQL Connection Error: <b>Check config values</b>";  // $conn->connect_error
} elseif (!$stmt = $conn->prepare("SELECT id, img FROM abc WHERE id IN ($placeholders) ORDER BY `date` DESC")) {
    echo "MySQL Query Syntax Error: <b>Failed to prepare query</b>";  // $conn->error
} elseif (!$stmt->bind_param($param_types, ...$values)) {
    echo "MySQL Query Syntax Error: <b>Failed to bind placeholders and data</b>";  // $stmt->error;
} elseif (!$stmt->execute()) {
    echo "MySQL Query Syntax Error: <b>Execution of prepared statement failed.</b>";  // $stmt->error;
} elseif (!$result = $stmt->get_result()) {
    echo "MySQL Query Syntax Error: <b>Get Result failed.</b>"; // $stmt->error;
} else {
    $resultset = $result->fetch_all(MYSQLI_ASSOC);
    echo "<div>Numrows: " , sizeof($resultset) , "</div>";
    foreach ($resultset as $row) {
        echo "<div>Row: {$row['id']} & {$row['img']}</div>";
    }
}

答案 1 :(得分:1)

用于搜索字符串的标准语法是逗号分隔的,因此您可以将破折​​号替换为逗号:

$rx = '1-2-3-4';
$rxc= str_replace("-",",",$rx);

$st = $db->query("select id, img from abc where id in ('" . $rxc . "') order by date desc");

echo $st->rowCount();

答案 2 :(得分:1)

您可以通过许多不同的方式来完成此操作,但是我的想法有两种。希望这会有所帮助:)

1。。尝试通过破折号-爆炸并以逗号,爆炸

$rx = '1-2-3-4';
$st = $db->query("select id, img from abc where id in ('" . implode(',',explode('-',$rx)) . "') order by date desc");
echo $st->rowCount();  // 1

OR

2。。使用-

将破折号,替换为逗号str_replace('-',',',$rx);
$rx = '1-2-3-4';
$st = $db->query("select id, img from abc where id in ('" . str_replace('-',',',$rx) . "') order by date desc");
echo $st->rowCount();  // 1

答案 3 :(得分:1)

您可以通过将-替换为','来轻松地做到这一点,请注意需要额外的引号...

$st = $db->query("select id, img 
         from abc 
         where id in ('" . str_replace("-", "','", $rx) . "') 
         order by date desc");

这会生成...

select id, img from abc where id in ('1','2','3','4') order by date desc