我有一个页面,如下面的屏幕截图所示.我们的想法是输入公交车号码和特定路线上所有站点的列表,每行一个.
停靠点已存储在名为“stops”的数据库表中,我需要textarea中每个停靠点的ID.我当前的代码只获取textarea中最后一站的ID.我觉得我错过了什么. ‘busnumber’是我的文本域,’busroute’是我的textarea.如果有人能指出我需要更改的内容,以便将textarea中输入的每个停止点的ID作为数组,我将不胜感激.感谢您提前的时间.
try {
$conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
if(isset($_POST["busnumber"]) && isset($_POST["busroute"])){
$stops = explode(PHP_EOL, $_POST["busroute"]);
$stopsArray = '"' . implode('","', $stops) . '"';
$sql = "SELECT * FROM stops WHERE stop_name IN ($stopsArray)";
echo $sql."";
$query = $conn->prepare($sql);
$query->execute();
$query->setFetchMode(PDO::FETCH_ASSOC);
$results = $query->fetchAll();
foreach($results as $result){
echo $result['stop_id'].' '.$result['stop_name'].'';
}
}
} catch (PDOException $pe) {
die("Could not connect to the database $dbname :" . $pe->getMessage());
}
更新1
我更改了代码如下
$conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
if(isset($_POST["busnumber"], $_POST["busroute"])){
$stops = explode(PHP_EOL, $_POST["busroute"]);
foreach($stops as $stop){
$sql = "SELECT * FROM stops WHERE stop_name = '".$stop."'";
$statement = $conn->query($sql);
echo $sql.'';
$statement->setFetchMode(PDO::FETCH_ASSOC);
$results = $statement->fetchAll();
foreach($results as $result){
echo $result['stop_id'].' '.$result['stop_name'];
}
$statement = null;
}
}
并且仍然得到相同的输出,它只给我textarea中最后一项的ID
解决方法:
我刚刚意识到你上面显示了工作代码.我很抱歉在上面已经有了答案(看看你想要的历史)(*哈哈).在这里,我更新了你的代码(第一个).我更改了显示结果的部分:
try {
$conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
if(isset($_POST["busnumber"]) && isset($_POST["busroute"])){
$stops = explode(PHP_EOL, $_POST["busroute"]);
$stopsArray = '"' . implode('","', $stops) . '"';
$sql = "SELECT * FROM stops WHERE stop_name IN ($stopsArray)";
$query = $conn->prepare($sql);
$query->execute();
if ($query->rowCount() > 0){
while ($row = $query->fetch(PDO::FETCH_ASSOC)){
echo '
'.$row['stop_id'].' '.$row['stop_name'];
}
}else{
echo "No records found...";
}
}
} catch (PDOException $pe) {
die("Could not connect to the database $dbname :" . $pe->getMessage());
}
注意:正如我已经阅读了一些教程,使用while循环比fetchAll()更常规.
标签:php,mysql,pdo,textarea
来源: https://codeday.me/bug/20190717/1487995.html