^我相信它不是同一个问题 - 其他作者代码与我的不同,需要不同的答案。我成功地从这篇文章中得到了答案,并将其标记为已回答。一切都工作正常(没有其他'重复'线程的帮助。
如果找不到结果,我想显示“No Client Found”消息,是否有以下代码的PDO方法?:
$result = mysql_query($sql) or die(mysql_error()."<br />".$sql);
if(mysql_num_rows($result)==0) {
echo "No Client Found";
我尝试了以下内容......
<?php
$db = new PDO('mysql:host=localhost;dbname=XXXXXXXXXXXX;charset=utf8','XXXXXXXXXXXX', 'XXXXXXXXXXXX');
$query = $db->query('SELECT * FROM client');
if ($query == FALSE) {
echo "No Clients Found";
}
else
{
foreach($query as $row)
{
<some code here>
}
}
?>
我错过了什么吗?
答案 0 :(得分:3)
<?php
$db = new PDO('mysql:host=localhost;dbname=XXXXXXXXXXXX;charset=utf8','XXXXXXXXXXXX', 'XXXXXXXXXXXX');
$query = $db->query('SELECT * FROM client WHERE ID = 10');
if ($query->rowCount() != 1) {
echo "No Clients Found";
}
else
{
foreach($query as $row)
{
<some code here>
}
}
?>
在PDO中,rowCount方法用于计算返回的结果。如果要检查唯一存在,您的查询必须选择一些唯一的东西,如电子邮件地址或用户名,否则,如果您想要至少找到一行,请将条件更改为:
if ($db->rowCount() == 0)
有一个教程:PDO for MySQL developers。
答案 1 :(得分:1)
PDOStatement::rowCount()
不会返回某些数据库中受 SELECT 语句影响的行数。 Documentation以下代码使用SELECT COUNT(*)
和fetchColumn()
。还准备了陈述和try
&amp; catch
阻止捕获异常。
<?php
// Get parameters from URL
$id = $_GET["client"];
try {
$db = new PDO('mysql:host=localhost;dbname=XXXX;charset=utf8', 'XXXX', 'XXXX');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Prepare COUNT statement
$stmt1 = $db->prepare("SELECT COUNT(*) FROM client WHERE client = ?");
// Assign parameters
$stmt1->bindParam(1,$id);
$stmt1->execute();
// Check the number of rows that match the SELECT statement
if($stmt1->fetchColumn() == 0) {
echo "No Clients Found";
}else{
//echo "Clients Found";
// Prepare Real statement
$stmt2 = $db->prepare("SELECT * FROM client WHERE client = ?");
// Assign parameters
$stmt2->bindParam(1,$id);
$stmt2->setFetchMode(PDO::FETCH_ASSOC);
$stmt2->execute();
while($row = $stmt2->fetch()) {
//YOUR CODE HERE FROM
// Title
echo '<div id="portfolio_detail">';
//etc.etc TO
echo '<div><img src="'."/client/".$row[client].'_3.png"/></div>';
echo '</div>';
}//End while
}//End if else
}//End try
catch(PDOException $e) {
echo "I'm sorry I'm afraid you have an Error. ". $e->getMessage() ;// Remove or modify after testing
file_put_contents('PDOErrors.txt',date('[Y-m-d H:i:s]').", myfile.php, ". $e->getMessage()."\r\n", FILE_APPEND);
}
//Close the connection
$db = null;
?>