This question already has answers here:
Row count with PDO
(21 answers)
Closed 6 years ago.
I'm not managing to display a message nothing found when the table is empty this query, someone could say where I am going wrong?
<?php
$sqlRead = "SELECT * FROM dados ORDER BY name ASC";
try{
$read = $db->prepare($sqlRead);
$read->execute();
} catch (PDOException $e) {
echo $e->getMessage();
}
while ($rs = $read->fetch(PDO::FETCH_OBJ)){
?>
<h1><?php echo $rs->name; ?></h1>
I found the solution
<?php
$sqlRead = "SELECT * FROM dados ORDER BY name ASC";
try{
$read = $db->prepare($sqlRead);
$read->execute();
$result = $read->rowCount();
} catch (PDOException $e) {
echo $e->getMessage();
}
if($result == 0){
echo "NOTHING FOUND!";
} else {
while ($rs = $read->fetch(PDO::FETCH_OBJ)){
?>
<?php echo $rs->name; ?>
<?php } } ?>
With the code above, can display the message if nothing is found in
the database
Related
This question already has answers here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
How can I prevent SQL injection in PHP?
(27 answers)
Closed 3 years ago.
I'm trying to insert data into the database, it run my coding and i get output as 'SOP data Added Successfully', but the data does not get into the database.
if (isset($_SESSION['admin_id']))
{
include 'databaseConnection.php';
if (isset($_POST['add_btn']))
{
$sop_name = $_POST['sop_name'];
$sop_step = $_POST['sop_step'];
$sop_comment = $_POST['sop_comment'];
$department_id = $_POST['department_id'];
$admin_id = $_SESSION['admin_id'];
$query = "SELECT * FROM sop WHERE sop_name = '$sop_name' && admin_id = '".$_SESSION['admin_id']."'";
$result = mysqli_query($connection, $query);
$count = mysqli_num_rows($result);
if ($count == 1)
{
echo '<script language="javascript">';
echo 'alert("SOP Data Already Existed")';
echo '</script>';
}
else
{
$addSOP = "INSERT INTO sop(sop_name, sop_step, sop_comment, department_id, admin_id) VALUES('$sop_name' , '$sop_step' , '$sop_comment' , '$department_id' ,'$admin_id')";
mysqli_query($connection, $addSOP);
echo '<script language="javascript">';
echo "alert('SOP Data Added Succesfully'); window.location.href='dashboardOrganizationDepartment.php'";
echo '</script>';
}
}
?>
I expect that the result can be post into the database, but it is not. There is also not showing any errors for me to refer.
Can you put some try catch within your insert query, you will get the actual error in query
try {
$addSOP = "INSERT INTO sop(sop_name, sop_step, sop_comment, department_id, admin_id) VALUES('$sop_name' , '$sop_step' , '$sop_comment' , '$department_id' ,'$admin_id')";
mysqli_query($connection, $addSOP);
} catch (Exception $e) {
die($e->getMessage());
}
I am trying to get a mysql data from the table, here -
try
{
$stmt = $user->prepare("SELECT status FROM users");
$result=$stmt->fetch(PDO::FETCH_ASSOC);
if($result['status'] != "Y")
{
$error[] = "Some error warning!";
}
else
{
// Some php codes
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
Here user is a class where prepare is db connection mysql prepare function. The error always prints - "Array!". I am new to php. Any help will be appreciated.
EDIT: I have managed to solve the problem.
You forgot the call of PDOStatement::execute(). See php.net for some examples.
Have you already tried this?
try
{
$stmt = $user->prepare("SELECT status FROM users");
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if($result['status'] != "Y")
{
$error[] = "Some error warning!";
}
else
{
// Some php codes
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
Regarding the Array! output: Did you post the whole code of your script? Were do you try to print the array $error?
I have obviously seen other threads related to the matter and couldn't solve my problem. I am not experienced with php. My file structure is like:
-search/
-index.jade
-search.php
css/
index.css
My index.jade code:
html
head
script(src='https://code.jquery.com/jquery-3.1.0.min.js')
link(href="css/index.css", rel="stylesheet", type="text/css")
body
form(id="search", method="POST", action="search.php")
input(type="text",placeholder="Search for...",name="search_bar")
input(type="submit",name="submit")
My search.php code:
<?php
$SQL_HOST = "peanuts";
$SQL_PSWD = "more_peanuts";
$SQL_USER = "peanuts_again";
$SQL_DB = "no_peanuts";
// jk...
try {
$link = new mysqli($SQL_HOST, $SQL_USER, $SQL_PSWD, $SQL_DB);
} catch (Exception $e) {
echo "PDO connection error: " . $e->getMessage();
exit(1);
}
$search = $_POST['search_bar']."*";
$search_query = $link->prepare("SELECT name FROM products WHERE MATCH(name) AGAINST (? IN BOOLEAN MODE)");
$search_query->bind_param('s', $search);
$search_query->execute();
$search_query->store_result();
$search_rows = $search_query->num_rows;
$search_query->bind_result($product_name);
if($search_rows > 0) {
while($search_query->fetch()) {
echo "Your search returned $search_rows results";
echo "$product_name <br>";
}
}
else {
echo "Your search returned no results, sorry :(";
}
?>
I keep getting: "Cannot POST /search/search.php". Help?
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Alternative for mysql_num_rows using PDO
^ I believe it isn't the same question - The other authors code is different to mine, which needed a different answer. I successfully got my answer from this post and marked it as answered. Everything is working fine now (no help from the other 'duplicate' thread.
I want to display a "No Client Found" message if no results are found, Is there a PDO method to the following code?:
$result = mysql_query($sql) or die(mysql_error()."<br />".$sql);
if(mysql_num_rows($result)==0) {
echo "No Client Found";
I tried the following...
<?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>
}
}
?>
Am I missing something?
I've read: http://php.net/manual/en/pdostatement.rowcount.php but hasn't helped
<?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>
}
}
?>
In PDO, rowCount method is used to count the returned results. Your query must select some thing unique, like an email address or username if you want to check for unique existence, else, if you want at least find one row, change the condition to this:
if ($db->rowCount() == 0)
There is a tutorial: PDO for MySQL developers.
PDOStatement::rowCount() does not return the number of rows affected by a SELECT statement in some databases. Documentation The code below uses SELECT COUNT(*) and fetchColumn(). Also prepared statements and try & catch blocks to catch exceptions.
<?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;
?>
Ok, I have a database full of values with one field value for prospects and another for clients...
I'd like to retrieve only the clients information...
How do I write the function???
UPDATE
Here is the script I tried to write:
<?php
try {
$sql = "SELECT * FROM clients" // WHERE history" or die(mysql_error());
foreach ($dbh->query($sql) as $row) {
$row['history'] = $value;
if ($value == 'clients'){
echo "1212";
} else {
echo "Failed";
return;
}
}
$dbh = null;
} catch (PDOException $e) {
echo "Failed: " . $e->getMessage();
$dbh->rollback();
}
?>
There's no reason to do a rollback here, especially since you haven't started a transaction, and this is just a SELECT, so there's nothing to rollback ... I'm also not sure why you're nulling out $dbh. It's possible to reuse $dbh for other queries, or throughout your application...
Also, your select statement should reflect what data you actually need. If all you need is history, then SELECT history FROM clients[...] is best.
<?php
try {
$sql = "SELECT * FROM clients WHERE history = 'clients'";
$query = $dbh->prepare($sql);
$query->execute();
while($row = $query->fetch())
{
if($row['history'] == 'clients'){
echo '1212';
}
}
} catch (PDOException $e) {
echo "Failed: " . $e->getMessage();
}
?>
Based on your sample script this would do the same but it would place the conditional operator in the query at the database layer instead of within the script at the application layer:
<?php
try {
$sql = "SELECT * FROM clients WHERE history = 'clients'" // WHERE history" or die(mysql_error());
foreach ($dbh->query($sql) as $row) {
echo "1212";
}
$dbh = null;
} catch (PDOException $e) {
echo "Failed: " . $e->getMessage();
$dbh->rollback();
}
?>
Of course, it obviously won't reflect non-client rows like your sample did, but from what I could understand of your question this was what you actually wanted to have happen.