I have this PHP script:
require_once('global.php'); //connects to db and various functions used
//select the user's information
$statement = $db->prepare("SELECT * FROM user WHERE id=1");
$statement->execute();
$result = $statement->fetchObject();
//get the chat
$string = $result->chats;
$from = $_REQUEST['from'];
$msg = $_REQUEST['msg'];
$sent = $_REQUEST['sent'];
//see what we should do with the recieved data
if($string == "") {
//there isnt any chats right now, we must add the first ever contact
$string = "<ResultSet><chats><chat><messages><sms><from>{$from}</from><msg>{$msg}</msg><sent>{$sent}</sent></sms></messages><contact>{$from}</contact></chat></chats></ResultSet>";
//send the data back to the user's row in the database
$statement = $db->prepare("UPDATE user SET chats='{$string}' WHERE id=1");
$statement->execute();
} else if($from == $result->name) {
//the user is sending a message to a contact. we now need to get the "to" value.
$to = trim(str_replace("_", " ", $_REQUEST['to']));
//add the sms to the contact's chat
$string = str_replace("</sms></messages><contact>{$to}</contact>", "</sms><sms><from>{$from}</from><msg>{$msg}</msg><sent>{$sent}</sent></sms></messages><contact>{$to}</contact>", $string);
//send the data back to the user's row in the database
$statement = $db->prepare("UPDATE user SET chats='{$string}' WHERE id=1");
$statement->execute();
} else if(strstr($string, "<contact>".$from."</contact>")) {
//The contact that sent the message already exists in this user's row, add the message to the contact's chat
$string = str_replace("</sms></messages><contact>{$from}</contact>", "</sms><sms><from>{$from}</from><msg>{$msg}</msg><sent>{$sent}</sent></sms></messages><contact>{$from}</contact>", $string);
//send the data back to the user's row in the database
$statement = $db->prepare("UPDATE user SET chats='{$string}' WHERE id=1");
$statement->execute();
} else {
//Person who sent the message doesnt exist in the chats, add him.
$string = str_replace("</chats>", "<chat><messages><sms><from>{$from}</from><msg>{$msg}</msg><sent>{$sent}</sent></sms></messages><contact>{$from}</contact></chat></chats>", $string);
//send the data back to the user's row in the database
$statement = $db->prepare("UPDATE user SET chats='{$string}' WHERE id=1");
$statement->execute();
}
The problem is in this else if code:
else if($from == $result->name) {
//the user is sending a message to a contact. we now need to get the "to" value.
$to = trim(str_replace("_", " ", $_REQUEST['to']));
//add the sms to the contact's chat
$string = str_replace("</sms></messages><contact>{$to}</contact>", "</sms><sms><from>{$from}</from><msg>{$msg}</msg><sent>{$sent}</sent></sms></messages><contact>{$to}</contact>", $string);
//send the data back to the user's row in the database
$statement = $db->prepare("UPDATE user SET chats='{$string}' WHERE id=1");
$statement->execute();
}
I am sure the code is running through this else, I have echo'd and confirmed. When I use the $string = str_replace(), I printed the $string and it had indeed replaced. But when I submit the data to the row in the database, nothing happens when I refresh my db. Why does it not work for this else but does for the rest of the if statement (and the if before it)?
It doesn't make sense to me. The code I tried my best to comment it appropriately, if you need something explained just ask.
In case $db is not an instance of MySQLi or PDO but a db wrapper, look at the class that is instantiated as $db and make sure it doesn't start a transaction. If there is a transaction initiated, you will need to commit the transaction so that the changes to the database are applied/saved.
I'm not sure why but I had to change my code up so Iwould send the variables in the execute function instead of in the query. In the query I would put "?" where I want the variables, and in the execute() function I would put an array like
$statement->execute(array($string, 1));
That seems to have fixed my problem.
Related
I'm not sure what am I doing wrong, however when I try to make an update with my API to my database the data is not being updated, I already checked if the name of my table or the name of the columns match and everything looks ok, I also checked if the data it's being received and yes, it is, however it is not updating, do you guys see the error in my code?
$msg['message'] = '';
$storeId = $data->storeId;
$id = $data->id;
//UPDATE CLIENT BY ID
$db_connection = new Database();
$conn = $db_connection->dbConnection();
$update_post = "UPDATE `client` SET name = :name, lastName = :lastName, phoneNumber = :phoneNumber, contactEmail = :contactEmail, address = :address, taxId = :taxId WHERE id = :id";
$update_post_stmt = $conn->prepare($update_post);
//DATA BINDING
$update_post_stmt->bindValue(':name', $data->name,PDO::PARAM_STR);
$update_post_stmt->bindValue(':lastName', $data->lastName,PDO::PARAM_STR);
$update_post_stmt->bindValue(':phoneNumber', $data->phoneNumber,PDO::PARAM_STR);
$update_post_stmt->bindValue(':contactEmail', $data->contactEmail,PDO::PARAM_STR);
$update_post_stmt->bindValue(':address', $data->address,PDO::PARAM_STR);
$update_post_stmt->bindValue(':taxId', $data->taxId,PDO::PARAM_STR);
$update_post_stmt->bindValue(':id', $data->id,PDO::PARAM_INT);
if($update_post_stmt->execute()){
$msg['message'] = 'Updated Successfully';
}else{
$msg['message'] = 'Unable to Update';
}
$closeConnection = $db_connection->closeInstance($conn);
// ECHO MESSAGE IN JSON FORMAT
echo json_encode($msg);
By the way, I'm getting the "Updated Successfully" message
First thing that stands out to me on this is you are declaring your "type" for each field as a PDO::Param_Int, meaning that it is trying to take in your "name", "lastname", "emailaddress", and "address" as an integer instead of a string. This would likely lead to a type-casting error in your code. Try replacing those fields with PDO::PARAM_STR, and you should be closer to a resolution. I believe the data binding will wrap things in the appropriate strings for you as well.
I'm developing a login/register form for my client. Right now I am working on the registration part of the form however I seem to have encountered an issue.
I am trying to append the user's input to a database if it does not currently exist. I'm developing this functionality using PHP version 7. However, the code does not seem to append the data to the database even when telling me it has done so successfully.
Here is code:
<?php
if($_SERVER["REQUEST_METHOD"] == "POST") {
//define variables and set values to null
$email = $code = "";
//set variable values to HTML input
$email = $_POST['email'];
$code = $_POST['code'];
//check if email exists
$stmt = $conn->prepare("SELECT userEmail FROM userDetails WHERE userEmail=?");
$stmt->bind_param("s", $prepemail);
//set parameters and execute
$prepemail = $email;
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows > 0) {
echo "email exists";
return false;
} else {
//$stmt->close(); removed as per #Akintunde-Rotimi's suggestion
//insert email into database
$stmt = $conn->prepare("INSERT INTO userDetails (userEmail) VALUES (?)");
$stmt->bind_param("s", $newemail);
//set parameters and execute
$newemail = $email;
$stmt->execute();
echo "New records created successfully";
}
}
?>
The code successfully connects to the database and even tells me if the user already exists. It just doesn't add the user's email to the database and I can't seem to figure out why.
I have researched methods on how to insert the data into the database using prepared statements as I have done here. I've used W3Schools as a reference but still no luck.
The code doesn't seem to have any obvious spelling errors, so have you tried to catch errors? Replace
$stmt->execute();
with
if(!$stmt->execute()) {
trigger_error("there was an error....".$conn->error, E_USER_WARNING);
}
You can also check how many rows are affected, -1 meaning there was an error.
printf("%d Zeile eingefügt.\n", $stmt->affected_rows);
Also, enabling more errors to be shown (at least for development)
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// ...
Hello Stackoverflow community,
I'm starting to work with PDO soon. I have a trivial question that I do not know how to solve. So, let me know if you guys can help me.
I have a form that aims to update data from a user account in a member space. This form has three fields "Last Name", "Name" and "E-mail".
I don't want that the user register and existing e-mail. However, if the user does not want to update their email and only wants to change the "Last Name" and "Name" fields, the PHP code must allow updating the records in the database.
I created a function to process the form. It is able to prevent the insertion of duplicate records, but it has a problem. If the user does not want to update their email, the function returns that there is already an equal email in the database. In fact, email already exists, so I would like to know how to implement this exception in my code to allow it to update the records when the user does not want to change their e-mail?
Below the function:
function update_admin_profile() {
session_start();
if (isset($_SESSION['id']) AND isset($_SESSION['login'])) {
// get the session variables for another propouse.
$id = $_SESSION['id'];
$pseudo = $_SESSION['login'];
// p - It's the URL parameter. anti_sql_injection is a function to check the parameter.
$p = anti_sql_injection($_GET['p']);
if (isset($_POST['last_name']) AND isset($_POST['name']) AND isset($_POST['email'])) {
$bdd = connexion_bdd();
$query = $bdd->prepare('SELECT * FROM tbl__administrators WHERE email = :email');
$query->execute(array('email' => htmlspecialchars($_POST['email'])));
$count=$query->rowCount();
if ($count == 0 ) {
$update = $bdd->prepare('UPDATE tbl__administrators SET last_name = :last_name, name = :name, email = :email WHERE id = ' . $p);
$update->execute(array(
'last_name' => htmlspecialchars($_POST['last_name']),
'name' => htmlspecialchars($_POST['name']),
'email' => htmlspecialchars($_POST['email'])
));
//The profile was updated.
header('Location: notify.php?m=49');
} else {
//The e-mail already exists!
header('Location: notify.php?m=48');
}
} else {
//Please fill in all fields
header('Location: notify.php?m=41');
}
} else {
//You session is expired. You will be disconnected now. Please, perform the login again and repeat this operation.
header('Location: notify.php?m=7');
}
}
Note: It's function works if I change the e-mail.
Thank you so much for your help.
Have nice day.
If the user does not want to update their email, the function returns that there is already an equal email in the database.
It's very simple. Just add another condition to exclude the current user from the query results
$query = $bdd->prepare('SELECT 1 FROM tbl__administrators WHERE email = ? and id != ?');
$query->execute(array($_POST['email'], $id));
OK I have this code to send an email account verification link
$verifyemail = $clean['email'];
$to = $verifyemail;
$subject = 'Virtual Pierz Close | Verify Your Account';
$message = "Thanks for registering with VPC, on clicking the verification link below, your account will be confirmed, you can then go ahead buy Virtual Properties, donating £5 each time to the worthwhile charity.
http://www.cambrianvacation.co.uk/vpc/registered.php?
email='$verifyemail'&hash='$hash1' ";
$headers = 'From:noreply#cambrianvacation.co.uk'; // Set from headers
mail($to, $subject, $message, $headers);
And then I have this code, that is trying to activate the account by setting active = 1 in the database, which will then be part of the access control logic at login, without active = 1, there is no login, amongst other protection
if(isset($_GET['email']) && !empty($_GET['email']) AND isset($_GET['hash']) && !empty($_GET['hash'])){
// Verify data
$accountemail = $_GET['email'];
$accounthash = $_GET['hash'];
}
$accountActive = 1;
$notactive = 0;
$username = '';
$password2 = '';
$username = 'xxxxxxx';
$password2 = 'xxxxxxx';
$db1 = new PDO('mysql:host=localhost;dbname=xxxxxxxxxxxxx', $username, $password2, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
$db1->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$db1->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try{
$search = $db1->prepare("SELECT email, hash, active FROM users WHERE email = :email AND hash= :hash AND active = :active");
$search->bindParam(':email', $accountemail);
$search->bindParam(':hash', $accounthash);
$search->bindParam(':active', $notactive);
$search->execute();
$colcount = $search->columnCount();
}catch(PDOException $e) {
$e->getMessage();
}
print_r($colcount);
if($colcount === 3){
//try{
$update = $db1->prepare("UPDATE users SET active=:active WHERE email=:email AND hash=:hash AND active = :active");
$update->bindParam(':active', $accountActive);
$update->bindParam(':email', $accountemail);
$update->bindParam(':hash', $accounthash);
$update->bindParam(':active', $notactive);
$update->execute();
//}catch(PDOException $e) {
// $e->getMessage();
//}
However I cannot get the active column to update.
I've also thought about using the GET['email'] could be subject to semantic url attacks, however the logic won't activate the account without the matching hash, which is randomly generated with crypt().........
If anyone can see any security holes in the code, please tell me.........
There really is no reason to make two separate queries here. Why not just have one query to update the record based on hash and email and active = 0? If the count of modified rows = 1, then you had a success, else you had a failure. You probably don't care why it failed, as it would be bad from a security perspective to indicate back to the user why update failed (i.e. bad email, bad hash, already active user, etc.).
That being said, your problem actually lies in the fact that your update uses ? style bindings, while you are using bindParam() with :param style bindings. This won't work since those values are not present in the prepared statement.
So just use this one single query:
UPDATE users SET active = 1 WHERE email = :email AND hash = :hash AND active = 0
Obviously if you think you are going to change the value for active/non-active then feel free to use a parameter for those as well, but my guess is you would want to treat that as a boolean-style tinyint field with only allowable values of 0 and 1, so there is really no point in having the parametrization there.
What you could do, is not include "email" at all.
You could try to gen the url by doing this:
$secret = "1032940fdjsjdkf##$!##%djsfisd";
$hash = md5($email.$secret);
$url = "http://www.cambrianvacation.co.uk/vpc/registered.php?hash=".$hash;
In the update query, you are using "?" for parameters, but then you try to set them as named with bindParam(). You should use
$update->execute(array($accountActive, $accountemail, $accounthash, $notactive));
Or modify the update query this way:
$update = $db1->prepare("UPDATE users SET active=:active WHERE email=:email AND hash=:hash");
Your new parameters are not bound correctly, change:
$update = $db1->prepare("UPDATE users SET active=? WHERE email=? AND hash=? AND active = ?");
To:
$update = $db1->prepare("UPDATE users SET active=:active WHERE email=:email AND hash=:hash");
EDIT - Full Update Code:
$update = $db1->prepare("UPDATE users SET active=:active WHERE email=:email AND hash=:hash");
$update->bindParam(':active', $accountActive);
$update->bindParam(':email', $accountemail);
$update->bindParam(':hash', $accounthash);
$update->execute();
Ok I am making a registry for my website.
First page asks for some personal info
if($error==false) {
$query = pg_query("INSERT INTO chatterlogins(firstName, lastName, gender, password, ageMonth, ageDay, ageYear, email, createDate) VALUES('$firstNameSignup', '$lastNameSignup', '$genderSignup', md5('$passwordSignup'), $monthSignup, $daySignup, $yearSignup, '$emailSignup', now());");
$query = pg_query("INSERT INTO chatterprofileinfo(email, lastLogin) VALUES('$emailSignup', now());");
$userNameSet = $emailSignup;
$_SESSION['$userNameSet'] = $userNameSet;
header('Location: signup_step2.php'.$rdruri);
}
The first query works. The second query works but doesn't save the email...
the session doesn't work but the header works and sends me to the next page
I get no errors even if I comment out header
next page
#session_start();
$conn = pg_connect("host=localhost dbname=brittains_db user=brittains password=XXXX" );
$signinCheck = false;
$checkForm = "";
if(isset($_SESSION['$userName'])) {
$userName = $_SESSION['$userName'];
$signinCheck = true;
$query = pg_query("UPDATE chatterprofileinfo SET lastLogin='now()' WHERE email='$userName'");
}
if(isset($_SESSION['$userNameSet'])) {
$userName = $_SESSION['$userNameSet'];
$signinCheck = true;
$query = pg_query("UPDATE chatterprofileinfo SET lastLogin='now()' WHERE email='$userName'");
}
This is the top starting the session depending on if your logged in or not.
then if I enter in the info here and put it through this
if($error==false) {
$query = pg_query("UPDATE chatterprofileinfo SET aboutSelf='$aboutSelf', hobbies='$hobbies', music='$music', tv='$tv', sports='$sports', lastLogin='now()' WHERE email='$userName'") or exit(pg_last_error());
//header('Location: signup_step3.php'.$rdruri);
}
nothing shows up for on my database from this.
I have no idea where I went wrong
the website is
http://opentech.durhamcollege.ca/~intn2201/brittains/chatter/
For starters, don't put things that aren't strings in single-quotes like that. 'now()' means a literal string "now()"
Also, if you're doing updates to your database you're better of using prepared statements to help prevent against sql injection. In your case, see http://www.php.net/manual/en/function.pg-prepare.php