Using Insert and Update in a single function - php

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]) . "' )";

Related

Check if an user is in a database

I have developed a game with Javascript and when the user finishes it, I must save his record in a database. Here you see the code:
$temp = $_POST['playername']; //username
$text = file_get_contents('names.txt'); //list with all usernames
//this text file contains the names of the players that sent a record.
$con=mysqli_connect("localhost","username","pass","my_mk7vrlist");
if (stripos(strtolower($text), strtolower($temp)) !== false) {
//if the username is in the list, don't create a new record but edit the correct one
mysqli_query($con, "UPDATE `my_mk7vrlist`.`mk7game` SET `record` = '".$_POST['dadate']."' WHERE `mk7game`.`playername` = ".$temp." LIMIT 1 ");
} else {
//The username is not in the list, so this is a new user --> add him in the database
mysqli_query($con, "INSERT INTO `mk7game` (`playername`,`record`,`country`,`timen`) VALUES ('".$_POST['playername']."', '".$_POST['dadate']."', '".$_POST['country']."', '".$_POST['time_e']."')");
file_put_contents("names.txt",$text."\n".$temp);
//update the list with this new name
}
//Close connection
mysqli_close($con);
When I have a new user (the part inside my "else") the code works correctly because I have a new row in my database.
When the username already exists in the list, it means that this player has already sent his record and so I must update the table. By the way I cannot edit the record on the player that has alredy sent the record.
mysqli_query($con, "UPDATE `my_mk7vrlist`.`mk7game` SET `record` = '".$_POST['dadate']."' WHERE `mk7game`.`playername` = ".$temp." LIMIT 1 ");
It looks like this is wrong, and I can't get why. I am pretty new with PHP and MySQL.
Do you have any suggestion?
You're missing quotes around $temp in the UPDATE statement:
mysqli_query($con, "UPDATE `my_mk7vrlist`.`mk7game`
SET `record` = '".$_POST['dadate']."'
WHERE `mk7game`.`playername` = '".$temp."'
^ ^
LIMIT 1 ") or die(mysqli_error($con));
However, it would be better to make use of prepared statements with parameters, rather than inserting strings into the query.
Escape your user input!
$temp = mysqli_real_escape_string($con, $_POST['playername']);
Make sure to stick your mysqli_connect() above that
$select = mysqli_query($con, "SELECT `id` FROM `mk7game` WHERE `playername` = '".$temp."'");
if(mysqli_num_rows($select))
exit("A player with that name already exists");
Whack that in before the UPDATE query, and you should be good to go - obviously, you'll need to edit it to match your table setup

update profile php

I have create a profile page in php. The page includes the address and telephone fields and prompts the users to insert their data. Data are then saved in my table named profile.
Everything works fine, but the problem is that the table updated only if it includes already data. How can I modify it (probably mysql query that I have in my function), so that data will be entered into the table even if it is empty. Is there a something like UPDATE OR INSERT INTO syntax that I can use?
Thanks
<?php
if ( isset($_GET['success']) === true && empty($_GET['success'])===true ){
echo'profile updated sucessfuly';
}else{
if( empty($_POST) === false && empty($errors) === true ){
$update_data_profile = array(
'address' => $_POST['address'],
'telephone' => $_POST['telephone'],
);
update_user_profile($session_user_id, $update_data_profile);
header('Location: profile_update.php?success');
exit();
}else if ( empty($errors) === false ){
echo output_errors($errors);
}
?>
and then by using the following function
function update_user_profile($user_id, $update_data_profile){
$update = array();
array_walk($update_data_profile, 'array_sanitize');
foreach($update_data_profile as $field => $data )
{
$update[]='`' . $field . '` = \'' . $data . '\'';
}
mysql_query(" UPDATE `profile` SET " . implode(', ', $update) . " WHERE `user_id` = $user_id ") or die(mysql_error());
}
I'm new to the posted answer by psu, and will definatly check into that, but from a quick readthrough, you need to be very careful when using those special syntaxes.
1 reason that comes to mind: you have no knowledge of what might be happening to the table that you're inserting to or updating info from. If multiple uniques are defined, then you might be in serious trouble, and this is a common thing when scaling applications.
2 the replace into syntax is a functionality i rarely wish to happen in my applications. Since i do not want to loose data from colomns in a row that was allready in the table.
i'm not saying his answer is wrong, just stating precaution is needed when using it because of above stated reasons and possible more.
as stated in the first article, i might be a newbie for doing this but at this very moment i prefer:
$result = mysql_query("select user_id from profile where user_id = $user_id limit 1");
if(mysql_num_rows($result) === 1){
//do update like you did
}
else{
/**
* this next line is added after my comment,
* you can now also leave the if(count()) part out, since the array will now alwayss
* hold data and the query won't get invalid because of an empty array
**/
$update_data_profile['user_id'] = $user_id;
if(count($update_data_profile)){
$columns = array();
$values = array();
foreach($update_data_profile as $field => $data){
$columns[] = $field;
$values[] = $data;
}
$sql = "insert into profile (" . implode(",", $columns) .") values ('" . implode("','", $values) . "')" ;
var_dump($sql); //remove this line, this was only to show what the code was doing
/**update**/
mysql_query($sql) or echo mysql_error();
}
}
You cannot update the table if there isn't any data in it corresponding the user_id, meaning that you must have a row containing the user_id and null or something else for the other fields.
a) You can try to check if the table contains data and if not insert it else use update (not ideal)
$result = mysql_query("UPDATE ...");
if (mysql_affected_rows() == 0)
$result = mysql_query("INSERT ...");
b) Checkout this links
http://www.kavoir.com/2009/05/mysql-insert-if-doesnt-exist-otherwise-update-the-existing-row.html
http://dev.mysql.com/doc/refman/5.0/en/replace.html
http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
#Stefanos
you can use use "REPLACE INTO " command in place of "INSERT INTO" in the SQL query.
for example
Suppose you have insert query
INSERT INTO EMPLOYEE (NAME,ADD) values ('ABC','XYZZ');
Now you can use following query as combination of insert and update
REPLACE INTO EMPLOYEE (NAME,ADD) values ('ABC','XYZZ');
Hope this will help!

INSERT INTO table1 values FROM table2 WHERE

I've looked around nothing seems to be working for me. I have a button when pushed it INSERTS data into 1 table-1, then it gets values from table-3 to put in table-2 where in they the ID is the same.
if ($movieTime != "") {
$query = "SELECT SchedID FROM tblCinemaSched WHERE TheaterID='$tid' AND CinemaID='$cid' AND MovieDate='$date' AND MovieTime='$movieTime'";
//echo "$query<br>";
$result=$conn->executeUpdate($query);
$numRows=$conn->numRows($result);
if ($numRows<=0) {
$query = "INSERT INTO tblCinemaSched SET TheaterID='$tid', CinemaID='$cid', MovieDate='$date', MovieTime='$movieTime', MovieID='$movieId', PriceAmt='$priceId', CrtBy='$username', CrtDate=NOW()";
//echo "$query<br>";
$result=$conn->executeUpdate($query);
//get seat defaults from tblCSeats
$query = "INSERT INTO tblSSeats SELECT TheaterID, CinemaID, '$date', '$movieTime', SeatID, RowNo, ColumnNo, Handicap, Status, LeftSeat, RightSeat, NULL, NULL,NULL,NULL,NULL,NULL,NULL,'$username',NOW() FROM tblCSeats WHERE TheaterID='$tid' AND CinemaID='$cid'";
//echo "$query<br>";
$result=$conn->executeUpdate($query);
$errorStr = "Succesfully added schedule.";
}
else {
$errorStr = "There's already an existing schedule for the specified time.";
}
You see tableCSeats has more than 1 row that has the same ID meaning I want to insert multiple data from tableCSeats to tableSSeats. tableSSeats is a has no data in it yet.
At a blind guess, it would seem that you are looking for INSERT ... SELECT statement.
check the return values of your queries. You always get "Succesfully added schedule." because you don't check if the queries were succesful. Ex:
if(!$result=$conn->executeUpdate($query)) {
die('error');
}
or something like that.

Update/Insert into mysql query

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.

SQL error in php

Hey, I wrote some code for extracting some information out of the database and checking to see if it met the $_COOKIE data. But I am getting the error message:
Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ')' at line 1
My code so far is:
$con = mysql_connect("XXXX","XXXXX","XXXXXXX");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("XXXXXX", $con);
$id = $_COOKIE['id'];
$ends = $_COOKIE['ends'];
$userid = strtolower($_SESSION['username']);
$queryString = $_GET['information_from_http_address'];
$query = "SELECT * FROM XXXXX";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
if ($queryString == $row["orderid"]){
$sql="UPDATE members SET orderid = ''WHERE (id = $id)";
$sql="UPDATE members SET level = 'X'WHERE (id = $id)";
$sql="UPDATE members SET payment = 'XXXX'WHERE (id = $id)";
$sql="UPDATE members SET ends = '$ends'WHERE (id = $id)";
if (!mysql_query($sql))
{
die('Error: ' . mysql_error());
}
}
}
Any help would be appreciated,
Thanks.
$sql="UPDATE members SET ends = '$ends'WHERE (id = $id)";
should be
$sql="UPDATE members SET ends = '$ends'WHERE (id = '$id')";
(IE add the ' around $id)
I'm not sure if this is the error, but do you realize you're code only runs the last UPDATE? You're assigning $sql 4 time, and only running it after the fourth assignement...
If $_COOKIE['id'] does not have a value, then $id in your SQL statements will be blank, leaving your SQL looking like this:
UPDATE members SET ends = 'something' WHERE (id = )
which, of course, is invalid SQL.
Only one of the SQL statements will execute, and that's the last one. You need to add some whitespace before the WHERE clause, like this:
$sql="UPDATE members SET ends = '$ends' WHERE (id = $id)";
Also be wary of SQL injection attacks in the event that your cookie is altered by the end user. One other thing of note is your orderid column. Is it a VARCHAR or some other unique identifier? If it's an integer, then setting it to empty string will not work. You might want to rethink your schema a bit here.
EDIT: Another thing you need to do is check to make sure the cookies actually have values. If not, your SQL strings will be messed up. Have you though about using parameterized queries through PDO so you don't have to worry about SQL injection at all?
first of all you keep overwriting $sql variable so only the
$sql="UPDATE members SET ends = '$ends'WHERE (id = $id)";
is being executed.
And I would say that $id variable is not what you think it is (maybe empty as query like the one above without id:
$sql="UPDATE members SET ends = '$ends'WHERE (id = )";
would throw such error back.
Try
$id = NULL;
before
$id = $_COOKIE['id'];
if the error is gone that means that $id is not what you think it is

Categories