UPDATE table mySQL problem - php

I've got an payment provider, which helps me to pay by call. However after the payment I need to UPDATE the order's status. This doesn't work. The whole script is found below.
if ($m->payed) {
$order_result = mysql_query('UPDATE jos_vm_orders SET order_status="C" WHERE order_id="'.$_GET['id'].'"');
echo '<b>Bedankt voor je betaling</b><br />
De betaling is succesvol gelukt!';
}
else {
$GET_['id'] is sent with the url.
I really don't know the answer, because the UPDATE line does work when I use it in the beginning (before the payment).
And not only the update line doesn't work, everything after 'if payed' doesn't work.
Thanks in advanced!

Examine the query:
$order_result = mysql_query('UPDATE jos_vm_orders SET order_status="C"
WHERE order_id="'.$_GET['id'].'"');
It is my guess that the WHERE clause is failing. Call mysql_affected_rows() after the operation; it will return 0 if no rows were updated.
The problem could also be the query failing. Wrap the query in a block similar to the following:
if (!$order_result = mysql_query('UPDATE jos_vm_orders SET order_status="C"
WHERE order_id="'.$_GET['id'].'"')) {
// Handle the error here.
}
Also note, it is not good practice to ever use $_GET or $_POST data directly in an SQL query. Consider validating it, at least by doing this:
$_GET['id'] = (int) $_GET['id'];
if ($_GET['id'] === 0) {
// handle the error here
}

Please verify the value of $m->payed by adding var_dump() in your code.
var_dump($m);
if ($m->payed)
{
$sql="UPDATE jos_vm_orders SET order_status='C' WHERE order_id=$_GET[id]";
$order_result = mysql_query($sql);
echo '<b>Bedankt voor je betaling</b><br />
De betaling is succesvol gelukt!';
}

You have to learn how to debug your code.
It's impossible to say what's the problem just by watching the code.
One have to run the code, get all possible error messages and check all important variables. that's the only way to find the problem.
So, to get possible error message you have to run your query the same way as previous one, by using mysql_error()
And also you must take care of the values going to the query.
So, make your code like this:
if ($m->payed) {
$id = intval($_GET['id']);
$sql = "UPDATE jos_vm_orders SET order_status='C' WHERE order_id=$id";
$res = mysql_query($sql);
if (!$res) {
trigger_error(mysql_error()." ".$sql);
echo '<br>Server Error<br>';
} elseif (!mysql_affected_rows($res)) {
trigger_error("No rows were updated! ".$sql);
echo '<br>Server Error<br>';
} else {
echo '<b>Bedankt voor je betaling</b><br />De betaling is succesvol gelukt!';
}
} else {
echo '<font color=red><b>Betaling is niet afgerond,<br />volg de onderstaande instructies!</b></font><br /><br />';
}
include('includes/include.paymentscreen.php');
}

The problem was eventually my server, I had 'display erros' on off. When I turned it on, the actually error lied with the session_start. When I opened the file on my server, I saw I saved it in the wrong format, this solved it!
Thanks for every answer.

Try Change This
UPDATE jos_vm_orders SET order_status="C" WHERE order_id="'.$_GET['id'].'"
To
$id=$_GET['id'];
"UPDATE jos_vm_orders SET order_status='C' WHERE order_id='$id'"
Be careful with quotes in query. Always Give Double quotes at starting and ending , prefer single quotes in the middle of query.
Avoid concatination in query and instead try including it like mentioned above

Related

Duplicate check before adding into database

I have a code which kinda works, but not really i can't figure out why, what im trying to do is check inside the database if the URL is already there, if it is let the user know, if its not the go ahead and add it.
The code also makes sure that the field is not empty. However it seems like it checks to see if the url is already there, but if its not adding to the database anymore. Also the duplicate check seems like sometimes it works sometimes it doesn't so its kinda buggy. Any pointers would be great. Thank you.
if(isset($_GET['site_url']) ){
$url= $_GET['site_url'];
$dupe = mysql_query("SELECT * FROM $tbl_name WHERE URL='$url'");
$num_rows = mysql_num_rows($dupe);
if ($num_rows) {
echo 'Error! Already on our database!';
}
else {
$insertSite_sql = "INSERT INTO $tbl_name (URL) VALUES('$url')";
echo $url;
echo ' added to the database!';
}
}
else {
echo 'Error! Please fill all fileds!';
}
Instead of checking on the PHP side, you should make the field in MySQL UNIQUE. This way there is uniqueness checking on the database level (which will probably be much more efficient).
ALTER TABLE tbl ADD UNIQUE(URL);
Take note here that when a duplicate is INSERTed MySQL will complain. You should listen for errors returned by MySQL. With your current functions you should check if mysql_query() returns false and examine mysql_error(). However, you should really be using PDO. That way you can do:
try {
$db = new PDO('mysql:host=localhost;db=dbname', $user, $pass);
$stmt = $db->query('INSERT INTO tbl (URL) VALUES (:url)');
$stmt->execute(array(':url' => $url));
} catch (PDOException $e) {
if($e->getCode() == 1169) { //This is the code for a duplicate
// Handle duplicate
echo 'Error! Already in our database!';
}
}
Also, it is very important that you have a PRIMARY KEY in your table. You should really add one. There are a lot of reasons for it. You could do that with:
ALTER TABLE tbl ADD Id INT;
ALTER TABLE tbl ADD PRIMARY KEY(Id);
You should take PhpMyCoder's advice on the UNIQUE field type.
Also, you're not printing any errors.
Make sure you have or die (mysql_error()); at the end of your mysql_* function(s) to print errors.
You also shouldn't even be using mysql_* functions. Take a look at PDO or MySQLi instead.
You're also not executing the insert query...
Try this code:
if(isset($_GET['site_url']) ){
$url= $_GET['site_url'];
$dupe = mysql_query("SELECT * FROM $tbl_name WHERE URL='$url'") or die (mysql_error());
$num_rows = mysql_num_rows($dupe);
if ($num_rows > 0) {
echo 'Error! Already on our database!';
}
else {
$insertSite_sql = "INSERT INTO $tbl_name (URL) VALUES('$url')";
mysql_query($insertSite_sql) or die (mysql_error());
echo $url;
echo ' added to the database!';
}
}
else {
echo 'Error! Please fill all fileds!';
}
As PhpMyCoder said, you should add a unique index to the table.
To add to his answer, here is how you can do what you want to do with only one query.
After you add the unique index, if you try to "INSERT INTO" and it result in a duplicate, MySQL will produce an error.
You can use mysql_errno() to find out if there was a duplicate entry and tell the user.
e.g.
$sql = "INSERT INTO $tbl_name (URL) VALUES('$url')";
$result = mysql_query($sql);
if($result === false) {
if(mysql_errno() == $duplicate_key_error) {
echo 'Error! Already in our database!';
} else {
echo 'An error has occurred. MySQL said: ' . mysql_error();
}
}
mysql_error() will return the mysql error in plain english.
mysql_errno() returns just the numeric error code. So set $duplicate_key_error to whatever the code is (I don't know it off the top of my head) and you are all set.
Also note that you don't want to print any specific system errors to users in production. You don't want hackers to get all kinds of information about your server. You would only be printing MySQL errors in testing or in non-public programs.
ALSO! Important, the mysql functions are deprecated. If you go to any of their pages ( e.g. http://php.net/manual/en/function.mysql-errno.php) you will see recommendations for better alternatives. You would probably want to use PDO.
Anyone who wants to edit my answer to change mysql to PDO or add the PDO version, go ahead.

php real_escape_string(), query not working anymore

I want to be able to add and update certain information. Now it was all working fine untill I found out the script no longer works when there's quotation marks in the text being sent to the database.
So I've done some research and found out I had to use the mysql_real_escape_string() function to ignore the quotation marks. I've done this but the script now isn't working at all anymore. I think the problem lies in the query part but i don't see the problem. Below is the code:
<?php
if(isset($_POST['bevestiging']))
{
$ID = (int)$_GET['ID'];
$titel = mysql_real_escape_string($_POST['Titel']);
$ondertitel = mysql_real_escape_string($_POST['ondertitel']);
$wanneer = mysql_real_escape_string($_POST['wanneer']);
$datum = mysql_real_escape_string($_POST['datum']);
$afbeelding = mysql_real_escape_string($_POST['afbeelding']);
$intro = mysql_real_escape_string($_POST['intro']);
$main = mysql_real_escape_string($_POST['main']);
$query = "UPDATE voorstellingen
SET '$titel','$ondertitel','$wanneer','$datum','$afbeelding','$intro','$main'
WHERE id = $ID";
mysql_query($query) or die('Error, bewerken van voorstelling is mislukt');
$query ="FLUSH PRIVILEGES";
echo"De voorstelling is succesvol bewerkt";
}
else{
$ID = (int)$_GET['ID'];
$query="SELECT * FROM voorstellingen WHERE id = $ID";
$result = mysql_query($query) or die('Error, bewerken van voorstelling is mislukt');;
?>
your update query should be like:
$query = "UPDATE voorstellingen SET title = '".$titel."' .....";
See: UPDATE Syntax
mysql_real_escape_string function returns FALSE on errors. You can check the return type of the below line
$titel = mysql_real_escape_string($_POST['Titel']);
to see if it succeeds or not. You do not need to check the next lines. If there is error on first function call, it will very probably mean that no SQL connection is present before invoking the function. Because a MySQL connection is required before using mysql_real_escape_string() otherwise an error of level E_WARNING is generated, and FALSE is returned.
If the above suggestion does not solve your issue , please elaborate what error exactly are you facing and on which line.

PHP: $_SESSION register

I'm having problem with this code and I can't figure out where the problem is. So when I run this code: if $row["count"] > 0 the else block is run and $_SESSION["error"] is set.
When $row["count"] == 0 query is executed and new row is inserted into database but both $_SESSION["save"] and $_SESSION["error"] are set! Does this mean that both if and else statements are run? It doesn't make any sense to me...
$stmt = $pdo->prepare("SELECT COUNT(*) AS count ... QUERY");
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if( $row["count"] == 0 ){
$stmt = $pdo->prepare("INSERT...QUERY");
$stmt->execute();
$_SESSION["save"] = "Saved";
header("Location:index.php");
exit();
}else{
$_SESSION["error"] = "Error";
header("Location:index.php");
exit();
}
i'm using this code in index.php
$save = (isset($_SESSION["save"]))? $_SESSION["save"] : false;
$error = (isset($_SESSION["error"]))? $_SESSION["error"] : false;
unset($_SESSION["error"]);
unset($_SESSION["save"]);
As I said, when $row["count"] == 0 I have both $save and $error set..
SOLVED
It appears that I found the problem. I've changed they way I access the script from:
<a href='script.php?id=10'><input type="button" value='Go to script' /></a>
to:
<a href='script.php?id=10'>Go to script</a>
And the script is working now. With the input button tag inside the a tag the script was behaving unpredictable executing the if and else statement in the same time.. I'm still confused why and how input tag caused that, but at least the script is working now...
Are you clearing $_SESSION["error"] and $_SESSION["save"] after they have been read in index.php? It sounds to me like you have run across both cases once and have lingering values in your $_SESSION array.
I suggest using the same variable name for both cases, e.g. $_SESSION['save'], and assigning either success or error to it. That way, you don't have to check whether one of two variables exist, but only what its contents are.
And don't forget to clear or unset the variable after it has served its purpose.
FOr example, when you trying this, if in a stage $row["count"] > 0 session will record $_SESSION["error"] . It will be stored if you don't delete it. Because of this $_SESSION["error"] is setted.
Maybe you have executed your code twice and ["error"] was still set. You dont clear it on success.
According to your logic, it is impossible for both conditions to run at the same time. However, I'm sure you've run this script multiple times. Sometimes with IF, sometimes with ELSE. It doesn't seem like you're ever clearing the $_SESSION variables.
Solution:
Right after you use the $_SESSION['save'] or $_SESSION['error'] variables, unset them.
unset($_SESSION['save']);
or
unset($_SESSION['error]');

Trouble with updating Data trough PHP

I have a problem with this code, it does delete a row but not editing one. I cannot figure out how to make it work.
Here's the script:
<?php
if($_POST['delete']){
$i = 0;
while(list($key, $val) = each($_POST['checkbox'])) {
$sql = "DELETE FROM $tbl_name WHERE id='$val'";
mysql_query($sql);
$i += mysql_affected_rows();
}
// if successful redirect to delete_multiple.php
if($i > 0){
echo '<meta http-equiv="refresh" content="0;URL=data.php">';
}
}
if($Submit){
for($i=0;$i<$count;$i++){
$sql="UPDATE $tbl_name SET naam='$naam[$i]', achternaam='$achternaam[$i]', leeftijd='$leeftijd[$i]', straat='$straat[$i]', postcode='$postcode[$i]', telefoon='$telefoon[$i]', email='$email[$i]', geslacht='$geslacht[$i]', pakket='$pakket[$i]', WHERE id='$id[$i]'";
$result1=mysql_query($sql1);
}
}
mysql_close();
?>
As others have pointed out $Submit isn't defined before the if statement - also $tbl_name isn't defined either so it would bring back an error if the if statement was triggered.
Also in $result1 you used $sql1 - $sql1 has not been defined.
You're vulnerable to SQL injections like Pekka said, so I advise reading up on it, always, ALWAYS validate user inputted data, never trust anyone :)
Also, you don't need to print a meta refresh, you can just use header
header ("Location: data.php");
$Submit is not defined before it is used. So, its value will be null which is a falsy value. Hence if loop will never get executed.
$Submit is not defined (as others already mentioned). Also, if you do define $Submit then $count is still undefined. So you still won't get into the for loop. And if $count is defined, your code still does not update the database. You store your sql query in $sql but pass $sql1 , which has not been set, as query that should be executed.
And your code is wide open for sql injection. You should not want that.

php form errors

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!!

Categories