This question already has answers here:
How do I check db query returned results using PHP's PDO
(3 answers)
Closed 6 years ago.
I need little help with my code.
I want to show message when table is empty.
My code is
function category()
{
global $config,$db,$lang;
$result = "SELECT id, name FROM category ORDER BY id";
$stmt = $db->prepare($result);
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
$tpl=parse_tpl('category.php');
$tpl=str_replace("{_HTTP_SERVER_}",$config['http_server'],$tpl);
$tpl=str_replace("{cat_id}",$row['id'],$tpl);
$tpl=str_replace("{cat_title}",kill_tags($row['name']),$tpl);
echo $tpl;
}
if(empty($row)) echo $lang['category_not'];
}
When no records in table show this message
$lang['category_not']
I tried with if(empty($row)) , if (!$row) and if($row == o) but didn't work.
You have to use your code as following way:
if($stmt->rowCount() == 0)
{
echo "nothing found message";
}
else
{
while($row = $stmt->fetch(PDO::FETCH_ASSOC)
{
// code for loop
}
}// else ends here
Related
This question already has answers here:
PDO query is always returning 1 or true
(2 answers)
Closed 3 years ago.
This code is a part of registration code. But it return always "Nickname already exist". I don't understand why.
if (isset($_POST['create'])) {
$nickname = $_POST['nickname'];
$email = $_POST['email'];
$password = $_POST['password'];
$slt1 = "SELECT nickname FROM users WHERE nickname='$nickname'";
$slt2 = "SELECT email FROM users WHERE email='$email'";
$stmt1 = $db->prepare($slt1);
$stmt2 = $db->prepare($slt2);
if($stmt1->execute([$nickname])) {
echo 'Nickname already exist';
} elseif ($stmt2->execute([$email])) {
echo 'email already exist';
} else {
//more code here
}
}
The way you use execute is wrong, and what an execute returns is a Boolean value (TRUE/FALSE) but not the number of rows your query has selected/affected.
So you need to get the count of the rows that your query affects and perform the "if" on that value.
Like this,
$stmt1->execute();
$number_of_rows = $stmt1->num_rows;
if($number_of_rows == 1){
echo 'Nickname already exist';
}
else{
//your code to insert data
}
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());
}
This question already has an answer here:
PHP MySql - Check if value exists
(1 answer)
Closed 8 years ago.
I've got a database table with two columns:
EMAIL_ADDRESS and ACTIVATION_CODE
I need to make the script check if the Activation Code the user has submitted in the URL, matches the Email Address in the table. So far this isn't working.
$email = mysql_real_escape_string($_GET['email']);
$acticode = mysql_real_escape_string($_GET['code']);
$result = mysql_query("SELECT * FROM xActivate WHERE EMAIL_ADDRESS='$email',1");
if ($result = '$acticode') {
echo 'Code is valid';
} else {
echo 'Code is NOT valid';
}
check row with mysql_num_row
if(mysql_num_rows($result)>0){...}
and check valid code with
if(mysql_error())
You need to know the column in the database where the code is stored, also, you need to actually get the data
$email = mysql_real_escape_string($_GET['email']);
$acticode = mysql_real_escape_string($_GET['code']);
$code_found = false;
$result = mysql_query("SELECT * FROM xActivate WHERE EMAIL_ADDRESS='$email',1");
if($result) {
$row = mysql_fetch_assoc($result);
if($row) {
if ($row['codefield'] == $acticode) {
$code_found = true;
}
}
}
if($code_found) {
echo 'Code is valid';
} else {
echo 'Code is NOT valid';
}
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;
?>
This question already has answers here:
How to prevent duplicate usernames when people register?
(4 answers)
Closed 7 months ago.
I am trying to create a user login/creation script in PHP and would like to know the best way to check if a username exists when creating a user. At the moment, I have the following code:
function createUser($uname,$pword) {
$server->connect(DB_HOST,DB_USER,DB_PASS,DB_NAME);
$this->users = $server->query("SELECT * FROM user_list");
while ($check = mysql_fetch_array($this->users) {
if ($check['uname'] == $uname) {
What I'm not sure about is the best logic for doing this. I was thinking of adding a boolean variable to do something like (after the if statement):
$boolean = true;
}
if ($boolean) {
echo "User already exists!";
}
else {
$server->query("INSERT USER INTO TABLE");
echo "User added Successfully";
}
But this seems a little inefficient - is there a more efficient way to do this? Sorry if this has a basic solution - I'm a relatively new PHP programmer.
Use the WHERE clause to get only rows with the given user name:
"SELECT * FROM user_list WHERE uname='".$server->real_escape_string($uname)."'"
Then check if the query results in selecting any rows (either 0 or 1 row) with MySQLi_Result::num_rows:
function createUser($uname,$pword) {
$server->connect(DB_HOST,DB_USER,DB_PASS,DB_NAME);
$result = $server->query("SELECT * FROM user_list WHERE uname='".$server->real_escape_string($uname)."'");
if ($result->num_rows() === 0) {
if ($server->query("INSERT INTO user_list (uname) VALUES ('".$server->real_escape_string($uname)."'")) {
echo "User added Successfully";
} else {
echo "Error while adding user!";
}
} else {
echo "User already exists!";
}
}
This basically involves doing a query, usually during validation, before inserting the member into the database.
<?php
$errors = array();
$alerts = array();
if (isset($_POST['register'])) {
$pdo = new PDO('[dsn]', '[user]', '[pass]');
// first, check user name has not already been taken
$sql = "SELECT COUNT(*) AS count FROM user_list WHERE uname = ?";
$smt = $pdo->prepare($sql);
$smt->execute(array($_POST['uname']));
$row = $smt->fetch(PDO::FETCH_ASSOC);
if (intval($row['count']) > 0) {
$errors[] = "User name " . htmlspecialchars($_POST['uname']) . " has already been taken.";
}
// continue if there are no errors
if (count($errors)==0) {
$sql = "INSERT INTO user_list ([fields]) VALUES ([values])";
$res = $pdo->exec($sql);
if ($res==1) {
$alerts[] = "Member successfully added.";
} else {
$errors[] = "There was an error adding the member.";
}
}
}
The above example uses PHP's PDO, so change the syntax to use whatever database abstraction you use.