update only records that are non empty - php

I have this query, which i use to update a table.
The issue is, i need to update only values different from "undefined"
With the help of someone here i got to this query:
$sqlStart="UPDATE forma SET ";
$sql="";
if (!empty($postDyqani_pergjegjes)) $sql += " dyqani_pergjegjes='$postDyqani_pergjegjes',";
if (!empty($postEmri)) $sql += " emri='$postEmri',";
if (!empty($postKlienti)) $sql += " klienti='$postKlienti',";
if (!empty($postTelefoni)) $sql += " telefoni='$postTelefoni,'";
if (!empty($postMontim)) $sql += " montim='$postMontim',";
if (!empty($postAdresa)) $sql += " adresa='$postAdresa',";
if (!empty($postData_e_shitjes)) $sql += " data_e_shitjes='$postData_e_shitjes',";
if (!empty($postDifekti)) $sql += " difekti='$postDifekti',";
if (!empty($postTekniku_emer)) $sql += " tekniku_emer='$postTekniku_emer',";
if (!empty($postTekniku_mesazh)) $sql += " tekniku_mesazh='$postTekniku_mesazh',";
if (!empty($postData_fillim)) $sql += " data_fillim='$postData_fillim',";
if (!empty($postData_mbarim)) $sql += " data_mbarim='$postData_mbarim',";
if (!empty($postData)) $sql += " data='$postData',";
if (!empty($postStatus)) $sql += " status='$postStatus',";
// replace the last `,` for `;`
if ($sql != "") {
$sql = substr($sql, 0, -1) . ";";
// replace the last `,` for `;`
// run sql command
echo $sqlCommand = $sqlStart.$sql;
$result=mysql_query($sqlCommand) or die(mysql_error()) ;
} else {
}
It won't execute though..
Please give me a hand on this..
if i print the variables most of them result to be undefined
Thanks

There are many things broken with your approach; first of all, += won't do what you think it does for PHP strings, and will probably make everything end up as the value 0. Use .= to concatenate a string to an existing string:
$foo = '123';
$foo .= 'abc';
// $foo == '123abc'
Second, without any more information about where your variables are coming from, it'll be hard to say what's going the wrong way. If you have a field named 'Dyqani_pergjegjes', the correct way to reference it will be to use $_POST['Dyqani_pergjegjes'].
In addition you need to escape strings that you want to use in an SQL query, to avoid SQL injection exploits and other possible bugs (or use prepared statements in mysqli or by using PDO) if you want do solve it properly):
difekti='". mysql_real_escape_string($postDifekti) . "'
You're also missing a condition for your UPDATE-statement, so in it's current form it'll change all the rows in the database. Probably not what you want. And you do not need to add a ";" at the end of the statement - this is implicit when performing a query, and is generally advised against.

Related

mysqli_query returns false because values contain space charcter

I am inserting data from a excel sheet but i receive error and it looks like it is breaking because the value contain a space character in between. As far as i remember space characters allowed in VARCHAR(200)
This is the code i am using
//CREATE SQL QUERY FOR INSERTING DATA IN DATABASE
$sql = "INSERT INTO ".$month."_".$year."(";
foreach($sheetData[1] as $columnName){
$sql .= preg_replace('#[ ]#', '_',$columnName). ",";
}
$sql = rtrim($sql, ',');//REMOVES COMMA FROM END OF THE STRING
$sql .= ")";
//
$sql .= " VALUES((";
for($i=2;$i < count($sheetData);$i++){
foreach($sheetData[$i] as $columnName){
$sql .= $columnName.",";
}
$sql = rtrim($sql,',');//
$sql .= "),";
}
$sql = rtrim($sql,',');//
$sql .= ")";
echo $sql;
$query = mysqli_query($conn,$sql) or die(mysqli_error($conn));
After loops this is how my SQL QUERY look
INSERT INTO December_2015(S_No,Zone,State,City2,VM_Town,Distibutor_Code,Distributor_Name,Dealer_Code,Dealer_Name,Category,Address,Location,Contact,Mobile_No,Visit_1,Visit_2,Visit_3,Visit_4,Visit_5,Visit_6) VALUES( (1,South,Telanagana,Hyderabad,Y,1006704,Sai Santhoshi Enterprises,TG000999,Sree Laxmi Mobiles,A,F4,anthem Arcade,gujarathi Galli,koti ,Koti,Rajesh,8790575680,7-Nov,18-Nov,28-Nov))
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 'Santhoshi Enterprises,TG000999,Sree Laxmi Mobiles,A,F4,anthem Arcade,gujarathi G' at line 1
It says near 'Santhoshi Enterprises ... ' before that there is a space character
You have two "(" instead of one after "VALUES"
Akash,
Didn't you asked a question just a while ago regarding same/similar code with a different error you got, here at: How to loop inside a variable ?!
By the looks of it in general you write messy code, and you are having trouble reading/understanding the error messages. So I'm gonna guess you are new at this.
Here are some good reads for you:
Top 15+ Best Practices for Writing Super Readable Code
PHP the right way
When all said and done, here is your code broken down into more readable segments:
// prepare dummy data
$month = date('M');
$year = date('Y');
$sheetData = array(
array('data00', 'data01')
,array('col1', 'col2', 'col3', 'col4', 'col5', 'col6')
,array('data20', "data21")
,array('data30', 'data31')
,array('data40', 'data41')
);
// prepare vars
$tableName = "{$month}_{$year}";
$dataCount = count($sheetData);
// prepare columns
$columnsSQL = "";
foreach ($sheetData[1] as $columnName) {
// wrap with ` ticks
$columnsSQL .= '`'. preg_replace('#[ ]#', '_', $columnName).'`'.',';
}
$columnsSQL = rtrim($columnsSQL, ',');
// prepare values
$valuesSQL = "";
for ($i=2;$i < $dataCount;$i++) {
foreach($sheetData[$i] as $columnValue){
$valuesSQL .= "'{$columnValue}', ";
}
}
$valuesSQL = rtrim($valuesSQL, ', ');
$SQL = "
INSERT INTO {$tableName}( {$columnsSQL} )
VALUES ( {$valuesSQL} )";
At the end you end up with something like this:
INSERT INTO Nov_2015( `col1`,`col2`,`col3`,`col4`,`col5`,`col6` )
VALUES ( 'data20', 'data21', 'data30', 'data31', 'data40', 'data41' )
Additional note and tips:
Considering that you said you are reading data from excel sheet... Never trust input data without some tests/checks/validation. Not just because of security but stability and in general you don't want things breaking.
Those excel tables could be manually made which automatically means its prone for human error, so you can't be always 100% sure what are you gonna get.
Consider using PDO and prepared statements (security reasons, but also good practice)

Split mysql query and delete a part of that

I have many conditions in PHP function which every of them produces a mysql query.All conditions work correctly except one query which ends with AND operator.Before returning the query result I need to check if query ends with AND it should remove AND and then returnes the query.
This is the sample of query:
$query="select * from case where case_name='name' AND case_status='102' AND";
If this kind of query is produced I need to do:
1-If it ends with AND
2-remove AND
3-return the query without last AND
The result should be like this:
$query="select * from case where case_name='name' AND case_status='102' ";
I do not have much experience to work with PHP functions.How can I do this?
Thnaks for your help.
Try this,
$query="select * from case where case_name='name' AND case_status='102' AND"
$query = trim($query,'AND');
quick fix:
$query = preg_replace( "/AND$/", "", $query);
You should fix the logic of condition though.
like
$cond[] = "....";
$cond[] = "...."
....
then
$query = $query_first_half + implode ( " AND " , $cond );
Ultimately please use sql library like PDO
http://fi1.php.net/manual/en/class.pdo.php
explode the string and pop the last element .
$arr = explode(" ", $query);
$last = array_pop($arr);
if($last != "and")
{
array_push($arr,$last);
}
$query = implode(" ",$arr);
Run the $query them it should work
First your table name CASE is mysql reserved keyword you should rename your table to something else or escpae it by backticks `
you could use query without AND , and when you add other query just start by AND .
like that :
$query="select * from `case` where case_name='name' AND case_status='102'";
$query .= " AND .........";
so like that , your condition is not true then just first query will work , if condition is true then second query will work and it start by AND. You dont need to remove the AND.

PHP MySQL Update Set query with Multiple columns

I've tried this query with both commas and "AND" statements as pictured below. I get a syntax error
Something went wrong.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 'are available 24/7 by phone and email to answer any questions and to assist you ' at line 1
every time I try this query:
$sql = mysql_query("UPDATE general
SET bookabandheading = $_POST[bookabandheading
AND bookaband = $_POST[bookaband]
AND contactus = $_POST[contactus]
AND aboutuslisten = $_POST[aboutuslisten]
AND contactusheading = $_POST[contactusheading]
AND nightclubsheading = $_POST[nightclubsheading]
AND acousticheading = $_POST[acousticheading]
AND schoolsheading = $_POST[schoolsheading]
AND privateheading = $_POST[privateheading]
AND concertsheading = $_POST[concertsheading]
AND festivalsheading = $_POST[festivalsheading]
AND submissions = $_POST[submissions]
AND interns = $_POST[interns]
AND managementbio = $_POST[managementbio]
AND latestnews = $_POST[latestnews]
AND artistofthemonth = $_POST[artistofthemonth]
AND artistofthemonthphoto = $_POST[artistofthemonthphoto]
AND artistofthemonthid = $_POST[artistofthemonthid]
AND listentoourartists = $_POST[listentoourartists]
AND musicianswanted = $_POST[musicianswanted]
AND aboutus = $_POST[aboutus]
AND bshowcases = $_POST[bshowcases]
AND bandavails = $_POST[bandavails]");
The query worked in a different database on another VPS, but I just migrated servers and it no longer works. Any help is greatly appeciated!
While the main problem is that you missed the closing bracket after bookamandheading, still I would like to advise you to refactor this request for example like this:
$keys = array("bookabandheading", "bookaband", "contactus", "aboutuslisten",
"contactusheading", "nightclubsheading", "acousticheading",
"schoolsheading", "privateheading", "concertsheading",
"festivalsheading", "submissions", "interns", "managementbio",
"latestnews", "artistofthemonth", "artistofthemonthphoto",
"artistofthemonthid", "listentoourartists", "musicianswanted",
"aboutus", "bshowcases", "bandavails");
$set = array();
foreach ($keys as $key) {
$set[] = sprintf(" %s = '%s' ", $key, mysql_escape_string($_POST[$key]));
}
$sql = mysql_query("UPDATE general SET " . implode(", ", $set));
It is much easier to maintain and also a bit more secure by escaping the input.
Update: add where statement example
$where = array();
$where[] = sprintf(" some_string = '%s' ", mysql_escape_string($some_string));
$where[] = sprintf(" some_integer = %d ", $some_integer);
$where = " WHERE " . implode(" AND ", $where);
$sql = mysql_query("UPDATE general SET " . implode(", ", $set) . " " . $where);
I see 3 things wrong with this:
Raw POST data in your query - at the very least user mysql_real_escape_string
The parameters look like strings so should have quotes around them
There's no WHERE option, so you'll update every row in that table
You have a few errors:
Syntax error. Change
$_POST[bookabandheading to $_POST[bookabandheading]
This is also incredibly prone to SQL injections. You should be using mysqli, but if you are set on mysql (which is deprecated as of 5.5.0), you should escape each $_POST variable using mysql_real_escape_string().
Each $_POST variable needs to bee parameterized using quotes a well. So, an example:
$_POST['bookabandheading'] (do this for all $_POST variables)
$_POST[bookabandheading
change to
$_POST[bookabandheading]

how to delete all rows using IN OPERATOR in mysql php

i am having problem in understanding the behaviour of this programme below is simple code to delete the email address using IN operator
$emails = $_POST['ids'];
$sql = "DELETE FROM newsletter where email ";
$condition = sprintf('IN ("%s")',implode(' "," ',$_POST['ids']));
$sql = $sql.$condition;
include '../includes/db.php';
$r = mysql_query($sql);
echo $sql;
it only deletes one email id and returns true . how can i make it run in a way it deletes all the emails .
below is the query constructed using the above code.
DELETE FROM newsletter where email IN ("adfadsf#gmail.com ","
asdfasfasf#gmail.com "," kjhkhsd#assdfsdf.sdfsf "," shit#gshit.com ","
someother#gmail.com")
is it wrong way of deleteing ?
Instead of:
$condition = sprintf('IN ("%s")',implode(' "," ',$_POST['ids']));
do:
$condition = sprintf('IN ("%s")',implode('", "',$_POST['ids']));
IN operator matches contents of the field with the values exactly. Spaces at the beginnings and ends of values might have cause your problems.
The query is valid however you are adding spaces before/after the email.
" asdfasfasf#gmail.com " does not match "asdfasfasf#gmail.com"
This code would be vulnerable to SQL injection attacks, i could make post something like
"); delete from newsletter; delete from newsletter where email in ("
the " are part of my post string, this would wipe your newsletter table.
However that aside the key issue with your code is potentially the spaces (do your strings include spaces in the database?) and the use of double quotes. I'm not 100% certain but I'm sure " can be used as a field indicator rather than a string so you probably want single quotes.
$emails = $_POST['ids'];
$sql = "DELETE FROM newsletter where email ";
$condition = sprintf("IN ('%s')",implode("','",$_POST['ids']));
$sql = $sql.$condition;
include '../includes/db.php';
$r = mysql_query($sql);
echo $sql;
Output then should be
DELETE FROM newsletter where email IN ('adfadsf#gmail.com','asdfasfasf#gmail.com','kjhkhsd#assdfsdf.sdfsf','shit#gshit.com','someother#gmail.com')
If you need to insert strings in a SQL query you have to single-quote them and protect against SQL injection. Also, the comma separator in the IN clause should not be quoted.
$safe_emails = array();
foreach($_POST['ids'] as $i){
$safe_emails[] = "'" . mysql_real_escape_string($i) . "'";
}
$sql = 'DELETE FROM newsletter WHERE email IN (' . implode(', ', $safe_emails) . ')';

MySQL or PHP syntax oversight when trying to perform conditional update

I think this is an escaping issue or something. When I execute the query and populate all variables, everything is peachy and all row is updated properly in the DB.
I looked on StackOverflow to get me rolling with these dynamic/contructed on the fly queries and I'm at the end of my rope.
My stuff looks like this:
$sql="UPDATE users SET ";
if (!empty($fname)) { "fname = '$fname', ";}
if (!empty($lname)) { "lname = '$lname', ";}
if (!empty($location)) { "location = '$location', ";}
if (!empty($url)) { "url = '$url', ";}
"WHERE id = '$id' LIMIT 1";
When I break the query to insert the "IFs" I keep getting the following: 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
I ECHO'd the query and for some odd reason it's nto complete and the variables are coming in before the query start like so
fname = 'Rob', lname = 'Smith', location = 'Jersey City, NJ', url = 'http://somesite.com', UPDATE users SET 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
Sorry if I am not clear. I will clarify where needed. I am new at all this. Thank you!
You're not allowed to have a comma after the last thing you SET.
One easy solution is this:
$set = array();
if (!empty($fname)) { $set[] = "fname = '$fname'";}
if (!empty($lname)) { $set[] = "lname = '$lname'";}
if (!empty($location)) { $set[] = "location = '$location'";}
if (!empty($url)) { $set[] = "url = '$url'";}
if(!empty($set)) {
$sql = "UPDATE users SET ";
$sql .= implode(', ', $set)
$sql .= " WHERE id = '$id' LIMIT 1";
}
Oh, and make sure the variables you're shoving in the query are SQL safe; otherwise you've got a SQL injection issue.
Remember in these programming languages, each statement (text ending with a ;) is much like a complete sentence. You need a subject-object-verb for it to make sense. I can't just say
doggy;
I have to say
feed the doggy;
Similarly, I can't just say
"fname = '$fname', "
when I mean "Append this string to the query I started earlier". I have to be explicit:
$sql .= "fname = '$fname', ";
I'm saying "Append this text to $sql". Its a complete sentence.
better to put all your SETs into an array and implode them into a string. That way you can be sure there are no dangling commas. Something like:
if (!empty($fname)) $sets[]="fname = '$fname' ";
if (!empty($lname)) sets[]= "lname = '$lname' ";
if (!empty($location)) sets[]= "location = '$location' ";
if (!empty($url)) sets[]= "url = '$url' ";
$setstring= implode(',',$sets);
if($setstring) {
$query="UPDATE users SET $sets WHERE id = '$id' LIMIT 1";
//run query, etc.
}
Not really a direct answer but for dynamic queries i suggest using PDO. That way you can specify optional parameters more secure, elegant and easier.
<?php
$stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (:name, :value)");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':value', $value);
// insert one row
$name = 'one';
$value = 1;
$stmt->execute();
// insert another row with different values
$name = 'two';
$value = 2;
$stmt->execute();
?>
If your queries become larger, the way you are doing things now will be pretty complicated to maintain.
echo out your query and take a look at the commas in your SET caluse. Do you have too many? Not enough? I think you'll find that you have one extra comma. You'll probably want to use the implode() function to build up your SET clause. This will insert the appropriate number of commas in the appropriate places.
I see two problems, there is no space before WHERE which means it could turn out "url=http://www.stackoverflow.com"WHERE" and maybe cause a problem.
Also, there is a comma at the end of every SET clause, the last one in the list should not have a comma.

Categories