if(isset($_SESSION['id'])) {
$message=$_POST['message'];
$cid=$_POST['cid'];
$user_id=$_SESSION['id'];
$stmt=$conn->prepare("update comments set message=? where id=? and user_id=?");
$stmt->bind_param("sss",$message,$cid,$user_id);
if(!$stmt->execute()){
echo "error";
} else {
echo "success";
}
I always get success but when I go to the database I find out that nothing is changed.
You are trying to do an UPDATE with a WHERE clause. If it does not actually update anything, it will still be considered a success. The reason !$stmt->execute() would happen, is if there is a sql error, and it bails.
So what you should be doing, is also check if num rows affected.
if ( ! $stmt->affected_rows ) { echo 'nothing changed!'; }
Related
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);
I have a simple registration form that inserts data into MySQL table. I am checking for error as well but it results in SUCCESS echo.
On Stackoverflow, I looked for the question, but couldn't really find an answer pertaining to my situation. Please forgive me if it has been answered. If it has been answered already, please provide a link and I will apologize for wasting anybody's time. Thank you! Below is my code:
<?php
if($_GET["regname"] && $_GET["regpass1"] && $_GET["regpass2"])
{
if($_GET["regpass1"]==$_GET["regpass2"])
{
$servername="localhost";
$username="root";
$password='';
$conn= mysql_connect($servername,$username,$password)or die(mysql_error());
mysql_select_db("test")or die("cannot select DB");
$sql="INSERT INTO members('id','username','password')VALUES('DEFAULT','$_GET[regname]','$_GET[regpass1]')";
if($sql)
{
echo "Success";
}
else
{
echo "Error";
}
print "<h1>you have registered sucessfully</h1>";
print "<a href='main_login.php'>go to login page</a>";
}
else print "passwords doesnt match";
}
else print"invaild data";
?>
You are checking if $sql exists. $sql is your actual query string. In this case, of course it will show it exists. Secondly, please do not use mysql_* for new code as it is deprecated. Instead use mysqli_* or PDO.
You actually haven't executed your query in your code. (Using deprecated mysql_* which is ill advised) the code as follows should execute the query:
$result = mysql_query($sql, $conn);
if($result == true)
echo 'Success';
else
echo 'Failure';
Instead of using the code above, I would strongly recommend updating your current code to use mysqli_* or PDO forms. You can read up more on this topic at the manpages linked previously.
Look at these lines:
$sql="INSERT INTO members('id','username','password')VALUES('DEFAULT','$_GET[regname]','$_GET[regpass1]')";
if($sql)
{
echo "Success";
}
You have created a request in $sql variable but have not executed it. The variable itself is non-empty, non-false so it evaluates to TRUE in the if-condition.
You should do it like this:
$sql="INSERT INTO members('id','username','password')VALUES('DEFAULT','$_GET[regname]','$_GET[regpass1]')";
$result = mysql_query($sql);
if (!$result)
{
die('Invalid query: ' . mysql_error());
}
else
{
echo "Success";
}
Just to be on the safe side I'll note that using variables from $_GET request like this, unfiltered, is an inapprorpiate tactic as it will lead to SQL injections, but I suppose you simplified code sample for the sake of brevity.
So i want to check if a post exists in the database but i have some problems with redirection.
This is my work so far:
echo '<br>';//the $row part tells the DB what post his looking on
echo 'View comments';
This is the show comment button that leads to the section where you see the comments for the post.
<?php
require_once ('checkp.php');
I have it to require the post checking script once.
<?php
include ('variables.php');
//connects to DB
$dbc=mysql_connect($host,$user,$pass);
if ($dbc) {
} else {
echo ('Failed to connect to MySql; '. mysql_error());
}
//selects db from MySQl
$sqldb=mysql_select_db('a2318052_blog');
$pid=$_GET['post_id'];
$query1="SELECT * FROM posts_b WHERE id='$pid'";
$sql=mysql_query($query);
if ($sql) {
} else {
echo "cant run query";
}
if (mysql_num_rows($sql) > 0) {
echo "that post does not exist!";
} else {
header ("location: comments.php?post_id='. $pid.'");
}
?>
And this is the script that checks for a empty result and then redirects back. I believe its something with the redirect here (header ("location: comments.php?post_id='. $pid.'");)
You mixed the quotes on the redirect:
"location: comments.php?post_id='. $pid.'"
should be
"location: comments.php?post_id=". $pid
The dot in php is used to concatenate strings. Bu there you are opening the string with " and closing it with '.
EDIT : Also as someone else already noticed you're using query instead of query1.
Also i suppose instead of:
if (mysql_num_rows($sql) > 0) {
echo "that post does not exist!";
you wanted something else:
if (mysql_num_rows($sql) == 0) {
echo "that post does not exist!";
You probably don't want single quotes around the post_id...
header ("location: comments.php?post_id=$pid");
first change pid
$pid = intval($_GET['post_id']); // for security
after that
if (mysql_num_rows($sql) == 0)
{
echo "that post does not exist!";
}
else
{
header("Location: comments.php?post_id=".$pid);
}
$query1="SELECT * FROM posts_b WHERE id='$pid'";
$sql=mysql_query($query);
You're using $query instead of $query1. That's probably the problem (along with the concatenation stuff other users have pointed out).
There's also a few other things, like I think you mixed up your if/else statement here:
if (mysql_num_rows($sql) > 0) {
echo "that post does not exist!";
} else {
header ("location: comments.php?post_id='. $pid.'");
}
Maybe you want the order to be reversed?
Also, you should look into avoiding SQL injection!
Sending a query with a $GET variable is pretty dangerous, as users can manipulate the URL and send malicious queries.
$pid=$_GET['post_id'];
Prepared statements are ideal, but for now, you could use mysql_real_escape_string around your $GET variable. It stops people from sending queries you really don't want done.
i need to know how to get success message after successful execution of sql or failure message of wrong execution.my example is below
`
public function actionSql()
{
$table_no='1';
$employee='1';
$status='1';
$connection=Yii::app()->db;
$sql="INSERT INTO orders_transaction (table_no,employee,status) VALUES(:table_no,:employee,:status)";
$command=$connection->createCommand($sql);
$command->bindParam(":table_no",$table_no,PDO::PARAM_STR);
$command->bindParam(":employee",$employee,PDO::PARAM_STR);
$command->bindParam(":status",$status,PDO::PARAM_STR);
$command->execute();} `
after executing i need to know is the row successfully inserted or not.
i used below one but no use its only echoing successfully not failure
if($command->execute())
{
echo "Successful";
}
else {
echo "ERROR";
}
so i tried this one its giving permission denied error for localhost with password" "
$result=mysql_query($sql);
// if successfully insert data into database, displays message "Successful".
if($result){
echo "Successful";
}
else {
echo "ERROR";
}
i hope you under stand my problem.please give any suggestion or answer.
Execute()
returns the number of affected rows(for INSERT, DELETE, UPDATE etc).
$num = $command->execute();
here $num will contain the affected number of rows.
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!!