Why my database table is not getting updated - php

I used the correct command to update my database table
$result_col ="UPDATE `try`.`5` SET `D` = '$value' WHERE `5`.`A` = '$filenames[$index]' ;";
It works if i write in phpmyadmin to update the database table using the above command.
But it doesnot work in my code, though when i echo the command it prints correct values
UPDATE Store SET D='SUN: 2.495' WHERE `Index` = 'Hi35'
UPDATE Store SET D='SUN: 1.416' WHERE `Index` = 'He_41'
And it doesnot show any error or warnings , i also used this error_reporting(E_ALL)
What could be the possible reasons?
I checked Database link, It works
I checked the code, NO error reports or warnings
I pasted the command in phpamyadmin, the command works
I used mysqli instead of mysql, still the same problem
I did so many trials but still why the command doesnot work in the code?
Any idea??

it worked! there were spaces in the array $filenames, which was ignored in phpmyadmin, that is why the query worked in phpmyadmin and not in the php script...

Take the semicolon ';' out of your query string.

Related

Using reserved word in sql update query in php overwrites the whole table

I am currently working on a php project and used the word 'value' as a column name. The problem being that when I run the query, it overwrites all entries in the database, even though I have a delimiter (primary key = *). I have tried everything I can think of to get this to work, and it hasn't yet. here is the complete line of code:
$SqlStatement = "UPDATE rev_exp SET Date_Entered = '".date('Y-m-d')."', Description = '".$_POST['txtUtilityType']." ".$_POST['txtAccountNumber']." ".$_POST['txtDateAdded']."', `Value` = ".$_POST['txtValueBalance'].", Notes = '".$_POST['txtNotes']."' WHERE PK_Rev_Exp = ".$row['FK_Rev_Exp'];
Note here, that $row['FK_Rev_Exp'] is the delimiter I was talking about. It is being pulled accurately from a previous query. Also, please ignore any sql injection problems, I'm just working on getting the project functional, I can optimize later.
EDIT 1: I have also tried enclosing the "value" in everything I can think of that may get rid of this problem, but no luck.
EDIT 2: I also don't think it is a problem with the statement itself, as I directly entered the statement into the mysql command line and it only affected 1 row, possibly a php problem?
EDIT 3: Full block, including the execution of the sql. Here, ExecuteSQL runs all necessary mysqli statements to execute the sql command. it takes in a sql statement and a true/false if there is a result set:
$SqlStatement = "UPDATE rev_exp SET Date_Entered = '".date('Y-m-d')."', Description = '".$_POST['txtUtilityType']." ".$_POST['txtAccountNumber']." ".$_POST['txtDateAdded']."', `Value` = '".$_POST['txtValueBalance']."', Notes = '".$_POST['txtNotes']."' WHERE PK_Rev_Exp = ".$row['FK_Rev_Exp'];
ExecuteSQL($SqlStatement, false);
I can't figure it out, and any help would be appreciated.
I think your problem is not about mysql reserver keywords because your correctly surrounded Value with backtick and that makes database understand this is a field. I'm more concerned about treating not integers as integers so i would suggest to surround with quotes '' your value since it is a decimal
`Value` = '".$_POST['txtValueBalance']."',

mysql_query update doesn't update

mysql_query running an UPDATE query isn't working for me, what am I doing wrong?
if($get_ip['user_ip']== ''){
$insert_ip = mysql_query("UPDATE user SET user_ip='$user_ip' WHERE username='$username' AND password='$password'");
if(!$insert_ip){
$message = 'invalid query'.mysql_error();
die($message);
}else{
echo ('success!');
};
};
Basically I am trying to update the table user at user_ip row with value ip_user, if user_ip field is empty of course.
So nothing updating and the user_ip filed remains empty please help.
There are two things I can see on your script.
you are using if($get_ip['user_ip']== '') statement, which will insert data when $get_ip['user_ip'] is only empty or it will ignore to insert data when $get_ip['user_ip'] have some data.
You are using SET user_ip='$user_ip' on update query, I may not be correct, however I assume that you are trying to store data from $get_ip['user_ip'], if this is the situation use SET user_ip='$get_ip['user_ip']' instead of SET user_ip='$user_ip' on your insert query.
if($get_ip['user_ip']== '')
won't work except if $get_ip['user_ip'] is empty.
use
if(!empty($get_ip['user_ip']))
instead
There are just soooo many things wrong here, but in the interest of being helpful:
Assign the query string to variable rather than directly injecting it into the mysql_query function. Then, echo this string out. This will show you want you are sending to the database. Copy that output somewhere, and then log into whatever you use to manage your database (I assume it'll be phpMyAdmin). Open up your database and then the table you're targeting, and then use the query editor to run your query (paste the output you copied earlier).
If your query string isn't what you expected, you have a code error.
If your query is as you expected, and runs in the database tool, you
likely have a permissions issue with the user account you're using in
your connection string.
If your query is as expected, but doesn't run correctly in your
database tool, your problem most likely is a schema error.

INSERT statement mystery - mysql_query returns true, yet no new rows appear in database

I must be doing really stupid here. I've been troubleshooting this for 3 days with no luck.
Here is the PHP string that is sent to mysql_query():
insert into post_replies (postID, fromID, toID, status) values ($id, $userID, $toID, ".g_unread.")
Before you say, "Ah-hah, there must be an error in the SQL", please note these two things:
mysql_query() returns true (1)
I export the string to a text file (see below) BEFORE sending to mysql_query() - If I paste the exported text into the same mysql_query() statement, it works fine (new row appears) - If paste the exported text into phpMyAdmin, it works fine (new row appears)
The exact (and I mean exact, as in I simply copy and pasted it) same query is used a few lines down and it always works fine
Another thing I tried was to load the query back from the text and then send it to mysql_query() - but that produces the same odd behavior - it returns success (1), yet no new rows are actually inserted.
I have showed this to another programmer, who complained about my PHP coding style. He said INTs should be wrapped as strings and I should use curly braces around those (e.g. '{$id}'). However, of course that fixed nothing, the behavior was exactly the same. If there was a problem with string generation then the problem would appear in the query that is exported to text file before sending to mysql_query(). He also complained that I was using outdated mysql functions (that I should be using mysqli functions). However, that does not explain why my hundreds of other queries sent via mysql_query() work fine, including the one a few line below this one. It does not explain why the query works fine if I paste the exported-to-text-file text directly into mysql_query().
Thank you so much. I am totally lost here.
UPDATE #1: By request, here is the code around the statement:
$q = "insert into post_replies (postID, fromID, toID, status) values ($id, $userID, $toID, ".g_unread.")";
$result = mysql_query($q);
if ($result == true) {
z($q);
} else {
z('failure');
}
z() is a function I use for easily exporting to text file. Btw, the query is always sent to z(), 'failure' is never sent.
Here is an example of what is sent to the text file:
insert into post_replies (postID, fromID, toID, status) values (2039, 8, 1, 1)
Please keep mind that if I paste that text into phpMyAdmin, or into the mysql_query() function above, the row is inserted.
UPDATE #2: Due to concern by some, I have updated this part of the code to use mysql[i]
$mysqli = new mysqli(g_db_server, g_db_user, g_db_pass, g_db);
$result = $mysqli->query($q);
I now make a separate connection, just for this single query. However, the behavior is exactly the same. It returns true, but no news rows are created. However, if I export $q to a text file, and then paste that text into $mysqli->query() above, it works fine and the new row is created as expected.
Since everyone seems to have given up, I am now working on isolating the problem to single MySQL table / PHP file which anyone can download and try for themselves.
UPDATE #3: Solved! Sort of. It seems to be an issue with the surrounding code, causing the row to be deleted after insertion. However, this still doesn't explain why mysql_insert_id() returned 0. Perhaps mysql_insert_id() breaks on composite keys. Anyhow, I don't care - because it's fixed. I will give the check to #user1231958 because his answer was the closest. Thank you all immensely for your help and sorry for being tricked by mysql_insert_id()
Try to use grave accent's when specifying your tables and rows,
$q = "INSERT INTO `post_replies` (`postID`, `fromID`, `toID`, `status`) VALUES ('$id', '$userID', '$toID', '".g_unread."')";
$result = mysql_query($q);
if ($result == true) {
z($q);
} else {
z('failure');
}
Tell me if if that works.
Does mysql_error() return anything? This maybe lame, but are you connecting to the right database while performing the insert?
You could also enable query logging in mysql to record all queries. Howtogeek has an article on enabling this feature. After the server is restarted, you should start seeing all queries logged into the file you specified. Mine looks like this.
/opt/local/libexec/mysqld, Version: 5.1.61-log (Source distribution). started with:
Tcp port: 3306 Unix socket: /opt/local/var/run/mysql5/mysqld.sock
Time Id Command Argument
120727 8:57:09 1 Connect root#localhost on foo
1 Query /* test comment */ insert into test(foo) values(NOW())
1 Quit
Now that you can monitor all queries going to the mysql server, prefix your query with a comment to identify it in the log. I used the following PDO code to generate the log above.
$dbh = new PDO("mysql:host=localhost;dbname=foo",'root','');
$dbh->exec("/* test comment */ insert into test(foo) values(NOW())");
I had a problem just like this. I found the problem to be fields not having a default value.... I recently went from a Linux server to a Windows server and must have got a bit lazy while using Linux.
The problem was, when using my Linux server i don't have to put every single field into the INSERT query, for some reason (I'm not sure why) it seems to default them for me however, the Windows server I'm using does so the mysqli error function was saying no default for some fields, add these fields in and it worked fine for me.
I know this question has been answered but this might help other people having the same problem, after all i don't want someone else pulling their hair out for 3 days.
you have to check if there is something prevent committing your command,
try this command after executing the query:
mysql_query ( "COMMIT;" );
I just ran into this issue and found the problem.
If, somehow, your table doesn't have a correct auto-increment for a primary key it will return true but not actually insert the new row.

automatically executing mysql query from php not working

I'd like to automatically execute the following PHP script to autmoatically delete a row in table after 3 days. However, the script seems not working, even though the query already yield the correct result. I've tried to run it manually, and it also worked. I'm not sure whether I've written the script correctly, but here's the code:
<?php
require_once('../../resources/db_connect.php');
$query = "DELETE FROM user_orders WHERE date_order < DATE_SUB(CURDATE(), INTERVAL 3 DAY) AND ID_status_order = 1";
$result = #mysql_query($query);
?>
I'm using xampp on Windows. I've tried to execute it via Windows Task Scheduler, but I don't think it's working. Any other idea?
Cheers
Hidding errors are not good enough. Thry and remove the # first and see what errors you are having. Come back and give the errors.
echo mysql_query($query) or mysql_error()
You aren't doing any error checking, and with the # in front of commands even actively suppressing errors. Use this to check for errors with your query or database connection:
mysql_query($query) or die(mysql_error());
If you want to check your query but don't want it to delete everything, add another condition to it:
... AND 1=0
which is always false, thus nothing gets deleted. MySQL will still check your query and give you errors, if e.g. some fields or the table are unknown.

Updating table in php-mysql

i am writing a php code involving mysql. At one point, i have to update a table in my database for which i am using the below 2 statements. But these are not working.
$temp = $row['tracking_id'];
mysql_query("UPDATE order_products SET state=4.00 WHERE tracking_id = '$temp'");
Note that i don't get an error message. The table is not updated though. Also note, the column names, table names are correct. I have also tried without the single '' quotes around $temp in WHERE clause.
The connection to database is fine. I know this cos select queries are working fine.
Any ideas?
Thanks
Try to var_dump temp
var_dump($temp);
and also check errors from your query
mysql_query("UPDATE order_products SET state=4.00 WHERE tracking_id = '$temp'") or trigger_error(mysql_error()." <here is that problem");
It will give you your answer
Firstly check what is the value in $temp.
If value is fine the do it like this to echo your query.
echo $sql = "UPDATE order_products SET state=4.00 WHERE tracking_id = '$temp'";
$result = mysql_query($sql);
its only for testing and check the query is it fine? try running it directly and see if any error comes
How did you fetch the row?
using mysql_tetch_row or mysql_fetch_array?
if you used fetch_array it's not an associative array and you can't do row['something'], only row[index], so use fetch_row instead.
print the value of temp to verify it's ok and if still can't find the problem try using the mysql_error() function to prinT the last mysql error.
Note that i don't get an error message.
No wonder. You have to ask a database for the error message.
$tmp = mysql_real_escape_string($row['tracking_id']);
$sql = "UPDATE order_products SET state=4.00 WHERE tracking_id = '$tmp'";
mysql_query($sql) or trigger_error(mysql_error()." ".$sql);
var_dump(mysql_affected_rows); //to see if rows were changed.
if it prints only 0 - then you have a row with exactly same values in your table already

Categories