Update/Insert into mysql query - php

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.

Related

SQL Select/ Insert / Update query PHP MySQL

I have a table with columns userID(int),timeIN(date),timeOUT(date)
I am inserting a record in mysql database. First I check if the userID is correct from the other table and if its correct it will add a new record of the userID and timeIN(date) whereas the timeOUT will be NULL, else it will display error if the userID is not correct. I want my code to be able to check if the user is currently timeIN so it will prevent a double entry. I would also like to insert or update timeOUT(date) if the values of userID is equals to the user input and timeIN is not null and timeOUT is null.
Please kindly help...thanks.
Here is my code for inserting userID and timeIN: IT WORKS when inserting into mysql database.
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
require_once('dbConnect.php');
$userID = $_POST['userID'];
$sql = "SELECT * FROM employee WHERE userID='$userID'";
$result = mysqli_query($con,$sql);
$check = mysqli_fetch_array($result);
if(isset($check)){
$sql = "INSERT INTO dtr (userID,timeIN) VALUES ('$userID', now())";
mysqli_query($con, $sql);
echo 'Time IN Successful!';
}else{
echo 'Invalid USER ID. Please try again!';
}
mysqli_close($con);
}
?>
You should handle these checks inside the database. The current check you are doing in the database can be handled by a foreign key constraint:
alter table dtr add constraint fk_dtr_userId
foreign key (userId) references employee(userId);
The second means that you want only one row with a NULl value. Ideally, this could be handled with a unique constraint:
alter table dtr add constraint unq_dtr_userId_timeOut
unique (userId, timeOut);
Unfortunately (for this case), MySQL allows duplicate NULL values for unique constraints. So, you can do one of two things:
Use a default value, such as '2099-12-31' for time out.
Use a trigger to enforce uniqueness
In either case, the database itself will be validating the data, so you can be confident of data integrity regardless of how the data is inserted or updated.
I did it from my mobile not tested but you will get the idea of what is going on
if(isset($check))
{
$sql="SELECT * FROM dtr WHERE userID = $userID";
$result = mysqli_query($con,$sql);
$check = mysqli_fetch_array($result);
if(isset($check))
{
echo "Already in";
if(isset($check['timeIN']) && !isset($check['timeOUT']))
{
$sql = "UPDATE dtr SET timeOUT= now() WHERE userID=$userID";
mysqli_query($con, $sql);
mysqli_close($con);
}
}
else
{
$sql = "INSERT INTO dtr (userID,timeIN) VALUES ('$userID', now())";
mysqli_query($con, $sql);
mysqli_close($con);
echo 'Time IN Successful!';
}
}
else
{
echo 'Invalid USER ID. Please try again!';
mysqli_close($con);
}

Better way to check if row exist update else insert new record

what is the best way to write the query if row exist update else insert new record? I was trying the rubbish code as listed below:
<?php
for ($i = 0; $i < ($_POST['count']); $i++) {
$form_details_subquestion_id = $_POST['form_details_subquestion_id'][$i];
$form_details_section_id = $_POST['form_details_section_id'][$i];
$mark = $_POST['mark'][$i];
$remark = $_POST['remark'][$i];
$result = $db->query("
SELECT *
FROM audit_section_markrecord
WHERE
form_details_subquestion_id = $form_details_subquestion_id AND
audit_section_no = $audit_no
");
if ($result->num_rows == 1) {
$query2 = "
UPDATE audit_section_markrecord
SET
mark = '$mark',
dateofmodify = '$date'
WHERE
form_details_subquestion_id = '$form_details_subquestion_id' AND
audit_section_no = '$audit_no'
";
$result2 = $db->query($query2);
$query3 = "
INSERT INTO markrecord_update_details (
audit_section_no,
form_details_subquestion_id,
form_details_section_id,
mark,
userlog,
ipaddress
) VALUES (
'$audit_no',
'$form_details_subquestion_id',
'$form_details_section_id',
'$mark',
'$user_staff',
'$ip'
)
";
$result3 = $db->query($query3);
} else if ($result->num_rows == 0) {
$query4 = "
INSERT INTO audit_section_markrecord (
audit_section_no,
form_details_subquestion_id,
form_details_section_id,
mark
) VALUES (
'$audit_no',
'$form_details_subquestion_id',
'$form_details_section_id',
'$mark'
)
";
$result4 = $db->query($query4);
} else {
echo "<script>alert('Error. Please contact IT support.')</script>";
echo "<script language='javascript'>window.location.href='index.php'</script>";
}
}
The above code is writing inside for loop. I try to get if the form_details_subquestion_id AND audit_no is exist then update old records and insert to markrecord_update_details;else insert new records.
I don't know how to use the most easier to write the code. I just try to learn from this journey.
Best way is insert on duplicate key update.
Explanation for first query.
/* execute this directly in MySQL to add unique key constraint*/
ALTER TABLE audit_section_markrecord
ADD UNIQUE(form_details_subquestion_id, audit_section_no);
/* this query is for calling from php */
INSERT INTO audit_section_markrecord
SET
/* try to insert value */
mark = '$mark',
dateofmodify = '$date',
form_details_subquestion_id = '$form_details_subquestion_id',
audit_section_no = '$audit_no'
/* if constraint check fails, i.e. */
/* there is a row with this form_details_subquestion_id and audit_section_no */
/* then just update mark and dateofmodify */
ON DUPLICATE KEY UPDATE
mark = '$mark',
dateofmodify = '$date';
P.S. Escape you data to prevent sql-injection!
P.S2. To check it works, run 2 queries in MySQL:
INSERT INTO audit_section_markrecord
SET
mark = 'good',
dateofmodify = '2015-11-10',
form_details_subquestion_id = 10,
audit_section_no = 23;
INSERT INTO audit_section_markrecord
SET
mark = 'good',
dateofmodify = '2015-11-10',
form_details_subquestion_id = 10,
audit_section_no = 23
ON DUPLICATE KEY UPDATE
mark = 'excellent',
dateofmodify = '2015-11-26';
Row should have mark=excellent and dateofmodify=2015-11-26.
P.S3. If it's inserting duplicate rows, there was a problem with adding the unique key. Take a look at SHOW CREATE TABLE audit_section_markrecord. (Thanks Barmar).
#Andrew, seems I'v understood your needs.
You want to update markrecord_update_details only if audit_section_markrecord was updated (not inserted).
You check for update needed by combination of two columns: form_details_subquestion_id and audit_section_no.
Seems your code is working fine. Use it, don't complicate things.
I suggest you to postpone leaning "easier way" to do work. Add data escaping to prevent sql-injection and relax.
P.S. When you will be ready, google "mysql triggers on update", "unique key" and "on duplicate key update" (my prev example has some foundation for it).
Another way is to use a REPLACE statement. It works just like an INSERT statement, but when it tries to insert the record, if a record with the same keys exists then deletes the old record and inserts the new one. Since you are not updating based on previous values, this might be easier to work.
The user will need DELETE rights so this works.
Example:
$query4 = "REPLACE INTO `audit_section_markrecord` (audit_section_no,form_details_subquestion_id, form_details_section_id, mark) VALUES
('$audit_no', '$form_details_subquestion_id', '$form_details_section_id', '$mark') ";

pdo lastInsertId() keeps returning 0

I have two queries that insert data to their respective tables. That works fine. What I have been trying to do is get the lastInsertId after each query is executed and insert those values into a third table. However, when I check the database, the value 0 is entered. Both tables have an auto-incremented field. Can you tell by my code why that is happening or have any suggestions? I'm relatively new to php so if you notice the way I'm coding is untidy, particularly at the end where I execute the queries, please tell me. I'd appreciate it.
if ($oneWay)
{
$query = "INSERT INTO journey
(from_destination,to_destination,journey_type,depart_date,depart_time,seats_available,journey_message,user_type)
VALUES('$pjFrom','$pjTo','$radioJourneyType', STR_TO_DATE('$departDate','%d/%m/%Y'),'$newDepTime','$seatcounter','$textareanotes','$radUserType')";
$userID = "SELECT user_id FROM `user` ORDER BY journey_id DESC LIMIT 1";
}
else
{
$query = "INSERT INTO journey
(from_destination,to_destination,journey_type,depart_date,depart_time,return_date,return_time,seats_available,journey_message,user_type)
VALUES('$pjFrom','$pjTo','$radioJourneyType', STR_TO_DATE('$departDate','%d/%m/%Y'),'$newDepTime',STR_TO_DATE('$returnDate','%d/%m/%Y'),'$newRetTime ','$seatcounter','$textareanotes','$radUserType')";
//$userID = "SELECT user_id FROM `user` ORDER BY journey_id DESC LIMIT 1";
}
$queryfb = "INSERT INTO user
(facebook_id,facebook_username,facebook_first_name,facebook_last_name,facebook_image,facebook_link)
VALUES('$hdnFacebookId','$hdnUsername','$hdnFirstName','$hdnLastName','$hdnFacebookImg','$hdnFacebookUrl')";
//$journeyID = "SELECT journey_id FROM `journey` ORDER BY journey_id DESC LIMIT 1";
$queryUserJourney = "INSERT INTO user_journey
(user_id,journey_id)
VALUES('$lastUserID','$lastJourneyID')";
$db->exec($query);
$lastUserID = $db->lastInsertId();
$db->exec($queryfb);
$lastJourneyID = $db->lastInsertId();
$db->exec($queryUserJourney);//problem: 0 values being entered???
}
Updated
$db->exec($query);
$lastUserID = $db->lastInsertId();
$db->exec($queryfb);
$lastJourneyID = $db->lastInsertId();
$queryUserJourney = "INSERT INTO user_journey
(user_id,journey_id)
VALUES('$lastUserID','$lastJourneyID')";
$db->exec($queryUserJourney);working thanks to jmadsen
Now that I've had my coffee - you are creating the last insert statement BEFORE you populate the variables. I think this is what Maerlyn was hinting at
You need to move $queryUserJourney down below your 2 inserts.
You might want to try
$db->lastInsertId();
... instead. Note the lowercase d in lastInsertId.
Reference doc
#Colin,
PDO's last insert id returns the value of an auto-increment primary key, if I'm not completely mistaken. It looks to me like $query's table doesn't have this

value not inserting into mysql and not updating enum value to 1?

Can someone please help me. I'm trying to create a basic like system by inserting the values into mysql and auto incrementing the number of times the column 'likes' has been updated.
Basically the script will insert where there is not currently any record and update if there is a record.
I am trying to insert 'user_id' as a value, aswell but only the liked_id is being inserted into the table. the 'likes' column is being auto incremented as it should be but i need to find out how i can insert the user_id which is the users session id aswel and this isn't being put in. also i am trying to update the column 'user_id_has_liked' from enum value 0 to 1 as a final result.
can someone please show me where i am going wrong. thanks
<?php
require_once('includes/session.php');
require_once('includes/functions.php');
require('includes/_config/connection.php');
session_start();
confirm_logged_in();
if (isset ($_GET['to'])) {
$user_to_id = $_GET['to'];
}
if (!isset($_GET['to']))
exit('No user specified.');
$user_id = $_GET['to'];
$result = mysql_query("SELECT * FROM ptb_likes WHERE liked_id ='".$user_to_id."' ");
if( mysql_num_rows($result) > 0) {
mysql_query("UPDATE ptb_likes SET likes = likes +1 WHERE liked_id = '".$user_to_id."' ");
$user_to_id = mysql_query("ALTER TABLE likes AUTO_INCREMENT = $id");
}
else
{
mysql_query("INSERT INTO ptb_likes (user_id,liked_id) VALUES ('".$_SESSION['user_id'].",".$user_to_id."') ");
}
$result1 = mysql_query("UPDATE ptb_likes SET user_id_has_liked='1' WHERE user_id=".$_SESSION['user_id']."")
or die(mysql_error());
if($result)
{
header("Location: {$_SERVER['HTTP_REFERER']}");
}
?>
As the others said, mysql_* statements are depricated, use mysqli_* statements...
The first issue is the code in the user id insert statement was missing some quotes, it should look like this:
mysql_query("INSERT INTO ptb_likes (user_id,liked_id) VALUES ('".$_SESSION['user_id']."','".$user_to_id."') ");
The user_id_has_liked query issue could be caused by the enum variable being an integer in mysql. you could also try saving your query to a query variable and passing the variable to your query function for readability...
$query = "UPDATE ptb_likes SET user_id_has_liked='1' WHERE user_id=".$_SESSION['user_id'];
$result1 = mysql_query($query) or die(mysql_error());

Using Insert and Update in a single function

I was wondering if someone would be able to shed some light on how I may overcome this problem.
I'm trying to add and update information on a database, so when a user first enters completes the questionnaire its fine and it works, However when they go back to update the questionnaire it throws an error, "Please go back and try again".
I have updated the PHP code with the recommendations given to me so far.
Thank You.
PHP code:
function updatePartCTQ_part1($questionAns, $memberid) {
//First Insert MemberID
$ctqmemberinsert = "INSERT INTO ctq_questionnaire (user_id) VALUES ('$memberid')";
$addresult = mysqli_query($ctqmemberinsert);
if ($addresult) {
$update = "UPDATE ctq_questionnaire SET Item1= '{$questionAns[0]}', Item2 = '{$questionAns[1]}' WHERE user_id = '$memberid'";
mysqli_query($conn, $update);
} else {
echo 'Please go back and try again';
}
}
Any help will be greatly appreciated.
Finished Code
Thanks to Michael and the rest of the guys I was able to get the code working, so I thought I'd post an update, if anyone else gets stuck they'd be able to have a glance at the working version of the code:
function updatePartCTQ_part1($questionAns, $memberid) {
//Check whether user exists
$exists = mysql_query("SELECT * FROM ct1_questionnaire WHERE user_id = '$memberid'");
if (mysql_num_rows($exists) === 0) {
// Doesn't exist. INSERT User into Table
$ctqmemberinsert = "INSERT INTO ctq_questionnaire (user_id) VALUES ('$memberid')";
mysqli_query($ctqmemberinsert);
}
// UDPATE after INSERT
$update = "UPDATE ctq_questionnaire SET Item1= '{$questionAns[0]}', Item2 = '{$questionAns[1]}, Item3 = '{$questionAns[2]}',
Item4 = '{$questionAns[3]}',Item5 = '{$questionAns[4]}', Item6 = '{$questionAns[5]}', Item7 = '{$questionAns[6]}',
Item8 = '{$questionAns[7]}', Item9 = '{$questionAns[8]}', Item10 = '{$questionAns[9]}', Item11 = '{$questionAns[10]}',
Item12 = '{$questionAns[11]}', Item13 = '{$questionAns[12]}', Item14 = '{$questionAns[13]}', Item15 = '{$questionAns[14]}'
WHERE user_id = '$memberid'";
mysql_query($update);
}
Your UPDATE syntax is incorrect. You must not repeat the SET keyword:
$update = "UPDATE ctq_questionnaire SET Item1= '{$questionAns[0]}', Item2 = '{$questionAns[1]}' WHERE user_id = '$memberid'";
//-------------------------------------------------------------^^^^^^^ no SET here
For readability it is recommended to enclose the array values in {}, although your way should work.
Note that your try/catch isn't going to be of much use since mysql_query() does not throw an exception. Instead it will just return FALSE on error. Instead, store it in a variable and test for TRUE/FALSE as you did with the INSERT.
// We assume these values have already been validated and escaped with mysql_real_escape_string()...
$update = "UPDATE ctq_questionnaire SET Item1= '{$questionAns[0]}', Item2 = '{$questionAns[1]}' WHERE user_id = '$memberid'";
$upd_result = mysql_query($update);
if ($upd_result) {
// ok
}
else {
// error.
}
Finally, and I suspect you've heard this before, the old mysql_*() functions are scheduled for deprecation. Consider moving to an API which supports prepared statements, like MySQLi or PDO.
Update
Assuming you have a unique index or PK on ctq_questionnaire.user_id on subsequent calls, the first query will error and your second won't be run. The simplest fix is to use INSERT IGNORE, which will treat key violations as successful.
$ctqmemberinsert = "INSERT IGNORE INTO ctq_questionnaire (user_id) VALUES ('$memberid')";
A more complicated solution is to first test if the username exists in the table with a SELECT, and if not, do the INSERT.
$exists_q = mysql_query("SELECT 1 FROM ct1_questionnaire WHERE user_id = '$memberid'");
if (mysql_num_rows($exists_q) === 0) {
// Doesn't exist. Do the INSERT query
}
// proceed to the UDPATE after INSERTing if necessary
Just change your insertion to this:
$ctqmemberinsert = "INSERT INTO `ctq_questionnaire` (`user_id`, `Item1`, `Item2`)
VALUES ( '$memberid', '" .
mysql_real_escape_string($questionAns[0]) . "', '" .
mysql_real_escape_string($questionAns[1]) . "' )";

Categories