Function that check if value exists in sql server - php

Hei,
I need a function in php that checks if a value entered by form is already in database (sql - server -- PDO), and return TRUE or FALSE.
I tried to do this, but I got stuck and didn't found a solution on internet.
could you give me a hint on how to threat the above condition ?
function check_code($code) {
GLOBAL $handler;
$code = check_input($code);
try{
$query2 = $handler -> prepare("SELECT code from stock where code = :code");
$query2 -> execute(array(
':code' => $code
));
return >???<
}
catch(PDOException $e){
echo $e -> getMessage();
} }

return something like row_count(result) > 0

I've never work with sql-server before but I had worked with PDO many times, basically this is how would check in pdo
<?php
function check_code($code)
{
GLOBAL $handler;
$code = check_input($code);
try {
$query2 = $handler->prepare("SELECT code from stock where code = :code");
$query2->execute(array(':code' => $code));
$results = $query2->fetchColumn();
if (count($results) > 0) {
echo "exists";
} else {
echo "does not exist";
}
}
catch (PDOException $e) {
echo $e->getMessage();
}
}
?>
NB: Avoid using the Global var... Stop using `global` in PHP

Related

PDO not working if I re-run a function inside itself

I'm trying to create a system, where my website generates an unique code (current date + 5 random characters) and that code is transferred to a table in my database.
Before function generateNumber() can insert the unique code into the database, it has to check if the code already exist in the database.
If the code doesn't exist, my function works flawlessly. But the problem is when the code can already be found on the database, my website just doesn't do anything (it should just re-run the function).
function generateNumber()
{
global $conn;
$rand = strtoupper(substr(uniqid(sha1(time())),0,5));
$result = date("Ydm") . $rand;
$SQL = $conn->query("SELECT code FROM test WHERE code='$result'");
$c = $SQL->fetch(PDO::FETCH_ASSOC);
if ($c['code'] > 0) { // test if $result is already in the database
generateNumber();
} else {
$sql2 = "INSERT INTO test (code) VALUES (?)";
$stmt2 = $conn->prepare($sql2);
$stmt2->execute([$result]);
return $result;
}
}
try {
$conn = new PDO("sqlite:db"/*, $username, $password*/);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo generateNumber();
}
catch(PDOException $e) {
echo "Error:" . $e->getMessage();
}
$conn = null;
?>
There are no error messages in the console, but I suspect the problem is this part of the code:
if ($c['code'] > 0) { // test if $result is already in the database
generateNumber();
}
Any idea how I can write this function in a better way?
Solution :
if ($c['code'] > 0) { // test if $result is already in the database
// if the code exists in db the function return nothing
// because you are missing a return :
return generateNumber();
}

var_dump and print_r show nothing, can't check it item exists in Database

I have a PDO that is querying a non-existant user in the database to handle user registration. The problem is, var_dump and print_r both do not print anything if the user is not found.
try {
$stmt->execute();
while($row = $stmt->fetch()) {
var_dump($row);
print_r($row);
if($row = null) { // Not working
# if(!isset($row)) { // Not working
# if(empty($row)) { // Also not working
echo "User not found";
} else {
echo $row['realname']."<br>";
}
}
} catch(PDOException $e) {
echo "FATAL ERROR OCCURED:".$e->getMessage();
}
What is happening here? The page is just blank.
php -l index.php repors no syntax errors and the page is not throwing error 500.
Nothing in view source either.
Here is connection details:
try {
$dbh = new PDO('mysql:host=127.0.0.1;dbname=PHP_PDO', "root", "root", array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
));
} catch(PDOException $e) {
die("FATAL ERROR OCCURED");
}
$stmt = $dbh->prepare("SELECT realname FROM users WHERE name = :name" );
$stmt->bindParam(":name", $name);
$name = "mivuckovaca"; // NOT IN DATA BASE
The reason why it's not working, is that you are "assigning" in if($row = null) using 1 equal sign, rather than "comparing" if($row == null) with 2 equal signs (or 3 "if identical", depending on what you want to check for).
Consult: The 3 different equals here on Stack about this.
References:
http://php.net/manual/en/language.operators.assignment.php
http://php.net/manual/en/language.operators.comparison.php
PHP sees the "assignment" as being valid syntax and that is why you are not receiving any errors.
Turns out i had to reorganize the code a bit.
I took the $row = $stmt->fetch(); out of the while loop, and checked the $row seperately. Like this:
$stmt = $dbh->prepare("SELECT realname FROM users WHERE name = :name" );
$stmt->bindParam(":name", $name);
$name = "mivuckovaca"; // NOT IN DATABSE ON PURPOSE
try {
$stmt->execute();
} catch(PDOException $e) {
echo "FATAL ERROR OCCURED:".$e->getMessage();
}
$res = $stmt->fetchAll(); # Replaced fetch() with fetchAll()
if(empty($res)) {
echo "User not found";
} else {
foreach($res as $row) { # replaced while() with foreach()
echo $row['realname'];
}
}

Mysql adds new row instead of updating it

I have integrated google loing to my website. It's working fantastic. When someone logs in via google for the firs time, then a new entry is stored in the database.
But, when he logs in again..only the last login (a column on the table) should be updated...but instead, mysql adds a new row.
What am I doing wrong here?
public function trigger_registration_from_google($fname,$lname,$email)
{
global $conn;
try
{
if(useremailexists($email))
{
$date = date('Y-m-d');
//run update query
//user already exists, only update
try
{
$s = $conn->prepare("UPDATE users set last_login = :last_login where emailid = :email ");
$s->bindParam(':last_login',$date);
$s->bindParam(':email',$email);
$s->execute();
$s->closeCursor();
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
else
{
//insert
//insert now..since he is a new user
$date = date('Y-m-d');
$v=1;
$r="google";
try
{
$s = $conn->prepare("INSERT INTO users(fname,lname,emailid,registeredby,registeredon,last_login,verified) values (:fname,:lname,:emailid,:registeredby,:registeredon,:last_login,:verified)");
$s->bindParam(':fname',$fname);
$s->bindParam(':lname',$lname);
$s->bindParam(':emailid',$email);
$s->bindParam(':registeredby',$r);
$s->bindParam(':registeredon',$date);
$s->bindParam(':last_login',$date);
$s->bindParam(':verified',$v);
$s->execute();
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}//function
Edit
useremailexists
function useremailexists($email)
{
//check if the email exists
global $conn;
try
{
$s = $conn->prepare("SELECT * from users where emailid = :email");
$s->bindParam(':email',$email);
$s->execute();
if($s->rowCount() > 0)
{
return true;
}
else
{
return false;
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}//function
Validate if the function useremailexist return true or false , we can't help you without this piece of code.

PDO self prepare returns an empty string

I connected to the DB via this.
public static function connect() {
try {
self::$db_handle = new PDO("mysql:host=".SERVER.";dbname=".DBNAME,USER, PASSWORD);
self::$db_handle->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
echo "Successful connected to DB<br/>";
}
catch(PDOException $e) {
echo "Conncection failed: " . $e->getMessage();
exit();
}
}
It echoes Successful Connection. So am guessing, there is no issue with the connectivity.
Now I use the following code to query the DB.
$sql=func_get_arg(0);
$params=array_slice(func_get_args(), 1);
$statement=self::$db_handle->prepare($sql);
echo "<br/>Stat: ".$statement."</br>"; //Just for testing purposes
if($statement===false){
echo "False";
return false;
}
if(count($params)==0){
$results=$statement->execute();
}
else
$results=$statement->execute($params);
if($results===false)
return false;
else{
return $statement->fetchAll(PDO::FETCH_ASSOC);
}
I have no clue why it echoes False. The statement which I tried to echo is an empty string.
$sql =
"SELECT * FROM `users` where $key = ?"
and $params is the email address itself.
I am unable to detect my fault. Kindly help. Thanks :)
change it to this
public static function connect()
{
self::$db_handle = new PDO("mysql:host=".SERVER.";dbname=".DBNAME,USER, PASSWORD);
self::$db_handle->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
self::$db_handle->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
$PDO = <yourclass>::connect();
$statement = $PDO->prepare("SELECT * FROM users WHERE key=?");
$statement->execute(array(1));
echo $PDO->lastInsertId();

Call a function after another function has completed

Why would it not work to call the get_accounts() function at the end of the delete_account() function?
function get_accounts() {
require(ROOT_PATH . "inc/database.php");
try {
$results = $db->query("SELECT * FROM account");
} catch (Exception $e) {
echo ("ERROR: Data could not be retrieved from the database." . $e);
exit;
}
$accounts = $results->fetchall(PDO::FETCH_ASSOC);
return $accounts;
}
if(isset($_GET['action']) && ($_GET['action'] == 'delete_account')) {
require("config.php");
require("database.php");
$deleteAccount = $_POST['account'];
try {
$results = $db->prepare("DELETE FROM account WHERE account_id_PK = ?");
$results->bindValue(1, $deleteAccount);
$results->execute();
} catch(Exception $e) {
echo "ERROR: Data could not be removed from the database. " . $e;
exit;
}
echo($deleteAccount);
get_accounts();
};
Basically, I want to run the delete_accounts() function and at the end I would like to run the get_accounts() function, which will refresh the list of accounts on the page after the selected account has been deleted. I can't seem to call a function from within another function, no matter what I try.
Use the finally part of the try catch & remove the 'exit();'
if(isset($_GET['action']) && ($_GET['action'] == 'delete_account')) {
require("config.php");
require("database.php");
$deleteAccount = $_POST['account'];
try {
$results = $db->prepare("DELETE FROM account WHERE account_id_PK = ?");
$results->bindValue(1, $deleteAccount);
$results->execute();
} catch(Exception $e) {
echo "ERROR: Data could not be removed from the database. " . $e;
}finally{
get_accounts();
}
echo($deleteAccount);
}

Categories