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;
?>
Related
This problem should be simple to resolve, but I can't...
After a request, a condition has to verify if the concerned article really exists, verifying the URL ($_GET).
My code : ( a testing file with simple echos )
$id = $bdd->prepare('SELECT content FROM articles WHERE idArticle = ?');
$id->execute(array($_GET['numArticle']));
while ($dataID = $id->fetch()) {
if (empty($dataID) or $dataID == null or !isset($dataID)) {
echo 'No content';
} else {
echo 'Can load the page';
}
}
$id->closeCursor();
The page behaviour : "can load the page" is writing when numArticle is right, but if it is not, nothing appears, neither an error message or something.
Any idea/advice? Thank you.
One way to do this is by checking the number of rows returned by mysqli:
$id = $bdd->prepare('SELECT content FROM articles WHERE idArticle = ?');
$id->execute(array($_GET['numArticle']));
if($id->num_rows > 0){
echo "can load page";
}else{
echo 'No content';
}
You can use fetchAll() function of PDO then run a foreach loop on data:
$rows = $id->fetchAll(PDO::FETCH_ASSOC);
if(!empty($rows)){
foreach($rows as $row){
echo "content";
}
}
else{
echo "No Content";
}
Assuming you are using Pdo, it looks like you want to be using Pdo's fetchColumn method.
<?php
$stmt = $db->prepare('SELECT content FROM articles WHERE idArticle = ? LIMIT 1');
$stmt->execute(array($_GET['numArticle']));
if ($result = $stmt->fetchColumn()) {
echo 'A result';
} else {
echo 'Db fetch returned false (or could be a string that evaluates to false).';
}
I just switched to PDO from mySQLi (from mySQL) and it's so far good and easy, especially regarding prepared statements
This is what I have for a select with prepared statement
Main DB file (included in all pages):
class DBi {
public static $conn;
// this I need to make the connection "global"
}
try {
DBi::$conn = new PDO("mysql:host=$dbhost;dbname=$dbname;charset=utf8", $dbuname, $dbpass);
DBi::$conn->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
DBi::$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo '<p class="error">Database error!</p>';
}
And in my page:
try {
$sql = 'SELECT pagetitle, pagecontent FROM mypages WHERE pageid = ? LIMIT 1';
$STH = DBi::$conn->prepare($sql);
$STH->execute(array($thispageid)); // $thispageid is from a GET var
}
catch(PDOException $e) {
echo '<p class="error">Database query error!</p>';
}
if ($STH) { // does this really need an if clause for it self?
$row = $STH->fetch();
if (!empty($row)) { // was there found a row with content?
echo '<h1>'.$row['pagetitle'].'</h1>
<p>'.$row['pagecontent'].'</p>';
}
}
It all works. But am I doing it right? Or can I make it more simple some places?
Is using if (!empty($row)) {} an ok solution to check if there was a result row with content? Can't find other decent way to check for numrows on a prepared narrowed select
catch(PDOException $e) {
echo '<p class="error">Database query error!</p>';
}
I would use the opportunity to log which database query error occurred.
See example here: http://php.net/manual/en/pdostatement.errorinfo.php
Also if you catch an error, you should probably return from the function or the script.
if ($STH) { // does this really need an if clause for it self?
If $STH isn't valid, then it should have generated an exception and been caught previously. And if you had returned from the function in that catch block, then you wouldn't get to this point in the code, so there's no need to test $STH for being non-null again. Just start fetching from it.
$row = $STH->fetch();
if (!empty($row)) { // was there found a row with content?
I would write it this way:
$found_one = false;
while ($row = $STH->fetch()) {
$found_one = true;
. . . do other stuff with data . . .
}
if (!$found_one) {
echo "Sorry! Nothing found. Here's some default info:";
. . . output default info here . . .
}
No need to test if it's empty, because if it were, the loop would exit.
I'm creating simple game for Facebook. All users who used app are written to database. I need always check If user already exists Is in database, how to do that correctly?
So I have variable $name = $user_profile['name']; It successfully returns user's name
And this is my part of code to check If user already exists in database.
$user_profile = $facebook->api('/me');
$name = $user_profile['name'];
$mysqli = new mysqli("host","asd","pw","asdf");
echo "1";
$sql = "SELECT COUNT(*) AS num FROM myTable WHERE userName = ?";
echo "2";
if ($stmt = $mysqli->prepare($sql)) {
echo "3";
$stmt->bind_param('s', $name);
echo "4";
$stmt->execute();
echo "5";
$results = $stmt->get_result();
echo "6";
$data = mysqli_fetch_assoc($results);
echo "7";
}
if($data['num'] != 0)
{
echo "bad";
print "user already exists\n";
} else {
echo "good";
$apiResponse = $facebook->api('/me/feed', 'POST', $post_data);
print "No user in database\n";
}
}
This code not working, It should post data on user's wall If user not exists in database. I spent many time to find reason why, but unsuccessfully. After debugging It don't show any errors. To find which line is incorrect after every line I used echo "number" so now I know which line is incorrect. It prints 1 2 3 4 5 and stucks. (everything what are below the code not loading.) So that means this line $results = $stmt->get_result(); is incorrect. But I misunderstood what's wrong with this line?
If I comment this line all code loading (then print 1 2 3 4 5 6 7 No user in database! and It post data on user's wall.) but in this case program always do the same, not checking database.
Also I've tried to change COUNT(*) to COUNT(userName), but the same.
So could you help me, please?
I've read this: Best way to check for existing user in mySQL database? but It not helped me.
P.s. In this case i need to use FB username.
Can you try this, $stmt->fetch() instead of mysqli_fetch_assoc($results)
$mysqli = new mysqli("host","asd","pw","asdf");
echo "1";
/* Create the prepared statement */
$stmt = $mysqli->prepare("SELECT COUNT(*) AS num FROM myTable WHERE userName = ?") or die("Prepared Statement Error: %s\n". $mysqli->error);
/* Execute the prepared Statement */
$stmt->execute();
/* Bind results to variables */
$stmt->bind_result($name);
$data = $stmt->fetch();
if($data['num'] > 0)
{
echo "bad";
print "user already exists\n";
} else {
echo "good";
$apiResponse = $facebook->api('/me/feed', 'POST', $post_data);
print "No user in database\n";
}
/* Close the statement */
$stmt->close();
Ref: http://forum.codecall.net/topic/44392-php-5-mysqli-prepared-statements/
I highly appreciate that you try to help me.
My problem is this script:
<?php include("inc/incfiles/header.inc.php"); ?>
<?php
$list_user_info = $_GET['q'];
if ($list_user_info != "") {
$get_user_info = mysql_query("SELECT * FROM users WHERE username='$list_user_info'");
$get_user_list = mysql_fetch_assoc($get_user_info);
$user_list = $get_user_list['username'];
$user_profile = "profile.php?user=".$user_list;
$profilepic_info = $get_user_list['profile_pic'];
if ($profilepic_info == "") {
$profilepic_info = "./img/avatar.png";
}
else {
$profilepic_info = "./userdata/profile_pics/".$profilepic_info;
}
if ($user_list != "") {
?>
<br>
<h2>Search</h2>
<hr color="#FF8000"></hr>
<div class="SearchList">
<br><br>
<div style="float: left;">
<img src="<?php echo $profilepic_info; ?>" height="50" width="50">
</div>
<?php echo "<h1>".$user_list."</h1>"; ?>
</div>
<?php
}
else {
echo "<br><h3>User was not found</h3>";
}
}
else {
echo "<br><h3>You must specify a search query</h3>";
}
?>
I am creating a search script that takes the mysql databse information and shows the result associated to the search query. My script is the above, but keep in mind the sql connection is established in an extern scipt.
The problem is that i want the script to first check if the user is found with the search query in the username row, and then get the entre information from that user and display it. If the user is not found with the username query, it should try and compare the search query with the name row, and then with the last name row. If no result is displayed it should then return an else statement with an error, e.g. "No user wsas found"
Yours sincerely,
Victor Achton
Do the query as Muhammet Arslan ... but just counting the rows would be faster ...
if(mysql_num_rows($get_user_info)){
//not found
}
you should add a "Limit 1" at the end if you are just interested in one result (or none).
But read about prepared statements
pdo.prepared-statements.php
This is how it should be done in 2013!
Something like this but you don't need 3 queries for this. you can always use OR in mysql statements
$handle1 = mysql_query("SELECT * FROM users WHERE username = $username"); // Username
if (($row = mysql_fetch_assoc($handle1) !== false) {
// username is found
} else {
$handle2 = mysql_query("SELECT * FROM users WHERE name = $name"); // name
if (($row = mysql_fetch_assoc($handle2) !== false) {
// name is found
} else {
$handle3 = mysql_query("SELECT * FROM users WHERE lastname = $lastname"); // Last name
if (($row = mysql_fetch_assoc($handle3) !== false) {
// last name is found
} else {
// nothing found
}
}
}
Already you did ,but you can improve it by using "AND" or "OR" on ur sql statement.
$get_user_info = mysql_query("SELECT * FROM users WHERE username='$list_user_info' or name = '$list_user_info' or last_name = '$list_user_info'");
$get_user_list = mysql_fetch_assoc($get_user_info);
if(empty($get_user_list))
{
echo "No User was found";
}
and you should control $list_user_info or u can hacked.
Here some adapted copy pasting from php.net
Connect
try {
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
foreach($dbh->query('SELECT * from FOO') as $row) {
print_r($row);
}
$dbh = null;
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
fetch data
$stmt = $dbh->prepare("SELECT * FROM users where name LIKE '%?%'");
if ($stmt->execute(array($_GET['name']))) {
while ($row = $stmt->fetch()) {
print_r($row);
}
}
the rest is your programing ...
And do some reading it's very dangerous to use copied code without understanding !
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.