Update is too slow - php

Updating is way too slow:
//class for Database
class MyDB extends SQLite3
{
function __construct()
{
$this->open('/database.db');
}
}
//new db - Object
$db = new MyDB();
if(!$db){
echo $db->lastErrorMsg();
} else {
echo "Opened database successfully\n";
}
This code updates the database and gives me begin_time and length:
//BEGIN
$db->exec('BEGIN;');
//prepare update:
$smt2 = $db->prepare("UPDATE users SET username = :username, full_name = :full_name, is_private = :is_private, is_follower = 1, updated_on = :time, was_follower = NULL WHERE user_id = :usernameId");
//bind parameter
$smt2->bindParam(':usernameId', $usernameId);
$smt2->bindParam(':username', $username);
$smt2->bindParam(':full_name', $full_name);
$smt2->bindParam(':is_private', $is_private);
$smt2->bindParam(':time', $time);
//Prepare second update
$smt3 = $db->prepare("UPDATE users SET followed_on = IfNull(followed_on, :time) WHERE user_id = :usernameId");
//bind parameter
$smt3->bindParam(':usernameId', $usernameId);
$smt3->bindParam(':time', $time);
try {
echo "start\n";
$time_begin = time();
echo $time_begin;
//LOOP
foreach ($followers as $follower) {
$usernameId = $follower->getUsernameId();
$username = $follower->getUsername();
$full_name = $follower->getFullName();
$ProfilPicUrl = $follower->getProfilePicUrl();
$is_private = $follower->isPrivate();
//muss 0 sein, aber ist im mom einfach nur '' bei false.
if(strcmp($is_private, 1) !== 0){
$is_private = 0;
}
$time = time();
//Function, which returns rows, how often an entry exists in db (can only be 0 or 1)
$existence = item_exists($db, 'users', 'user_id', $usernameId);
if($existence)
{
//EXECUTE first update
$smt2->execute();
if(!$smt2){
echo $db->lastErrorMsg();
}
//EXECUTE second update
$smt3->execute();
if(!$smt3){
echo $db->lastErrorMsg();
}
}
}
//COMMIT
$db->exec('COMMIT;');
//TIME
$time_diff = time() - $time_begin;
echo "END: ". $time_diff . "\n";
}
catch (Exception $e) {
echo $e->getMessage();
}
I already use "BEGIN" and "COMMIT" and "prepare". But for an array with 10300 entries it still takes 173 seconds. Where I insert an array with 100.000 entries that took 8 seconds! What makes the update statement in this code so slow?
I merged the two update statements into one:
$smt2 = $db->prepare("EXPLAIN UPDATE users SET followed_on = IfNull(followed_on, :time), username = :username, full_name = :full_name, is_private = :is_private, is_follower = 1, updated_on = :time, was_follower = NULL WHERE user_id = :usernameId");
It still takes 87 seconds.
"EXPLAIN QUERY PLAN" :
0|0|0|SCAN TABLE users

Related

Scraping GPU data seems taking too long

so in my spare time I wanted to make a web to track the GPU price on a e-commerce. I am using PHP and the library Simple HTML DOM to parse the target HTML and it happen every hour from CRON Job.
(Yes, I knew I can make it in Selenium or others to scrape data more efficiently, but in this case just to challenge myself while learning it).
How it work is : Grab data and store it into database. Next, in other table it matches data from database : When the new price of a GPU is the same as latest price, it just update the date and time; If the new price is different with the latest, it make the latest price into old price and update some other things.
The scraping things is coded for a specific e-commerce website;
These variables placement are still scattered a little bit because I tried other
things;
It grab data every hour and logs the seconds on average 40-50, so my assumption is this processing time.
My question is : How can I make the code more efficient compared to my current method?
This is the code to grab the data :
<?php
error_reporting(E_ALL ^ E_WARNING);
require_once 'simple_html_dom.php';
// Database variables here
// ...
try {
$conn = new PDO("mysql:host=$servername;$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Get the URL List
$stmt = $conn->prepare("SELECT id,url FROM url_list");
$stmt->execute();
$url_list = $stmt->fetchAll(PDO::FETCH_COLUMN|PDO::FETCH_UNIQUE);
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
// Scrap the data from a website then return as array
function get_gpu_info(string $targeturl, int $gpu_id)
{
$results = array();
$html = new simple_html_dom();
$html->load_file($targeturl);
if (!empty($html)) {
$div_class = $price = $stock = "";
$div_class = $html->find("#main-pdp-container", 0);
$out_of_stock = $html->find(".css-1igct5v-unf-quantity-editor__input[disabled]", 0);
$price = $div_class->find(".price", 0)->innertext;
$price_int = intval(preg_replace('/[^\d\,]+/', '', $price));
$stock = ($div_class->find(".css-1a29oke p b", 0)->innertext) ?: 0;
if (!empty($price)) {
$results = array(
'GPUID' => $gpu_id,
'PRICE' => $price,
'PRICEINT' => $price_int,
'STOCK' => $stock
);
} else {echo "Price not found";}
} else {echo "URL Not Found";}
return $results;
}
// Scrap every single data from the URL list found
$gpu_data = array_map('get_gpu_info', array_values($url_list), array_keys($url_list));
try {
$time = date("H:i:s");
$date = date("Y-m-d");
$stmt = $conn->prepare("INSERT INTO price_history (gpu_id, price, price_int, stock, update_time, update_date)
VALUES (:insert_gpu_id, :insert_price, :insert_price_int, :insert_stock, :insert_update_time, :insert_update_date)");
$stmt->bindParam(':insert_gpu_id', $insert_gpu_id);
$stmt->bindParam(':insert_price', $insert_price);
$stmt->bindParam(':insert_price_int', $insert_price_int);
$stmt->bindParam(':insert_stock', $insert_stock);
$stmt->bindParam(':insert_update_time', $time);
$stmt->bindParam(':insert_update_date', $date);
foreach ($gpu_data as $data => $val) {
$insert_gpu_id = $val['GPUID'];
$insert_price = $val['PRICE'];
$insert_price_int = $val['PRICEINT'];
$insert_stock = $val['STOCK'];
$stmt->execute();
$stmt2 = $conn->prepare("SELECT COUNT(gpu_id) FROM gpu_data WHERE gpu_id = :gpu_id");
$stmt2->bindValue(':gpu_id', $val['GPUID'], PDO::PARAM_INT);
$stmt2->execute();
$count = (int)$stmt2->fetchColumn();
if($count) {
$stmt4 = $conn->prepare("SELECT old_price, old_price_int, latest_price, latest_price_int, latest_update_time, latest_update_date FROM gpu_data WHERE gpu_id = :gpu_id");
$stmt4->bindParam(':gpu_id', $val['GPUID']);
$stmt4->execute();
$old_data = $stmt4->fetch(PDO::FETCH_ASSOC);
$old_price_int = $old_data['old_price_int'];
$old_latest_price_int = $old_data['latest_price_int'];
$old_price = $old_data['old_price'];
$get_date = $old_data['latest_update_date'];
$get_time = $old_data['latest_update_time'];
$combined_old_date_time = date('Y-m-d H:i:s', strtotime("$get_date $get_time"));
if($old_price_int == $insert_price_int) {
//print_r("Same price");
$stmt3 = $conn->prepare("UPDATE gpu_data SET
stock = :stock,
latest_update_time = :update_time,
latest_update_date = :update_date
WHERE gpu_id = :gpu_id");
} else {
//print_r("Different price");
$stmt3 = $conn->prepare("UPDATE gpu_data SET
old_price = :old_price,
old_price_int = :old_price_int,
old_datetime = :old_datetime,
latest_price = :price,
latest_price_int = :price_int,
stock = :stock,
latest_update_time = :update_time,
latest_update_date = :update_date
WHERE gpu_id = :gpu_id");
$stmt3->bindParam(':old_price', $old_price);
$stmt3->bindParam(':old_price_int', $old_price_int);
$stmt3->bindParam(':old_datetime', $combined_old_date_time);
$stmt3->bindParam(':price', $insert_price);
$stmt3->bindParam(':price_int', $insert_price_int);
print_r("Old price updated");
}
$stmt3->bindParam(':update_time', $time);
$stmt3->bindParam(':update_date', $date);
$stmt3->bindParam(':stock', $insert_stock);
$stmt3->bindParam(':gpu_id', $val['GPUID']);
$stmt3->execute();
//print_r("GPU Data with the same record found and has been updated");
} else {//print_r("ERROR: No GPU Data with that GPU ID has been found");
}
}
//print_r("Price record/s updated successfully");
} catch(PDOException $e) {
echo $sql . "<br>" . $e->getMessage();}
$conn = null;
?>
Thanks in advance!
It's likely you're taking a lot of time to load each page you're scraping. Probably some pages are a lot slower than others. Try doing something like this, to time your load_file() operations, to figure that out.
$loadStartTime = date();
$html->load_file($targeturl);
$loadEndTime = date();
echo $targeturl . ': ' . $loadEndTime - $loadStartTime . ' seconds to load.';
Your dom-romping code looks straightforward enough.
It seems doubtful you have many thousands of rows in your table, so your database stuff should be fast enough.

Prevent null values to being written in SQLite with PDO Php in Online Counter

I have a php script that counts how many users are online at any given time using php, sqlite and PDO. I using apache 2.4.53 and php 8.0.19 both at 64bit. The problem is that null values ​​are often written inside the database which cause the counter to increment unnecessarily and which are not canceled in any way, I have tried everything to eliminate the null values ​​that are written but I have not succeeded:
$deleteNull = $db->prepare('DELETE FROM online WHERE last_activity IS NULL AND id IS NULL');
$deleteNull->execute();
But is not working, I only found a trick that only counts the values ​​that are not null but obviously it is a hack because in the database these null values ​​are there and they remain there without being able to delete them:
$count = $db->query('SELECT COUNT() AS visitors FROM online WHERE last_activity IS NOT NULL AND id IS NOT NULL')->fetch(PDO::FETCH_ASSOC);
In the screenshot you can see 2 columns and 3 rows, 2 rows are legit, the 3rd is fake since is null. The result is that counter counts 3 visitors instead of 2. This happens on Linux machines (CentOS).
Is there any way to modify the script to prevent these null values ​​from being written in database?
<?php
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
$_SESSION['id'] = (isset($_SESSION['id'])) ? $_SESSION['id'] : uniqid();
$secondsToConsiderOffline = 60;
$hitonlinedb = "online.sqlite";
try {
if (!file_exists($hitonlinedb)) {
$db = new PDO("sqlite:" . $hitonlinedb);
$db->exec('CREATE TABLE online(id TEXT PRIMARY KEY NOT NULL, last_activity INTEGER)');
} else {
$db = new PDO("sqlite:" . $hitonlinedb);
}
}
catch (PDOException $e) {
die($e->getMessage());
}
$currentTime = time();
$gracePeriod = $currentTime - $secondsToConsiderOffline;
$id = $_SESSION['id'];
$delete = $db->prepare('DELETE FROM online WHERE last_activity < :gracePeriod OR id = :id');
$delete->bindValue(':gracePeriod', $gracePeriod, PDO::PARAM_INT);
$delete->bindValue(':id', $id, PDO::PARAM_STR);
$delete->execute();
$insert = $db->prepare('INSERT INTO online(id, last_activity) VALUES (:id, :currentTime)');
$insert->bindValue(':id', $id, PDO::PARAM_STR);
$insert->bindValue(':currentTime', $currentTime, PDO::PARAM_INT);
$insert->execute();
$count = $db->query('SELECT COUNT() AS visitors FROM online')->fetch(PDO::FETCH_ASSOC);
if ($count['visitors'] <= 1) {
$visitors = 1;
} else {
$visitors = $count['visitors'];
}
echo $visitors;
$db = null;
?>
download the database to see the bug: online.sqlite
I edited the script like below, is there a good chance the following version will work fine?
<?php
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
$_SESSION['id'] = (isset($_SESSION['id'])) ? $_SESSION['id'] : uniqid();
$secondsToConsiderOffline = 60;
$hitonlinedb = "online.sqlite";
try {
if (!file_exists($hitonlinedb)) {
$db = new PDO("sqlite:" . $hitonlinedb);
$db->exec('CREATE TABLE online(id TEXT PRIMARY KEY NOT NULL, last_activity INTEGER NOT NULL)');
} else {
$db = new PDO("sqlite:" . $hitonlinedb);
}
}
catch (PDOException $e) {
die($e->getMessage());
}
$currentTime = time();
$gracePeriod = $currentTime - $secondsToConsiderOffline;
$id = $_SESSION['id'];
$delete = $db->prepare('DELETE FROM online WHERE (last_activity < :gracePeriod OR last_activity IS NULL) OR (id = :id OR id IS NULL)');
$delete->bindValue(':gracePeriod', ((is_null($gracePeriod) || empty($gracePeriod)) ? time() - 60 : $gracePeriod), PDO::PARAM_INT);
$delete->bindValue(':id', ((is_null($id) || empty($id)) ? uniqid() : $id), PDO::PARAM_STR);
$delete->execute();
$insert = $db->prepare('INSERT INTO online(id, last_activity) VALUES (:id, :currentTime)');
$insert->bindValue(':id', ((is_null($id) || empty($id)) ? uniqid() : $id), PDO::PARAM_STR);
$insert->bindValue(':currentTime', ((is_null($currentTime) || empty($currentTime)) ? time() : $currentTime), PDO::PARAM_INT);
$insert->execute();
$count = $db->query('SELECT COUNT() AS visitors FROM online')->fetch(PDO::FETCH_ASSOC);
if ($count['visitors'] <= 1) {
$visitors = 1;
} else {
$visitors = $count['visitors'];
}
echo $visitors;
$db = null;
?>

I want to write code for check if data already exits then insert in different table

I already write the code to check if table call hm2_history type = commission if yes then insert data into table call hm2_deposit, when I test echo was correct and show the result is :
Connected successfully
354
368
But won't insert into hm2_deposit , I don't know how to adjust it i have a little bit knowledge about php
This is my code
<?php
$servername = "localhost";
$username = "tinybaht_findroom";
$password = "212224";
function setChecked($conn,$params){
$s = $conn->prepare("UPDATE `hm2_history`
SET history_ref_id=-1
WHERE id=:id
");
$s->execute($params);
}
try {
$conn = new PDO("mysql:host=$servername;dbname=tinybaht_findroom", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
$stmt = $conn->prepare("SELECT * FROM hm2_history");
$stmt->execute();
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$a = $stmt->fetchAll();
$plans = array();
foreach($a as $i){
$plans[$i['type']] = 'commissions';
}
$stmt = $conn->prepare("SELECT * FROM hm2_history WHERE id NOT IN(SELECT ref_id FROM hm2_deposits WHERE ref_id > 0) AND type='commissions'");
$stmt->execute();
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$rows = $stmt->fetchAll();
foreach($rows as $k=>$v) {
$plan_type = isset($plans)?:'';
$m = $v['type'];
if (!empty($plan_type)){
echo '<br>'.$v['id'];
if ($m = "commissions" ){
setChecked($conn,array('id'=>$v['id']));
continue;
}
}else{
setChecked($conn,array('id'=>$v['id']));
continue;
}
//deposits
$s = $conn->prepare("INSERT INTO `hm2_deposits`
SET `user_id`=:user_id,
`type_id`=:type_id,
`deposit_date`=:deposit_date,
`last_pay_date`=:last_pay_date,
`status`=:status,
`q_pays`=:q_pays,
`amount`=:amount,
`actual_amount`=:actual_amount,
`ec`=:ec,
`compound`=:compound,
`dde`=:dde,
`unit_amount`=:unit_amount,
`bonus_flag`=:bonus_flag,
`init_amount`=:init_amount,
`ref_id`=:ref_id
");
$v['ref_id'] = $v['id'];
$v['amount'] = $v['amount']*$rate;
$v['actual_amount'] = $v['actual_amount']*$rate;
$v['init_amount'] = $v['init_amount']*$rate;
$v['bonus_flag'] = 1;
$v['type_id']= 9;
unset($v['id']);
$s->execute($v);
$lastDepositId = $conn->lastInsertId();
$date = date('Y-m-d H:i:s');
}
?>
this is photo of my db table name is hm2_deposits hm2_deposits
this is photo of my db table name is hm2_history enter image description here
There is an error in your SQL:
$s = $conn->prepare("INSERT INTO hm2_deposits
SET user_id=:user_id,
type_id=:type_id,
deposit_date=:deposit_date,
last_pay_date=:last_pay_date,
status=:status,
q_pays=:q_pays,
amount=:amount,
actual_amount=:actual_amount,
ec=:ec,
compound=:compound,
dde=:dde,
unit_amount=:unit_amount,
bonus_flag=:bonus_flag,
init_amount=:init_amount,
ref_id=:ref_id
");
Read the proper way to do it at:
https://www.w3schools.com/sql/sql_insert.asp

PDO: Query does not produce the right results the first time

I have three queries on my login script. One select query checks the users' credentials, another to update the last login, and the third one is a select query to see whether the user exists in another table, so if the user exists in the table, go some where. If the user doesn't exist, go somewhere else.
The third query is the one is acting weird. Below:
require_once '../includes/sessions.php';
//echo 'hello';
$employerlogindata = $_POST['employerlogindata'];
$data = json_decode($employerlogindata);
$employeremailfromjs = $data->employeremail;
$employerpasswordfromjs = $data->employerpassword;
//sanitization
$employeremail = htmlentities($employeremailfromjs);
$employerpassword = htmlentities($employerpasswordfromjs);
//PHP validation rules
$validflag = true;
function checkblanks($variable){
if($variable == ''){
$validflag = false;
print_r('Empty Inputs. Please try again.');
}else {
$variable = trim($variable);
$variable = stripslashes($variable);
return $variable;
}
}
checkblanks($employeremail);
checkblanks($employerpassword);
if($validflag == false) {
echo 'You have problematic entries. Try again.';
} else {
try{
$sql = "SELECT EID AS dbeid, EMPLOYER_EMAIL AS dbemail, `PASSWORD` AS dbpwd, EMPLOYER_NAME AS dbcompanyname, LAST_LOGIN AS dblastlogin FROM userpwd WHERE EMPLOYER_EMAIL = :employeremail;";
$query = $conn->prepare($sql);
$query->bindParam(":employeremail", $employeremail);
$query->execute();
//echo "select statement successfully executed";
//echo $sql;
} catch(PDOException $e){
echo "Error connecting to server: " . $e->getMessage();
die;
}
//echo $query->rowCount();
if ($query->rowCount() == 0){
echo "Email/Password combo was not found in the system.";
}else {
$result = $query->fetch(PDO::FETCH_OBJ);
//print_r($result);
$dbeid = $result->dbeid;
$dbemail = $result->dbemail;
$dbpwd = $result->dbpwd;
$dbcompanyname = $result->dbcompanyname;
$dblastlogin = $result->dblastlogin;
//echo $dbeid;
if(password_verify($employerpassword, $dbpwd)){
try{
$sql = "UPDATE userpwd SET LAST_LOGIN = NOW() WHERE EMPLOYER_EMAIL = :employeremail; ";
$query = $conn->prepare($sql);
$query->bindParam(":employeremail", $employeremail);
$query->execute();
}catch (PDOException $e){
echo "Error connecting to server: " . $e->getMessage();
die;
}
$_SESSION['EID'] = $dbeid;
$_SESSION['EMPLOYER_EMAIL'] = $dbemail;
$_SESSION['EMPLOYER_NAME'] = $dbcompanyname;
$_SESSION['LAST_LOGIN'] = $dblastlogin;
//echo "Logged in";
} else {
echo "Email/Password combination is invalid. Please Try Again.";
}
try{
$select = "SELECT EID from e_profile WHERE EID=:eid";
$stmt = $conn->prepare($select);
$stmt->bindParam(":eid", $sessemployerid);
$stmt->execute();
}catch(PDOException $e){
echo "Error connecting to server: " . $e->getMessage();
die;
}
$res = $stmt->fetch();
$eid = $res['EID'];
$count = $stmt->rowCount();
if($stmt->rowCount() == 1){
echo "employerdashboard.php $eid $count";
$stmt->closeCursor();
} else if ($stmt->rowCount() == 0){
echo "e_profile.php $eid $count";
$stmt->closeCursor();
}
}
}
?>
After a set of login credential is successful, the script hits both the second and the third queries. However, the third query takes on the results of the previous ran query. After a second click on the frontend with the same credentials, it produces the right results.
I thought maybe I could find the functionality of mysqli_free_result() in PDO's closeCursor, but that doesn't work. I want it to produce the right result the first time.
Any clues as to why this is happening?
Your variable is out of date (or at least that is my theory), as I said in the comments.
If you have
global $sessemployerid = $_SESSION['EID'];
Then you do
$_SESSION['EID'] = $dbeid;
Then you use $sessemployerid it will not be equal to $_SESSION['EID'] = $dbeid. It will be equal to the previous value of the session when it was assigned, which may or may not be correct. Probably on the first attempt it is wrong, then on subsequent attempts it is correct.
Just to lay it out a bit further:
//you assign $sessemployerid way up here
global $sessemployerid = $_SESSION['EID'];
...
//then you update the session
if(password_verify($employerpassword, $dbpwd)){
try{
$sql = "UPDATE userpwd SET LAST_LOGIN = NOW() WHERE EMPLOYER_EMAIL = :employeremail; ";
$query = $conn->prepare($sql);
$query->bindParam(":employeremail", $employeremail);
$query->execute();
}catch (PDOException $e){
echo "Error connecting to server: " . $e->getMessage();
die;
}
$_SESSION['EID'] = $dbeid; //<--- here you update the session but neglect $sessemployerid
$_SESSION['EMPLOYER_EMAIL'] = $dbemail;
$_SESSION['EMPLOYER_NAME'] = $dbcompanyname;
$_SESSION['LAST_LOGIN'] = $dblastlogin;
//echo "Logged in";
} else {
....
//then you use $sessemployerid, but it has a stale value (sometimes)
$select = "SELECT EID from e_profile WHERE EID=:eid";
$stmt = $conn->prepare($select);
$stmt->bindParam(":eid", $sessemployerid);
To fix this you could use a reference assignment
global $sessemployerid =& $_SESSION['EID'];
This can be demonstrated by this simple code:
$a = 1;
$b =& $a; //initial assignment, with reference
echo $b."\n";
$a = 2; //change the value of $a
echo $b; //$b is auto-magically updated
See it here
Ouputs
1
2
If you do it this way (the "normal" way)
$a = 1;
$b = $a; //initial assignment, normal
echo $b."\n";
$a = 2; //change the value of $a
echo $b; //$b is not updated
The output is
1
1
Alternatively you could simply update the global after changing the session's value:
if(password_verify($employerpassword, $dbpwd)){
...
$_SESSION['LAST_LOGIN'] = $dblastlogin;
global $sessemployerid = $_SESSION['EID'];
}else{
...
Because the value of $sessemployerid is out of sync with $_SESSION['EID'] you will get inconstant behavior depending on if you had updated the session or not on a previous page attempt.
Hope that makes sense.

Having trouble checking mysql database for existing user_id in PHP

I'm having a problem with the following PHP script. Specifically, the part that creates the user_id. This is part of a larger registration.php file that works fine without the section that creates the user_id.
As you can see, it's a while loop that uses a variable, $useridexits, to control the loop. It's set to true by default, so the loop runs. A random number is generated and then checked against the database. If a result is returned, the $useridexists variable is set to true and the loop continues. If no results are returned, $useridexists is set to false, so the loops stops. The number generated is then set to $userid and is then added to the database in the following section.
Here's the code:
//This section creates a new userid for each user.
//This varible is used by the while loop and is set to true by default.
$useridexists = true;
//While loop to create userid and check the database to see if the userid
//already exists. If it does, the while loop keeps going until a unique
//user id is created.
while($useridexists){
// Function to create random user id number.
function randomNumber($length) {
$result = '';
for($i = 0; $i < $length; $i++) {
$result .= mt_rand(0, 9);
}
return $result;
}
// user id value created from randomNumber function.
$number = randomNumber(1);
//query the database to see if the user id already exists
$query = "SELECT * FROM users WHERE user_id = :number";
$query_params = array(':number' => '$number');
try {
// These two statements run the query against the database table.
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Failed to run query: " . $ex->getMessage();
die(json_encode($response));
}
$row = $stmt->fetch();
if ($row){
$useridexists = true;
}else{
$useridexists = false;
}
}
$userid = $number;
// This section adds the values to the database:
$query = "INSERT INTO users (username, password, email, firstname, lastname, user_id) VALUES ( :user, :pass, :email, :firstname, :lastname, :uid)";
//update tokens with the actual data:
$query_params = array(
':user' => $_POST['username'],
':pass' => $_POST['password'],
':email' => $_POST['email'],
':firstname' => $_POST['firstName'],
':lastname' => $_POST['lastName'],
':uid' => $userid
);
//run the query, and create the user
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Failed to run query: " . $ex->getMessage();
die(json_encode($response));
}
$response["success"] = 1;
$response["message"] = "Username Successfully Added! Please log in.";
echo json_encode($response);
$email= mysql_escape_string($_POST['email']);
$username = mysql_escape_string($_POST['username']);
If I comment out this section, everything works:
// user id value created from randomNumber function.
$number = randomNumber(1);
//query the database to see if the user id already exists
$query = "SELECT * FROM users WHERE user_id = :number";
$query_params = array(
':number' => '$number'
);
try {
// These two statements run the query against the database table.
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Failed to run query: " . $ex->getMessage();
die(json_encode($response));
}
$row = $stmt->fetch();
if ($row){
$useridexists = true;
}else{
$useridexists = false;
}
If I don't comment that section out, I don't get any errors, but nothing gets added to the database.
Everything works except the part that checks the database to see if the user_id already exists and changes the $useridexists variable to false, which should escape the while loop. When I add that, nothing gets added to the database.
BTW: I'm using a 1 digit value for testing purposes, but I'll change it to $number = randomNumber(7); once the code actually works.

Categories