I am having a problem with my update query when users request a password reset.
It simply does nothing, It does show that the password has been reset according to the alert command, but the database does not reflect the update...
Any assistance would be great as I cannot see where I am going wrong...
if(isset($_GET["acc"]) && isset($_GET["np"])){
$acc=decrypt(htmlspecialchars($_GET["acc"]));
$np=decrypt(htmlspecialchars($_GET["np"]));
//var_dump($acc);
//var_dump($np);
$query="UPDATE `master_profile` SET `password`=? where `email_address`=?";
if ($stmt = $connection_link->prepare($query)){
// Bind the variables to the parameter as strings.
$stmt->bind_param("ss",$np,$acc);
// Execute the statement.
if($stmt->execute()){
?>
<script>
alert('Your password has been reset. Please login with your new password.');
</script>
<?
//echo "Updated {$stmt->affected_rows} rows";
}else{
echo '<h1>An Error Has Occoured. Please try again later.</h1>';
}
if ($stmt->errno) {
echo "FAILURE!!! " . $stmt->error;
}
// Close the prepared statement.
$stmt->close();
}
}
Update
Changed if($stmt->execute(array($np,$acc))){} as suggested below but it simply gives me an error An Error Has Occoured. Please try again later., How can i catch this error and report the proper error?
I have tried $stmt->error; and $connection_link->error; but both just give an empty value.
Because you are using anonymous placeholders I think you need to omit your bind statement. Instead you would place the parameters in the execute as an array and in order of appearance in the statement
if($stmt->execute(array($acc, $np)){}
You would omit this line
$stmt->bind_param("ss",$np,$acc);
Related
I want to delete some rows from my table. But when I click delete, this just show me a blank page. I'm sure about id value and my db connection.
This is my code:
// connect to the database
include('connect-db.php');
// 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 record from database
if ($stmt = $mysqli->prepare("DELETE FROM my_table 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: Dashboard.php");
} else {
// if the 'id' variable isn't set, redirect the user
header("Location: Dashboard.php");
}
There is a similar question MySQLi Prepared Statement not executing
. Basically, you can try running the SQL directly in the database to see if you get any errors. Also confirm that the database user has delete permissions and that the id is stored as an integer in your database.
First I'd suggest you use the $_POST method, you can read more about it GET vs. POST.
Try using bindValue() instead of bindParam(), I believe something else needs to be declared for bindParam() I forget (I'm new at PHP too).
I have been going through the password_hash() and password_verify() methods in PHP and I've been trying to include that in my code. I can't seem to get it to work, I've gone through series of googling and even some of the questions here on SO but they don't seem to resolve the issue.
My column length in the database is 255. When I try to run the code, I get the $loginerror message. Here's my code block. Please what am I doing wrong.
$signin_email=$_POST['signin_email'];
$signin_password=$_POST['signin_password'];
if($valid){
require_once 'scripts/connect_to_mysql.php';
$sql = "SELECT First_name, Last_name,Password FROM customer WHERE Email=? AND Password=? LIMIT 1";
$stmt=$conn->prepare($sql);//preparing the statement
if(!$stmt){
echo "Unable to prepare: ".$conn->errno. " " .$conn->error;
}
//executing the statement
//$date=date('d m Y h:i:s');
if(!$stmt->bind_param('ss', $signin_email, $signin_password)){//bind parameters to sql statement. i=integer, s=string, b=blob, d=double
echo "Binding parameters failed: ".$stmt->errno. " " . $stmt->error;
}
if(!$stmt->execute()){//executing the statement
echo "Statement Execution failed: ". $stmt->error;
}
if(!$stmt->bind_result($dbfirstname,$dblastname,$dbpassword)){// used to bind variables to a prepared statement for result storage
echo "Unable to bind results to variables: ".$stmt->error;
}
$stmt->store_result();
//echo $stmt->num_rows;
echo $dbpassword;
if(password_verify($signin_password, $dbpassword)){
if($stmt->num_rows===1){//to check if username and password actually exists
while($row=$stmt->fetch()){
$user=$dbfirstname. " ". $dblastname;
echo $user;
}
/*$_SESSION['user']=$user;
header('location:logintest.php');
exit();*/
}
}
else{
//$error="Invalid Email address/Password. Please try again";
$loginerror= "Invalid Email address/Password. Please try again";
}
$stmt->close();//closing the prepared statement
$conn->close();//closing the connection
}
Problem does not lie in password_verify but in way that you build your query:
`$sql ="SELECT First_name, Last_name,Password FROM customer WHERE Email=? AND Password=? LIMIT 1";
You bind $signin_password to that query and it contains not hashed value from $_POST.
There are 2 solutions:
1) remove AND Password=? from your query - you will check your password with password_verify
2) change $signin_password to:
$signin_password=password_hash($_POST['signin_password']);
(but this way using password_verify is kind of irrelevant.
$signin_password=$_POST['signin_password'];
$hash = password_hash($dbpassword, PASSWORD_DEFAULT);
if (password_verify($signin_password, $hash))
{
echo 'Password is valid!';
}
else
{
echo 'Invalid password.';
}
Try with this :) Better option is just build your own query.
i try to implement a register form and try to check via php and jQuery if a user already registered with a certain email.
here is my piece of code:
if(endsWith($email, 'domain.tld'))
{
$result = $database->prepare("SELECT id FROM users WHERE email LIKE ?");
$result->bind_param('s', $email);
//echo $email;
$result->execute();
//echo $result->execute();
//echo $result->num_rows;
//exit();
if($result->num_rows == 0)
{
echo'ok';
}
else {
echo 'duplicate';
}
$result->close();
}
else {
echo 'validation failed';
}
I used the commented echos and exit() to debug my code. The problem is that the database holds the user user#domain.tld and the script shows me in the echo "user#domain.tld10". So the statement ist executed successful but no rows are returned. If i execute the statement
SELECT id FROM users WHERE email LIKE "user#domain.tld"
i get the id (in this case 11) returned.
My question is, how can i debug this php script better and the biggest question is, why is my scipt not working properly?
Thank you so much in advance!
Use before num_rows
$result->store_result();
The use of mysqli_stmt_num_rows() depends on whether or not you used
mysqli_stmt_store_result() to buffer the entire result set in the
statement handle.
Docs
i have this code but i got two errors. I put in the comments the errors
if(!empty($_POST['email']) && validateEmail($email)) {
$email = $_POST["email"];
if ($sql = $db->prepare("select email from users where email=?")) {
$sql->bind_param('s', $email);
$sql->execute();
$sql->bind_result($email);
while ($sql->fetch()) {
$salt = "PiuwrO1#O0rl#+luH1!froe*l?8oEb!iu)_1Xaspi*(sw(^&.laBr~u3i!c?es-l651";
$password = md5($salt . $userExists["email"]);
$pwrurl = "www.yoursite.com/reset_password.php?q=" . $password;
$mailbody = "Dear user,<br><br>If this e-mail does not apply to you please ignore it. It appears that you have requested a password reset at our website www.yoursitehere.com<br>
To reset your password, please click the link below. If you cannot click it, please paste it into your web browser's address bar.<br> <a href='$pwrurl'>$pwrurl</a> <br> <br>
Thanks,\nThe Administration";
$mail->MsgHTML($mailbody);
$mail->AddAddress("dxxb#hotmail.com","Nome da Pessoa");
$mail->IsHTML(true);
if(!$mail->Send()) {
echo "Deu erro: " . $mail->ErrorInfo;
} else {
echo "Enviado com sucesso";
}
}
$sql->close();
$db->close();
}
($sql = $db->prepare('insert into password_reset (code) values (?)')); // Warning: mysqli::prepare() [mysqli.prepare]: Couldn't fetch mysqli in
$sql->bind_param('s', $password); // Fatal error: Call to a member function bind_param() on a non-object
$sql->execute();
$sql->fetch();
$sql->close();
$db->close();
}
all code works fine, but now i need to insert the salt in the db but i can't, and i don't know why
thanks
Edited code to the last version
After you execute a query, fetch returns one result. There may be more -- there may be many, many more -- so you should be calling fetch in a loop to get them all. You aren't supposed to prepare a new query until you've finished dealing with the old one, which would usually mean fetching every row of the result and closeing (in your case) $sql. Otherwise, the database is still in the middle of answering one request when you're trying to issue another one.
The first error says it all - you can't have more than 1 prepared statement/query "in flight" at once. You've not finished fetching data from the first query (select email ...) when you tried to prepare another statement (insert into ...).
hello im trying to set custom errors. i got a form. actions to post.php i dont want form to go post.php for errors i need to set errors in same page. i tried
$sql = "
INSERT INTO yazilar (baslik, spot, spot_kisa, spot_resim, spot_resim_isim, icerik, kategori, tiklanma, eklemetarihi)
VALUES
('$_POST[baslik]','$_POST[spot]','$_POST[spot_kisa]','$_POST[spot_resim]','$_POST[spot_resim_isim]','$_POST[icerik]','$_POST[kategori]','$_POST[tiklanma]','$_POST[tarih]')
";
$sonuc = mysql_query($sql);
<?
if ($sonuc) {
echo ("<p class='msg done'>Yeni icerik basarili bir sekilde eklendi.</p>");
}
if(! $sonuc) {
echo ("<p class='msg warning'>Ekleme basarisiz oldu.</p>");
}
?>
this always shows Yeni icerik basarili bir sekilde eklendi. this.
help me plx
Your query is valid and it inserts data sucsesfully, therefore MySql_Query() returns true, which in turn "triggers" the first if, but not the second.
See documentation for return values of MySql_Query.
If you want validation you have to write it.
also: your two if statements can be refactored into one. Look at the if/else syntax
If you're trying to have your errors show up in the submitting form just move your post.php code into your form page and condition it like this:
<?php
if(isset($_POST['baslik'])) {
$sql = "
INSERT INTO yazilar (baslik, spot, spot_kisa, spot_resim, spot_resim_isim, icerik, kategori, tiklanma, eklemetarihi)
VALUES
('$_POST[baslik]','$_POST[spot]','$_POST[spot_kisa]','$_POST[spot_resim]','$_POST[spot_resim_isim]','$_POST[icerik]','$_POST[kategori]','$_POST[tiklanma]','$_POST[tarih]')
";
$sonuc = mysql_query($sql);
if ($sonuc) {
echo ("<p class='msg done'>Yeni icerik basarili bir sekilde eklendi.</p>");
exit;
}
else {
$error = "<p class='msg warning'>Ekleme basarisiz oldu.</p>";
}
}
?>
// form code here
<?php if(isset($error)) { echo $error; } ?>
// around where you'd like the error to display
Now if the action is a success the success message will display with nothing else, otherwise the form will be redisplayed with the error message where you positioned it. Also, please see soulmerge's comments on SQL injection, it's a serious security risk that can be easily avoided.
replace
$sonuc = mysql_query($sql);
with this
$sonuc = mysql_query($sql) or die(mysql_error());
is there any errors?
is it possible that your table fields do not match that ones you insert?
What is wrong about it? The return values of mysql_query() is a boolen for INSERT queries, which is true if the operation was successful. Have you tried inserting invalid values (like a text that is too long)? That should generate a warning and return false.
But what bothers much more is that your code is vulnerable to SQL injection. Please read up on sql injections on php.net how to fix that problem.
try this
$sonuc = mysql_query($sql);
<?php
if($sonuc !== false){
echo ("<p class='msg done'>Yeni icerik basarili bir sekilde eklendi.</p>");
} else {
echo ("<p class='msg warning'>Ekleme basarisiz oldu.</p>");
}
?>
EDIT: When you need a validation instead of a check if the query worked check this http://www.php-mysql-tutorial.com/wikis/php-tutorial/form-validation-using-php.aspx
Try this:
if ($sonuc !== false){...
See php manual entry
Jan Hančič has already answered the question but as a side note:
Don't use POST data directly on your queries it will end badly trust me!!