What is Wrong in prepared statement Registration [NO Errors?]? - php

SQL table consist of Id(AI),PID,AID,WEB,ADVERT
My code gets all variables but does not registers anything. But There are two methods of registration.
A. Form includes only to fill PID and Website, where ADVERT is sent hidden.
B. Form includes PID,AID,and website where Advert is sent hidden.
PID is not unique and can be multiple
AID is Unique or 0 if not registered selecting the FORM A in which AID is passed as 0 or NULL
Website is not unique and can be duplicate
If AID is null or 0
IF AID is NULL Check if PID and WEB match [Only Once registered if AID is null]
IF AID is Not NULL Check if AID,PID and WEB is already registered. [Already exist]
LASTLY If Everything is OKAY Register the product in database.
<?php
session_start();
$u = $_SESSION['username']; //GETS Session username to register a product
require('db.php'); //db connection
// ----------------PART A------------
//This gets the ID index Number of user from Member Table
$user = "SELECT id from members WHERE username=?";
$stmt = $ref->prepare($user);
$stmt->bind_param("s", $u);
$rc = $stmt->execute();
if ( false===$rc ) {
die('execute() failed at 1: ' . htmlspecialchars($stmt->error));
}
$stmt->bind_result($ux);
$stmt->fetch();
$stmt->close();
echo "Pass A <br>"; //Testing purpose
// ----------------------------------------------------------
$aid = $_POST['proslot'];
$web = $_POST['web'];
$pid = $_POST['pub'];
$advert = $_POST['advert'];
//-------------INFO DEBUG-----------------
//Testing Codes Variables pass
echo "<br>uid:<br>".$ux; // User ID
echo "<br>advert:<br>".$advert; //Product advertiser
echo "<br>pid:<br>".$pid; //Product id
echo "<br>aid:<br>".$aid; //audit id
echo "<br>web:<br>".$web; //Product website
//------------------------------------------------------
//-------------------PART B-----------------------------
if($_POST['adslot'] != NULL){
//Cheack if AID and WEBSITE matches any existing record.
$valid = "SELECT id from prologger WHERE aid=? AND userweb=?";
$stmt = $ref->prepare($valid);
$stmt->bind_param("is", $aid,$web);
$rc = $stmt->execute();
if ( false===$rc ) {
die('execute() failed at 2: ' . htmlspecialchars($stmt->error));
}
$stmt->store_result();
$val = $stmt->num_rows;
if($val > 0){
echo "Product Already exist :";
$stmt->close();
$ref->close();
exit();
} else{
$stmt->close();
$ref->close();
}
echo "Pass B[1]";
//---------------------PART B[2]-------------------------
} else {
//Cheack if PID,AID and WEBSITE matches any existing record.
$valid = "SELECT id from prologger WHERE pid=? AND aid=? AND userweb=?";
$stmt = $ref->prepare($valid);
$stmt->bind_param("sis", $pid, $aid,$web);
if($_POST['adslot'] == '0' || $_POST['adslot'] == NULL) {
$aid = '0' or $aid = NULL;
} else {
$aid = $_POST['proslot'];
}
$rc = $stmt->execute();
if ( false===$rc ) {
die('execute() failed at 3: ' . htmlspecialchars($stmt->error));
}
$stmt->store_result();
$val2 = $stmt->num_rows;
if($val2 > 0){
echo "Unique product per website Required. This product is already registered to this website:"
$stmt->close();
$ref->close();
exit();
}
$stmt->close();
//------------------------------------------------------
//------------------------PART C------------------------
echo "Pass C";
echo "<br>ROW 1:<br>".$val; //DEBUG VALUE
$sql = "INSERT INTO prologger (uid,advert,pid,aid,userweb) VALUES (?,?,?,?,?)";
$stmt = $ref->prepare($sql) ;
$stmt->bind_param("sssis", $ux , $advert, $pid, $aid , $web); //bind variables
if($_POST['adslot'] == NULL) {
$aid = '0';
} else {
$aid = $_POST['adslot'];
}
$input = $_POST['web'];
$input = trim($input, '/');
// If not have http:// or https:// then prepend it
if (!preg_match('#^http(s)?://#', $input)) {
$input = 'http://' . $input;
}
$urlParts = parse_url($input);
// Remove www.
$web = preg_replace('/^www\./', '', $urlParts['host']);
$rc = $stmt->execute();
if ( false===$rc ) {
die('execute() failed: at 4 ' . htmlspecialchars($stmt->error));
}
$stmt->close();
$ref->close();
echo "Pass Final";
}
//------------------------------------------------------
?>

I fixed it myself. There was an "IF else" Condition that was in this above code Part B
if($_POST['adslot'] != NULL){ //code } else { rest of the code }
where Else needed to be removed
and a $ref->close in the Part B in the else statement of if($val>0) condition which needed to be removed to fix the issue.

Related

How to move data from one table to another table using prepare method in PHP

I have 2 tables in My database and I want to move data from one table to another table.
columns are
question_answer= id,question,answer,added_by,added_on
and
unknown_question=id,question,answer,added_on
On a button click, I want to move data from unknown_question to question_answer So below is my update question function which is currently working.
function updateQuestion($question_id)
{
if (canUpdateQuestion()) {
global $errors, $question, $answer, $isEditting; // pull in global form variables into function
$errors = validateUnknownQuestion($_POST, ['update_question','answer']); // validate form
if (count($errors) === 0) {
// receive form values
$question = $_POST['question'];
$answer = $_POST['answer'];
$sql = "UPDATE unknown_question SET question=?, answer=? WHERE id=?";
$result = modifyRecord($sql, 'ssi', [$question, $answer, $question_id]);
if ($result) {
$_SESSION['success_msg'] = "Unknown Question successfully updated". CHECKMARK;
$isEditting = false;
header("location: " . BASE_URL . "pages-unknown-question-list.php");
exit(0);
} else {
$_SESSION['error_msg'] = "Something went wrong. Could not save Unknown question in Database";
}
}
} else {
$_SESSION['error_msg'] = "You do not have permission to Edit Unknown question!!";
header("location: " . BASE_URL . "pages-unknown-question-list.php");
exit(0);
}
}
here what I am trying
// ACTION: Move question
if (isset($_GET['move_question'])) {
$question_id = $_GET['delete_question'];
deleteQuestion($question_id);
}
function moveToMainQuestion($question_id)
{
if (canUpdateQuestion()) {
global $question// pull in global form variables into function
$sql = "INSERT INTO question_answer SELECT question , answer FROM unknown_question WHERE id=?";
$result = modifyRecord($sql, 'i', [$question_id]);
if ($result) {
$sql = "DELETE FROM unknown_question WHERE id=?";
$result = modifyRecord($sql, 'i', [$question_id]);
if ($result) {
$_SESSION['success_msg'] = "Question Moved successfully". CHECKMARK;
header("location: " . BASE_URL . "pages-unknown-question-list.php");
exit(0);
}
} else {
$_SESSION['error_msg'] = "Something went wrong. Could not save Unknown question in Database";
}
} else {
$_SESSION['error_msg'] = "You do not have permission to Edit Unknown question!!";
header("location: " . BASE_URL . "pages-unknown-question-list.php");
exit(0);
}
}
And my prepare medhod
function modifyRecord($sql, $types, $params)
{
global $conn;
$stmt = $conn->prepare($sql);
$stmt->bind_param($types, ...$params);
$result = $stmt->execute();
$stmt->close();
return $result;
}

changePSW function does not work

can you help out a beginner trying to learn PHP? I wrote a code for changing password without any validations yet, just to change it and it does not work. It's been days I've been trying and couldn't figure out what's wrong. Thanks in advance.
id is variable name in database where id is kept.
db connection is done with first line and it definitely works.
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
session_start();
print_r($_SESSION);
function changePSW()
{
//$password = $_POST['currPassword']; // required
$newPassword = $_POST['newPassword']; // required
//$newPassword2 = $_POST['NewPassword2']; // required
$newPasswordH = password_hash($newPassword, PASSWORD_DEFAULT);
echo($newPassword);
$id = $_SESSION['userID'];
echo($id);
// create PDO connection object
$dbConn = new DatabaseConnection();
$pdo = $dbConn->getConnection();
try {
$statement = $pdo->prepare("SELECT * FROM `users` WHERE id = :id LIMIT 1");
$statement->bindParam(':id', $id);
$statement->execute();
$result = $statement->fetchAll(PDO::FETCH_ASSOC);
echo "SADASDASD";
// no user matching the email
if (empty($result)) {
$_SESSION['error_message'] = 'Couldnt find user';
header('Location: /Online-store/userForm.php');
return;
}
$sql = "UPDATE users SET password=:newPasswordH WHERE id = :id";
// Prepare statement
$stmt = $pdo->prepare($sql);
echo "AFGHANIKO";
// execute the query
$update_status = $stmt->execute(array(':password' => $newPasswordH, ':id' => $id));
echo "IHAAA";
echo($update_status);
if ($update_status === TRUE) {
echo("Record updated successfully" . "\r\n");
echo nl2br("\nPassword: ");
echo ($newPassword);
echo nl2br("\nHashed Password: ");
echo ($newPasswordH);
return true;
} else {
echo "Error updating record";
die();
}
} catch (PDOException $e) {
// usually this error is logged in application log and we should return an error message that's meaninful to user
return $e->getMessage();
}
}
if($_SESSION['isLoggedIn'] == true) {
require_once("database/DatabaseConnection.php");
unset($_SESSION['success_message']);
unset($_SESSION['error_message']);
changePSW();
}
?>
$update_status = $stmt->execute(array(':newPasswordH' => $newPasswordH, ':id' => $id));
This is what I needed to have instead of
$update_status = $stmt->execute(array(':password' => $newPasswordH, ':id' => $id));

Php $var returning no value inside HTML

I have a variable $success set to $success = "Successfully Created" but the var $success has no value inside HTML.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// username and password sent from form
if (isset($_POST['okbutton'])) {
if (isset($_POST['clientuser'], $_POST['clientpass'])) {
$clientuser = $_POST['clientuser'];
$clientpass = $_POST['clientpass'];
$_SESSION['cuser'] = $clientuser;
$_SESSION['cpass'] = $clientpass;
header('Location: trialaccount.php');
die();
}
}
}
try {
if (isset($_SESSION['cuser'])) {
$stmt = $conn->prepare("SELECT user_id FROM user WHERE user_id=:username");
$stmt->bindParam(':username', $_SESSION['cuser']);
$stmt->execute();
$checkdup = $stmt->rowCount();
if ($checkdup == 0) {
$stmt = $conn->prepare("INSERT INTO user (user_id, user_pass, user_online, user_enable, user_start_date, user_end_date, reseller, type) VALUES (:clientuser, :clientpass,0, 1, now(), now() + interval 4 hour, :panelUSER, 'Trial')");
$stmt->bindParam(':clientuser', $_SESSION['cuser']);
$stmt->bindParam(':clientpass', $_SESSION['cpass']);
$stmt->bindParam(':panelUSER', $username);
$stmt->execute();
$success = "Trial Account Created Successfully!";
} else {
$error = "Username '" . $_SESSION['cuser'] . "' is already taken. Try to input unique username." ;
}
}
} catch (PDOException $e) {
echo "Error: Database Error";
}
Inside my HTML, I use echo!
<?php if(isset($success)){ echo $success; } ?>
var $success is returning the value on my personal smartphone,
but no value on other devices.
I dont know what is happening?
Can I use Session instead? ty
Your method does not get the total row count. Therefore, it doesn't go through (if($checkdup == 0)) to set the value for $success. You can try the code below.
Replace:
$stmt = $conn->prepare("SELECT user_id FROM user WHERE user_id=:username");
$stmt->bindParam(':username', $_SESSION['cuser']);
$stmt->execute();
$checkdup = $stmt->rowCount();
With:
$stmt = $conn->prepare("SELECT COUNT(*) FROM user WHERE user_id=:username");
$stmt->bindParam(':username', $_SESSION['cuser']);
$stmt->execute();
$checkdup = $stmt->fetchColumn();

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.

Best Way To Show User Their Photo

Okay so I was wondering what is the best way to show a user their own photo and if my way is safe or what should i change.
url:
http://localhost/project/everyone/myphoto.php?num=2
php code:
$user_id = $_SESSION['user_id'];
if (isset($_GET['num'])) {
$num = $_GET['num'];
if ($stmt = $dbconn->prepare("SELECT 1 FROM t_photos WHERE id ='$num' AND user_id ='$user_id' LIMIT 1")) {
$stmt->execute();
$stmt->store_result();
$rows = $stmt->num_rows;
if ($rows === 1) {
$stmt = $dbconn->prepare("SELECT url,uploaddate FROM t_photos WHERE id = ?");
$stmt->bind_param('i', $num); // Bind "$email" to parameter.
$stmt->execute(); // Execute the prepared query.
$stmt->store_result();
$stmt->bind_result($photopath, $uploadtime); // get variables from result.
$stmt->fetch();
} else {
$error2 = "Error 2";
require 'notfound.php';
die();
}
}
}
html & Php code :
<div id="pathwrap">
<div class="photowrap">
<?php if (isset($photopath)) {
echo '<img src="' . $photopath . '">';
} ?>
</div>
</div>
This is how I would do it with PDO and Exception style:
function requestCurrentUserPhoto(){
if( !isset($_GET['num']) ){
throw new Exception('Bad request. The generated link missing get prop num.');
}
if( !isset($_SESSION['user_id']) ){
throw new Exception('Bad request. The generated link linked to a guest.');
}
$sth = $dbh->prepare('SELECT url,uploaddate FROM t_photos WHERE id = :id AND user_id = :user_id LIMIT 1');
$sth->execute(array(
':id' => (int) $_GET['num'],
':user_id' => (int) $_SESSION['user_id']
));
$result = $sth->fetch(PDO::FETCH_ASSOC);
if( $result === false ){
throw new Exception('Bad request. The generated link linked to a non-existence photo or unauthorized user.');
}
//optional...
if( empty($result['url']) || empty($result['uploaddate']) ){
throw new Exception('Bad database table row. There is a invalid photo row in t_photos');
}
return $result;
}
This code should be safe. And it should also check if the code that is related got any errors.

Categories