PHP script to check If user already exists in MySQL database - php

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/

Related

SQL prepared statements. PHP

May be this question will be sort of "stupid-questions", but still...
I'm new to PHP and SQL and I can't understand what I am doing wrong here:
if(isset($_POST[$logButton])) //Checking for login button pressed
{
//Retrieving information from POST method
$uid = $_POST['login'];
$upwd = $_POST['password'];
//SQL Connection
$mysqli = new mysqli('localhost', 'root', '', 'students');
if(!$mysqli)
{
echo "<h1 class='h1A'>Problem accured while connecting to the DB. " . mysqli_error($mysqli) . "</h1>"; //!!!Delete displaying error msg after dev.
}else
{
$sql = "SELECT * FROM login_data WHERE login = ? AND password = ?"; //SQL query
$stmt = $mysqli->prepare($sql) or die("error1"); //No error
$stmt->bind_param('ss', $uid, $upwd) or die("error2");//No error
$stmt->execute() or die("error3");//Giving DB query. No error
$result = $stmt->fetch() or die("error4".mysqli_error($mysqli)); //Putting query's result into assoc array. !!!Delete displaying error msg after dev. No error
echo print_r($result); //It prints out "11" ? ? ?
if(count($result['id']) < 1) //If no rows found.
{
echo "<h1 class='h1A'>Couldn't find account. Please, recheck login and password.</h1>";
die();
}elseif($result['id'] > 1)//If more then 1 row found.
{
echo "<h1 class='h1A'>Caught 9090 error. Contact the administrator, please.".mysqli_error($mysqli)."</h1>";
die();
}elseif($result['id'] == 1) //If only one row's been found.
{
$_SESSION['isLoggedIn'] = true;
redirectTo('/index.php'); //Declared function.
die();
}
}
}
Here is a part of handler function in lib.php file. This file is included to the html-page and the function is used. No errors displayed and when I print_r $result - it prints out 11. Can't get it.
Well, use print_r without echo :
print_r($result);
or pass second parameter to print_r function so it can return string:
echo print_r($result, true);
See http://php.net/manual/en/function.print-r.php for more info.

How to delete the image path from a server using unlink in PHP?

I've almost finished my project but I'm stuck on a small problem I'm hoping to get help with. This is my first PHP/mysqli project and I'm still very "green". Any help is much appreciated.
I have been able to successfully upload and delete images from my database, however I can't seem to get the unlink command to delete the images from my server.
Please find below the code I am using in the background (hotel-imgdelete.php):
<?php
include_once 'db_connect.php';
include_once 'functions.php';
sec_session_start();
// confirm that the 'id' variable has been set
if (isset($_GET['id']) && is_numeric($_GET['id']))
{
// get the 'id' variable from the URL
$id = $_GET['id'];
// delete image from server
$path = "../hotels/";
$image = "name";
unlink($path.$image);
// delete record from database
if ($stmt = $mysqli->prepare("DELETE FROM hotels WHERE id = ? LIMIT 1"))
{
$stmt->bind_param("i",$id);
$stmt->execute();
$stmt->close();
}
else
{
echo "ERROR: could not prepare SQL statement.";
}
$mysqli->close();
// redirect user after delete is successful
header("Location: ../home.php");
}
else
// if the 'id' variable isn't set, redirect the user
{
header("Location: ../delete-hotel-images.php");
}
?>
This is the code I am using to view and select the images to delete
(delete-hotel-images.php)
<?php
// get the records from the database
if ($result = $mysqli->query("SELECT * FROM hotels ORDER BY id"))
{
// display records if there are records to display
if ($result->num_rows > 0)
{
while ($row = $result->fetch_object())
{
$row->id;
echo "<div id='partner'><img src='hotels/" . $row->name . "'></a><br><br>";
echo "<center><a href='#' onclick='delete_user(". $row->id . ")'>Delete</a></center></div>";
}
}
// if there are no records in the database, display an alert message
else
{
echo "No results to display!";
}
}
// show an error if there is an issue with the database query
else
{
echo "Error: " . $mysqli->error;
}
// close database connection
$mysqli->close();
?>
I'm not entirely sure what your filesystem looks like, or what the file is supposed to be, but it looks like you're trying to delete "../hotels/name", since $image is set to the string "name".
I'm assuming this wasn't intentional so that could be the problem there. If, however, you are trying to delete a directory (since it appears to have no file extension) you will need to use "rmdir" and not "unlink".
How are the images laid out on your filesystem?
sorted
if (isset($_GET['id']) && is_numeric($_GET['id']))
{
// get the 'id' variable from the URL
$id = $_GET['id'];
if ($stmt = $mysqli->prepare("SELECT id, name FROM hotels WHERE id=?"));
{
$stmt->bind_param("i", $id);
$stmt->execute();
}
$stmt->bind_result($id, $name);
$stmt->fetch();
$path = "../images/hotels/";
$image = $name;
unlink($path.$image);
$stmt->close();
include_once 'db_connect.php';
include_once 'functions.php';
// delete record from database
if ($stmt = $mysqli->prepare("DELETE FROM hotels WHERE id = ? LIMIT 1"))
{
$stmt->bind_param("i",$id);
$stmt->execute();
$stmt->close();
}
else
{
echo "ERROR: could not prepare SQL statement.";
}
$mysqli->close();
// redirect user after delete is successful
header("Location: ../home.php");
}
else
// if the 'id' variable isn't set, redirect the user
{
header("Location: ../delete-hotel-images.php");
}

the user exists in the database into the Get_Id

This is how I'm going to make a small sign system, it is such that it must find out if username is in the Get_id that you have visited,
GET_Id it is the page ID as it is for example 1 or 10
tilmeldt_navn the user's name on the page.
tilmeldt_email the person's own email.
I think like here in this still:
if ($stmt = $mysqli->prepare('SELECT tilmeldt_navn, tilmeldt_email FROM `tilmeldtOpgave` WHERE `get_id` = ?')) {
$stmt->bind_param('i', $id);
$id = $_GET['id'];
$stmt->execute();
$stmt->bind_result($tilmeldt_navn, $tilmeldt_email);
while ($stmt->fetch()) {
if($tilmeldt_navn == "")
{
echo "finds in the database";
}
else
{
echo "The finds in the database so can not sign me again!";
}
}
$stmt->close();
}
the problem is: it does not appear in the with some of them at all.
The need to find out whether the user has signed up for the get_id and if it has it must take the last of if and when it does not have to be the roof the first in the if
Honestly, it's really hard to understand what you really want to happen. But, since you try to
echo "finds in the database" it seems that you want to check if the record exist from your database.
Just try this:
if(isset($_GET['id'])){
$stmt = $mysqli->prepare("SELECT tilmeldt_navn, tilmeldt_email FROM `tilmeldtOpgave` WHERE `get_id` = ?");
$id= $_GET['id'];
$stmt->bind_param('s', $id);
$stmt->execute();
$stmt->bind_result($id);
$stmt->store_result();
if($stmt->num_rows == 1) //Check if value is returned
{
while($stmt->fetch()) //To fetch the contents of the row
{
echo 'Result Found';
}
}
else {
echo 'No result found';
}
$stmt->close();
$stmt->free_result();
}
$mysqli->close();
?>
Hope this helps.

PDO version of mysql_num_rows($result)==0) [duplicate]

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;
?>

Best way to check for existing user in mySQL database? [duplicate]

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.

Categories