I'm attempting to UPDATE my postgres table on Heroku and have been blocked by the eccentricity of the UPDATE statement.
My initial guess was to say:
$query = pg_query($someDB, $updateQuery);
and then check if it is false, but to no avail. Here's the troublesome snippet:
$update_query = "UPDATE jellybeans SET $form[1]=$data[1], $form[2]=$data[2] WHERE $form[0]='$data[0]'";
echo 'attempting update: ' . $update_query . '<br>';
$update = pg_query($connect, $update_query);
echo "Rows updated: ", pg_affected_rows($update);
//if update failed, push to the table
How does one check on statements like INSERTS, DELETES, and the like? I'm surprised affected_rows doesn't return anything meaningful. Much appreciated.
*EDIT: * Using a SELECT query first yielded the best result:
$exists_query = "SELECT * FROM jellybeans WHERE $form[0]='$data[0]'";
$exists = pg_query($connect, $exists_query);
if($row = pg_fetch_row($exists)){
$update_query = "UPDATE jellybeans SET $form[1]=$data[1], $form[2]=$data[2] WHERE $form[0]='$data[0]' RETURNING *";
echo '<br>' . 'Attempting: ' . $update_query;
$update = pg_query($connect, $update_query);
}else{
$insert_query = "INSERT INTO jellybeans VALUES('$data[0]', $data[1], $data[2])";
echo '<br>' . 'Attempting: ' . $insert_query;
$insert = pg_query($connect, $insert_query);
pg_free_result($insert);
}
pg_free_result($exists);
pg_free_result($update);
From there a simple $row = pg_fetch_row($exists) gives a reliable existence check. In the future, it would probably be best to add an IF FOUND check into the query itself.
One way of knowing is to get the updated rows:
UPDATE ... WHERE condition RETURNING *;
This will return the set of rows updated, just count the number of results.
CREATE OR REPLACE PROCEDURE public."ChangePassword"(
IN id int,
IN pwd text,
OUT affectedrows int)
LANGUAGE 'plpgsql'
AS $BODY$
BEGIN
UPDATE "UserProfile" SET "Password" = pwd WHERE "Id" = id;
GET DIAGNOSTICS affectedrows := ROW_COUNT;
END
$BODY$;
After execution of the stored procedure in below way, it will return the affected row count(s), if any.
Why are you even using pg_* functions? Have you considered using PDO instead? You'd probably have more luck with PDOStatement::rowCount.
Related
I'm having a problem with inserting info into the database. Strangely the update query works but not the insert query. I don't get any error either when submitting, it goes through correctly and echo account saved but nothing is inserted. What am i missing or doing wrong. please assist
if(isset($_POST['Submitaccount'])){
$allowedusers = $_POST['users'];
$accountid = trim($_POST['accountid']);
if(!$_POST['copyperms']) $_POST['copyperms']='N';
if(!$_POST['allusers']) $_POST['allusers']='N';
if(!$_POST['enabled']) $_POST['enabled']='N';
if(!$_POST['servertime']) $_POST['servertime']='N';
if(!$_POST['delremovals']) $_POST['delremovals']='N';
unset($_POST['Submitaccount']);
unset($_POST['accountid']);
unset($_POST['users']);
$notmust = array("email" , "skip" , "comments" , "firstmod");
foreach($_POST as $key=>$val){
if(!trim($val) && !in_array($key , $notmust)) {
$err = 1;
$empty = "$key";
break;
}
$qpart .= "`$key` = '".mysql_escape_string($val)."' , " ;
}
if($qpart) $qpart = substr($qpart , 0 , -2);
if(!$err){
$chk = mysql_num_rows(mysql_query("SELECT * from accounts WHERE name = '".mysql_escape_string($_POST['name'])."' and id <> '$accountid'"));
if($chk >0){
$err = 2;
}
}
if(!$err){
if(!$accountid){
$q = "INSERT into accounts SET $qpart ";
mysql_query($q) or die("Error inserting the record :".mysql_error()."<br>".$q);
$accountid = mysql_insert_id();
}else{
$q = "UPDATE accounts SET $qpart WHERE id = '$accountid'";
mysql_query($q) or die("Error updating the record :".mysql_error()."<br>".$q);
}
}
This is because the INSERT command has different syntax:
INSERT into accounts SET $qpart "
is not usual, you can write it like this:
INSERT into accounts (column names) VALUES your values"
13.2.5 INSERT Syntax
You have double if(!$err){. Do you want both (!$err) into one? If the first (!$err) is for indicator for the second to insert, function SELECT can not be placed above the function INSERT indirectly.
try this:
if(!$err){
$chk = mysql_num_rows(mysql_query("SELECT * from accounts WHERE name = '".mysql_escape_string($_POST['name'])."' and id <> '$accountid'"));
if($chk >0){
$err = 2;
// if(!$err){ again ...
if(!$accountid){
$q = "INSERT into accounts SET (column1) VALUES ($var1)";
mysql_query($q) or die("Error inserting the record :".mysql_error()."<br>".$q);
$accountid = mysql_insert_id();
}
else{
$q = "UPDATE accounts SET $qpart WHERE id = '$accountid'";
mysql_query($q) or die("Error updating the record :".mysql_error()."<br>".$q);
}
}
}
else{
//other code to handle if ($err)
}
Note: I would prefer using PDO to handle database, it's so simple scripting, besides, it's no longer supported
You have to understand that mysql functions have become deprecated. Either using mysqli or pdo would be the better option, but if you absolutely have to use mysql as a solution i would suggest not posting the form to itself, rather post to another php file as you will have less problems.In my environment it seems to work well as an interim solution while we are rewriting everything to use mysqli.If it a go and let me know.
$tSQL = "insert into events(title,start,end,allday,url,customerid) VALUES(\"" . $_POST['title'] . "\", FROM_UNIXTIME($epochstart), FROM_UNIXTIME($epochend), \"$allday\", \"$url\", \"$customerid\")";
$mysqli->multi_query($tSQL);
$lasterror = $mysqli->error;
$tSQL = "update events set url = \"details.php?\"" . mysql_insert_id() . " where idevents = \"$eventid\"";
$row = $mysqli->multi_query($tSQL);
$lasterror = $mysqli->error;
echo print_r($tSQL);
My insert statement for sure does insert the record however mysql_insert_id() keeps returning 0. It should not be this way because there is an auto incremented primary key in that events table and that is running fine as well. Any suggestions on how to get the last inserted ID?
Your query is executed via mysqli, so the mysql function would not hold the inserted ID. Instead, use the mysqli version:
$id = $mysqli->insert_id;
Becasue you are using mysqli and not mysql,
Simply replace mysql_insert_id() with mysqli_insert_id() if using Procedural style
Or replace it with $mysqli->insert_id if using Object Oriented Style
Since you are using mysqli extension, change
$tSQL = "update events set url = \"details.php?\"" . mysql_insert_id() . " where idevents = \"$eventid\"";
to
$tSQL = "update events set url = \"details.php?\"" .$mysqli->insert_id. " where idevents = \"$eventid\"";
Because your are using mysqli which is an improvement version of mysql.
Use mysqli->insert_id instead of mysql->insert_id()
$tSQL = "insert into events(title,start,end,allday,url,customerid) VALUES(\"" . $_POST['title'] . "\", FROM_UNIXTIME($epochstart), FROM_UNIXTIME($epochend), \"$allday\", \"$url\", \"$customerid\")";
$mysqli->multi_query($tSQL);
$lasterror = $mysqli->error;
$lastInsId=$mysqli->insert_id();
$tSQL = "update events set url = \"details.php?\"" . $lastInsId . " where idevents = \"$eventid\"";
$row = $mysqli->multi_query($tSQL);
$lasterror = $mysqli->error;
echo print_r($tSQL);
I am trying to perform a update/insert into query for MySQL. Should insert, if not already in database.
However, it will not update. My db connection is good. I cannot figure it out.
$sql = "UPDATE jos_bl_paid SET u_id='$uid', m_id = '$mid', t_id = '$cus', pd = '1', paypal_payment='$txn',p_date=NOW() WHERE u_id = '$uid' AND '$mid' = m_id ";
$test45 = mysql_affected_rows();
if ($test45 == 0) {
$sql = "INSERT INTO jos_bl_paid(paypal_payment,u_id,m_id,pd,t_id,p_date)VALUES('$txn','$uid','$mid','1','$cus',NOW())";
if (!mysql_query($sql)) {
error_log(mysql_error());
exit(0);
}
echo 'Yes';
}else{
echo 'No';
}
From the code you are showing you aren't even running the update query. You need to put
if (!mysql_query($sql)) {
error_log(mysql_error());
exit(0);
}
before the line
$test45 = mysql_affected_rows();
for that to even return what you want
I would make these into one statement using the ON DUPLICATE KEY UPDATE mysql command. I would guess that your problem is that the insert may be failing because of some unique key set in you schema even though the actual uid doesn't yet exist so the update also fails. Can you post exactly what error message you get?
check your last value in update query i found an error there and have fixed it from my side
try this
$sql = mysql_query("UPDATE jos_bl_paid SET u_id='$uid',m_id = '$mid', t_id = '$cus', pd = '1', paypal_payment='$txn',p_date=NOW() WHERE u_id = '$uid' AND m_id = '$mid'") or die(mysql_error());
Answer is updated try the updated one
From the code you posted, it appears that you're setting the $sql string to an update statement, but not executing it before checking for the number of affected rows.
You'll probably need to call mysql_query($sql) before checking mysql_affected_rows();
Otherwise you're not telling the database to update anything.
If the new values in update are the same as old one mysql won't update the row and you will have mysql_affected_rows be 0. If you have primary key on fields u_id, m_id you can use INSERT ON DUPLICATE UPDATE http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
If you don't have such you may use the count query:
SELECT count(*) FROM jos_bl_paid WHERE u_id = '$uid' AND '$mid' = m_id
To decide if you should update or insert new one.
i have tried to prevent the duplicate data at my project.
but until now it still make duplicate.
i try this code but still not work:
$cek_user= "SELECT Model, Serial_number, Line FROM inspection_report WHERE Model='".$Model."' AND Serial_number='".$Serial_number."' AND Line='".$Line."'";
$cek_data=mysql_num_rows($cek_user);
if($cek_data!=0){
echo "Data already exists!";
}
else{
$sql = "INSERT INTO inspection_report ";
$sql.= "(Model, Serial_number, Line, Shift, Inspection_datetime, Range_sampling, Packing, ";
$sql.= "Accesories, Appearance, Tuner, General_operation, Remark, ";
$sql.= "NIK) ";
$sql.= "VALUES ('";
$sql.= $Model."','".$Serial_number."', '".$Line."','".$Shift."','".postVar('insp_date')." ".postVar('time')."','".$Range_sampling."','".$Packing."','";
$sql.= $Accesories."','".$Appearance."','".$Tuner."','".$General_operation."','".$Remark."','";
$sql.= $NIK."')";
//echo $sql;
$result=mysql_query($sql) or die(_ERROR26.": ".mysql_error());
//echo $result;
}
mysql_close($dbc);
}
but still not work,please help.
This will not prevent duplicates unless your table also has a UNIQUE constraint somewhere allowing the database to determine what you mean by a duplicate. If you have such a constraint, perhaps you could post your table definition.
You can do a select before insert,
eg. Select id from table where serial_number = '$serial_number'
If mysql_num_rows equals 0, do insert. This assumes serial_number is unique for each row.
$sql = "SELECT ID FROM inspection_report WHERE Serial_number = '$Serial_number'";
$result = mysql_query($sql);
if(mysql_num_rows($result) == 0){
$sql = "your insert sql..."
$result = mysql_query($sql);
}
You do realize your're running the INSERT query twice, right?
if ( mysql_query($sql) ) {
^^^^^^^^^^^--- here
[.... snip ....]
}
$result=mysql_query($sql) or die(_ERROR26.": ".mysql_error());
^^^^^^^^^^^--- and here
As well, you should look into using HEREDOCs to build your query string. That long chunk of string concatenation and quote-soup you've got could look like this with a HEREDOC:
$insp_date = postVar('insp_date') . ' ' . postVar('time');
$sql = <<<EOL
INSERT INTO inspection_report
(Model, Serial_number, Line, Shift, Inspection_datetime,
Range_sampling, Packing, Accesories, Appearance, Tuner,
General_operation, Remark, NIK)
VALUES (
$Model, $Serial_number, $Line, $Shift, $insp_date,
$Range_sampling, $Packing, $Accesories, $Appearance, $Tuner,
$General_operation, $Remark, $NIK)
EOL;
every so slightly more readable.
edit/comment followup:
You're running the query twice, in the spots where I've put the '^^^^^--- here' lines.
First instance: if ( mysql_query($sql) ) {
Second instance: $result = mysql_query($sql) or die.......
You haven't changed the contents of $sql between the two mysql_query() calls, so when you do the second call, it runs the exact same query string, which is your INSERT query. So you end up inserting the data TWICE.
Beyond that, your error handling is atrocious. Scanning an error string for a particular string is the wrong way to go about it. The error text might change (think of what would happen if your code runs on a server running in (say) a German location, which has localized error messages and spits out "Doppelter eintrag für ..." instead of "Duplicate entry for". What you should have is something like this:
$sql = "... your query here ... "
$result = mysql_query($sql); // if query fails, this returns FALSE
if ($result === FALSE) {
die("MySQL error: " . mysql_error());
}
If you need to check for a particular error that could be corrected by your code, you can use mysql_errno() to retrieve the server error code, and work from there. Using your example, 'Duplicate entry' is error # 1062 (full error codes documented here), so you'd do
if (mysql_error() == 1062) {
... handle error here ...
}
first of all:
ALTER inspection_report ADD UNIQUE(Model, Serial_number, Line);
Then:
$sql = "INSERT IGNORE INTO..........";
I have a MySQL database that I'm working with, but when I try to update a row in it, it doesn't work. Here's the update code I'm working with:
mysql_query("UPDATE offtopic SET next = '$insert' WHERE id = '$id'");
First of all, you should make it a bit more safe:
mysql_query(sprintf("UPDATE offtopic SET next = '%s' WHERE id = '%s'",
mysql_real_escape_string($insert),
mysql_real_escape_string($id));
Now, is your id actually string, and not numeric? If its numeric, you should rather have:
mysql_query(sprintf("UPDATE offtopic SET next = '%s' WHERE id = %d",
mysql_real_escape_string($insert), $id);
your syntax is correct, so it might be an error with the variables or your field names.
Try this:
$sql = "UPDATE offtopic SET next = '$insert' WHERE id = '$id'";
if (!mysql_query($sql)) {
echo "MySQL Error: " . mysql_error() . "<br />" . $sql;
}
That might show you some useful information to help you debug.
Please, for the love of the internet, don't built an SQL query yourself. Use PDO.