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!
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.
I have been given a task to convert the hardcoded fields into dynamic fields.I have changed it partially to dynamic
Let me explain you the situation ,
We have a lot of databases and each database has a table by name Surveys
By using the DESCRIBE statement we will retrieve the fields in the Surveys table regardless of the database .
I need to know the way where we can loop again and again till all the fields in the survey table appears.
In the below code I have left the for loop blank .
Please let me know the changes that neeeds to be done to get this working
I would really appreciate any kind of help
function insertIntoUserUploadFileds() {
$describe="DESCRIBE surveys";
$sql = "INSERT INTO `userUploadFields` (`fieldName`, `inUse`, `mandatory`, `type`, `mapTo`) VALUES";
$inUse="0";
$type="";
//for(){
if($field=='type'){
$type="N";
}elseif(($field=='fname') || ($field=='lname') || ($field=='phone')){
$inUse="1";
$type="T";
}elseif($field=='email'){
$inUse="1";
$type="E";
}
//$sql .= "('".$field."', '".$inUse."', '0', '
$result1 = mysql_query ($describe);
$result = mysql_query ($sql);
//}
}
$result1 = mysql_query ('DESCRIBE surveys');
//here is how you retieve all field and check
while($row = mysql_fetch_array($result1)) {
$sql = "INSERT INTO `userUploadFields` (`fieldName`, `inUse`, `mandatory`, `type`, `mapTo`) VALUES";
//here you can do if else to check the column name
if($row['field']=='type')
{
$type="N";
}
else if(($row['field']=='fname') || ($row['field']=='lname') || ($row['type']=='phone'))
{
$inUse="1";
$type="T";
}
else ($row['field']=='email')
{
$inUse="1"
$type="E";
}
//build your query
$sql .= "('".$field."', '".$inUse."', '0', '......)
//execute your complete query
$result = mysql_query ($sql);
}//end of while
Instead of using DESCRIBE, if you are trying to retrieve the default type of a particular column you might look into this. It describes how to break down the information from a particular table. Codex
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]) . "' )";
I have the following code which is supposed to increment a field value by 1 in a prepared PHP mysql statement:
function db_OP_doVote($pdo, $postid, $votetype)
{
$prepStatement = $pdo->prepare(
"UPDATE content_posts SET `:votetype` = `:votetype` + 1 WHERE `id` = :id"
);
$prepStatement->execute(array(':votetype' => $votetype, ':id' => $postid));
echo "Success";
}
This however, does nothing. No error is thrown back about incorrect SQL syntax and the script runs to completion, but my field does not update at all.
The values for this script are fed through a jQuery post() to this script:
//isset checking here
$postID = (int)$_POST['id'];
$voteType = $_POST['type'];
if ($voteType == "y")
{
$trueType = "v-cool";
}
elseif ($voteType == "m")
{
$trueType = "v-meh";
}
elseif ($voteType == "n")
{
$trueType = "v-shit";
}
else
{
die();
}
$db = db_Connect();
db_OP_doVote($db, $postID, $trueType);
Which also appears to filter the values and send them fine. I can't wrap my head around what the issue could be. The field being incremented is a BIGINT(20).
What am I missing?
EDIT: Solved the issue.
N.B's comment hit the nail on the head - binding the column name causes it to be quoted, which invalidates the query. Thanks!
you can't use binding for the field names.
from the question it seems that your setup is wrong.
you should have another table with votes and vote types as data.
You can't parameterize column names with PDO. What you can do is have hard-coded values (which you basically already have) and construct the SQL string accordingly. I would check this value in the actual function too though, just to be on the safe side:
function db_OP_doVote($pdo, $postid, $votetype)
{
if( !in_array( $votetype, array( 'v-cool', 'v-meh', 'v-shit' /*, etc. */ ), true ) )
{
throw new InvalidArgumentException( 'Unexpected $votetype: ' . $votetype );
// or simply return false perhaps
}
$sql = '
UPDATE content_posts
SET `' . $votetype . '` = `' . $votetype . '` + 1
WHERE `id` = :id
';
$prepStatement = $pdo->prepare( $sql );
$prepStatement->execute(array(':id' => $postid));
echo "Success";
}
However, this strategy suggests your database design could use a little more attention. The way you have it now, is that for every type of vote, you have a column. This is not really efficient and/or flexible database design. What happens if you get asked to add another type of vote?
I'd suggest adding another table, to be more flexible:
CREATE TABLE `content_post_vote` (
`content_post_id` int(11) NOT NULL,
`vote_type` enum('cool','meh','shit') NOT NULL, # using enum() to assure valid vote types
`votes` bigint(20) DEFAULT NULL,
PRIMARY KEY (`content_post_id`,`vote_type`)
)
Then your query would be something like:
$sql = '
INSERT INTO `content_post_vote` (`content_post_id`,`vote_type`,`votes`)
VALUES( :id, :votetype, 1 )
ON DUPLICATE KEY UPDATE `votes` = `votes` + 1
';
What this does is insert a vote if there is no record for a certain primary key (content_post_id,vote_type) yet, and else update the record with a vote if the record already exists.
Then to query the database for how many votes of a particular type a particular content_post has gotten, you do this:
$sql = '
SELECT `votes` # or perhaps more columns
FROM `content_post_vote`
WHERE `content_post_id` = :id AND
`vote_type` = :votetype
';
I have mysql table with following fields
id (which auto increments)
title,name,age,institution,iod
the fields like title,name,age,institution are entered in the form structure (html page) and by clicking submit button are stored in DB(mysql)
iod is the field is something like this 123/id (nothing but same id field but with '123/' prefix before)
now when the user enters title,name,age,institution these need to stored in DB including id and iod.
Now for executing the above i wrote the following the fields title,name,age,institution and id are successfully stored but iod is not stored.
Can you please show me the error i made here??
I wrote the following syntax for the code(part of the same code)
if ($_POST['title'] != '')
{
$value = $_POST['title'];
$value1 = $_POST['name'];
$value2 = $_POST['age'];
$value5 = $_POST['institution'];
$sql = "INSERT INTO parentid(title,name,age,institution) VALUES('$value','$value1','$value2','$value5')" ;
}
$sql1="SELECT * FROM parentid ORDER BY id DESC LIMIT 1";
$value6=$row['id'];
$value4= '123/' . $row['id'] ;
$sql2="UPDATE parentid SET iod='$value4' WHERE id = '$value6' ";
The problem is that you are not executing your queries, you just put the query in a string but then you donĀ“t do anything with it.
For the second query (simple sample code):
$sql1="SELECT * FROM parentid ORDER BY id DESC LIMIT 1";
$result = mysql_query($sql1);
if ($row = mysql_fetch_assoc($result))
{
$value6=$row['id'];
// etc., error handling not added
}
You didn't execute any of the queries? Also, you should escape the parameters...
if ( !empty( $_POST['title'] ) || !empty( $_POST['calc_url'] ) ) {
$value = mysql_real_escape_string( $_POST['title'] );
$value1 = mysql_real_escape_string( $_POST['name'] );
$value2 = mysql_real_escape_string( $_POST['age'] );
$value5 = mysql_real_escape_string( $_POST['institution'] );
$sql = "INSERT INTO parentid
(title,name,age,institution)
VALUES ('$value','$value1','$value2','$value5')" ;
mysql_query( $sql ) or die( mysql_error());
}
Also, you don't need a second select... Get the id by using mysql_insert_id function.
$value6 = mysql_insert_id();
$value4= '123/' . $value6 ;
And then update:
$sql2="UPDATE parentid SET iod='$value4' WHERE id = '$value6' ";
mysql_query( $sql2 );
I encorage you to use PDO or mysqli though...
Unless you've missed out chunks of code when copying/pasting into the question, there are a few problems.
Firstly, you're not actually executing the queries (I'm assuming that you are actually connecting to the database somewhere). After you assign a string to $sql, you can execute the query:
$result = mysql_query($sql);
Secondly, $row won't contain anything unless you get the data out of the dataset returned by the query:
$row = mysql_fetch_assoc($result);
Third, your if statement does not contain the UPDATE query, so that's going to execute whether or not $_POST['title'] is empty or not.
As others have mentioned, your queries are wide open to SQL injection attacks. At a minimum you will need to use mysql_real_escape_string around any inputs.
Finally, you can use mysql_insert_id to get the ID of the latest insert, instead of making another read.
Here's some attempt to rework your code (note that this is untested and could be much better):
if($_POST['title'] != '') {
//Connect to database here (or somewhere else if you already are)
$value = mysql_real_escape_string($_POST['title']);
$value1 = mysql_real_escape_string($_POST['name']);
$value2 = mysql_real_escape_string($_POST['age']);
$value5 = mysql_real_escape_string($_POST['institution']);
$sql = "INSERT INTO parentid(title,name,age,institution) VALUES('$value','$value1','$value2','$value5')";
$result = mysql_query($sql);
if($result) {
$value6 = mysql_insert_id($result);
$value4 = '123/' . $value6;
$sql2 = "UPDATE parentid SET iod='$value4' WHERE id = '$value6'";
mysql_query($sql2);
}
}
My guess is that you have a special character that needs escaping.
I'm assuming you already know you should escape all those strings before inserting them in the DB.
In PHP you have a mysql_real_escape_string function that you should use to escape each of those values.