$query="INSERT INTO subscriber (RandomCode,Email,CreateDate,UpdateDate <?if ($num!=0) echo ','.$string; ?> ) VALUES (?,?,?,?,CURDATE(),'',<? if ($num!=0) echo ','.$stringResult; ?>)";
echo $query;
If i add something conditional in the sql statement , it will not check or trigger the php function.
if (!isset($set['Attribute']))
{$set['Attribute']=NULL;} <=======This statement to check if there is no value posted
$stringResult=$stringResult.$_POST[$set['Attribute']].",";}}
$stringResult = substr($stringResult, 0, -1);
echo $stringResult;
Also, if a result is a null value posted, how can i set it so that it can be view in stringResult as '' ? I need to put it in my sql statement.
Thank you.
$query="INSERT INTO subscriber (RandomCode,Email,CreateDate,UpdateDate <?if ($num!=0) echo ','.$string; ?> ) VALUES (?,?,?,?,CURDATE(),'',<? if ($num!=0) echo ','.$stringResult; ?>)";
This is broken; you don't echo to add to a string, you need to concatenate it together. Here's how:
$query="INSERT INTO subscriber (RandomCode,Email,CreateDate,UpdateDate";
if ($num!=0)
{
$query .= ',' . $string;
}
$query .= ") VALUES (?,?,?,?,CURDATE(),'',"
if ($num!=0)
{
$query .= ','.$stringResult;
}
$query .= ")";
When you are guilding a string and need to stop and make a decision, like "is this zero? then do this, now continue on.", you need to end the string, concatenate a string into it if need be, and then concatenate the rest of the string onto the end. Continue ending the string and concatenating parts on until you are done.
If you are adding a null value to a string, it's the same as adding an empty string - ''.
$string "mystring" . NULL . "morestring"; //result is "mystringmorestring"
$string "mystring" . "" . "morestring"; //result is "mystringmorestring"
The resulting string is exactly the same. While NULL !== "" (meaning NULL and "" are not identical because they are not the same type), as far as the resulting string goes, it's the same.
The problem you have is that you're trying to open <?php ?> when you're already in PHP. The string will be output as-is to the mysql handler. What you'll want to do instead is simply set a variable and then just add the result into your string.
$firstAddition = ($num!=0) ? ','.$string : '';
$secondAddition = ($num!=0) ? ','.$stringResult : '';
And then, when you build your query, simply concatenate in those new variables.
You could use an inline ternary:
$str = 'abcd' . ($num != 0 ? ',' : '' ) . 'efg';
Otherwise, just break it up with if statements:
$query = "INSERT INTO subscriber (RandomCode, Email, CreateDate, UpdateDate ";
if ($num != 0) {
$query .= ', ' . $string;
}
$query .= ") VALUES (?, ?, ?, ?, CURDATE(), ''";
if ($num != 0) {
$query .= ', ' . $stringResult;
}
$query .= ")";
I'd put the conditional above the line where I set the query.
<?php
$extra='';
if ($num!=0) $extra= ','.$string;
$extra2='';
if ($num!=0) $extra=','.$stringResult;
$query="INSERT INTO subscriber (RandomCode,Email,CreateDate,UpdateDate '.$extra.' ) VALUES (?,?,?,?,CURDATE(),'','.$extra2.')";
?>
Completely untested. Be sure you sanitize $string and $stringResult.
Related
I got this code from google and it fulfills my requirement, but I don't understand the meaning of this line:
substr($query,0,strlen($query)-2)
Could somebody explain it to me?
<?php
function insert($tablename, $parameter_order, $values)
{
$query = "insert into $tablename (";
foreach($parameter_order as $po)
{
$query .= $po.', ';
}
$query = substr($query,0,strlen($query)-2).') values (';
foreach($values as $v)
{
$query .= "'$v', ";
}
$query = substr($query,0,strlen($query)-2).');';
return $this->makeQuery($query);
}
?>
This is what those functions do exactly:
substr() is used to generate a sub-string of specified length from another string.
strlen() will return the length of the provided string.
Code substr($query,0,strlen($query)-2) removes comma and space from foreach Loop.
The line removes the last comma and space from $query. These characters have been added in the foreach loop to glue together the elements of $parameter_order.
Note that this standard task is usually done better with the implode() function:
$query = "insert into $tablename (" . implode (', ', $parameter_order) . ' ) values (';
I'm using php to generate an oracle query like this:
...
$sql = sprintf("INSERT INTO $table_name %s %s ON DUPLICATE KEY UPDATE ",
$this->prepare_insert_sql("", $fields, false),
$this->prepare_insert_sql(" VALUES ", $values, true));
for ($index = 0; $index < count($fields); $index++) {
if ($index > 0) {
$sql .= ", ";
}
$sql .= $fields[$index] . "='" . $values[$index] . "'";
}
...
And the result query is:
INSERT INTO TBL_CONFIG(KEY,VALUE)
VALUES ('1_default_meter_type_for_device_type_1','822')
ON DUPLICATE KEY
UPDATE KEY='1_default_meter_type_for_device_type_1', VALUE='822'
It gives an ORA-00933 error.
I really can't seem to find the error. Any tip is appreciated.
Using merge instead of insert into worked.
MERGE INTO TBL_CONFIG USING DUAL ON (KEY ='1_default_meter_type_for_device_type_1')
WHEN MATCHED THEN UPDATE SET VALUE = '822'
WHEN NOT MATCHED THEN INSERT (KEY, VALUE) VALUES ('1_default_meter_type_for_device_type_1', '822')
Per your posted code KEY is a reserve word and so you need to escape it using "" double quote like below
INSERT INTO TBL_CONFIG("KEY",VALUE)
VALUES ('1_default_meter_type_for_device_type_1','822')
ON DUPLICATE KEY
UPDATE "KEY"='1_default_meter_type_for_device_type_1', VALUE='822'
EDIT:
Totally confused. Oracle doesn't have ON Dulicate Key Update. You have to use MERGE statement as commented by Fred-ii.
Try this:
$sql = sprintf(
"INSERT INTO $table_name %s %s ON DUPLICATE KEY UPDATE ",
$this->prepare_insert_sql("", $fields, false),
$this->prepare_insert_sql(" VALUES ", $values, true)
);
for($index = 0; $index < count($fields); $index++) {
if($index > 0) {
$sql .= ", ";
}
// added " before and after field name
$sql .= '"' . $fields[$index] . '"=\'' . $values[$index] . "'";
}
This question already has answers here:
How can I bind an array of strings with a mysqli prepared statement?
(7 answers)
Closed 6 months ago.
I have a string like this 'dubai,sharjah,' and I want to make it like this 'dubai','sharja',
I am passing the value dubai,sharjah, in the URL using ajax and my code
$city=$_GET['city'];
$sql = "SELECT * FROM filter where isdeleted = 0 ";
if ($city !="" && $city !="Empty" ){
$sql.=" and twon in ('".$citydata."')";
}
when I print the query, it's like this
SELECT * FROM filter where isdeleted = 0 and twon in ('dubai,sharjah,')
but I want it like this
SELECT * FROM filter where isdeleted = 0 and twon in ('dubai','sharja')
Can anyone guide me on how to do this using PHP?
Here's how I would approach it. I'm going to use PDO instead of mysqli because trying to get an array into mysqli_stmt::bind_param is just a pain.
First, create an array of cities, removing any empty values
$params = array_filter(explode(',', $city), function($c) {
return !empty($c) && $c !== 'Empty';
});
$paramCount = count($params);
$query = 'SELECT * FROM filter where isdeleted = 0';
Now generate a placeholder string for your prepared statement.
if ($paramCount) {
$placeholders = implode(',', array_fill(0, $paramCount, '?');
// looks something like '?,?'
$query .= " AND twon IN ($placeholders)";
}
Now, prepare a statement
// assuming you have a PDO instance in $pdo created with something like
// $pdo = new PDO('mysql:host=localhost;dbname=your_db;charset=utf8', 'username', 'password', [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
$stmt = $pdo->prepare($query);
Execute and fetch values :)
$stmt->execute($params);
$filters = $stmt->fetchAll(PDO::FETCH_ASSOC);
$cities = explode(",", $_GET['city']);
//escape!
foreach ($cities as $citykey => $city) {
$cities[$citykey] = "'" . mysql_real_escape_string($city) . "'";
}
$sql = "SELECT * FROM `filter` where `isdeleted` = 0";
if (!empty($cities)) {
$sql .= ' and `twon` in (' . implode(',', $cities) . ')';
}
An alternative is to use FIND_IN_SET(). No PHP code change needed.
$sql.=" and FIND_IN_SET(town, '".$citydata."')";
you can try to explode the string
$cityparts = explode(",",$city);
and you can use
$cityparts[0] and $cityparts[1] in your query
array explode ( string $delimiter , string $string [, int $limit ] )
you can find more information on [http://www.php.net/explode]
hope this helps!!
You just have to explode and implode here. Rest is the problem with extra , in your string at the end.
$str = "dubai,sharjah,";
$citydata = implode("','",explode(',',rtrim($str,',')));
echo "'$citydata'";
test
After 6 answers I gotta add a 7th:
$sql.=" and twon in ('".str_replace(",","','",$citydata)."')";
You can do this.
$string = 'dubai,sharjah';
$cities = explode(',', $string);
echo $cities[0]; //dubai
echo $cities[1]; //sharjah
try this
$str = "dubai,sharjah,";
$arr = explode(",", $str);
$arr_temp = array()
foreach($arr as $s)
{
if($s!="")
{
$arr_temp[] = "'".$s."'";
}
}
$new_str = implode(",", $arr_temp);
echo $new_str; // output 'dubai','sharjah'
Now your Sql will be
$sql = "SELECT * FROM filter where isdeleted = 0 and twon in ($new_str) ";
You can use it
in $city I fix two values with, you can use here by $_GET ;
$city = "dubai,sharjah,";
$query_string ="";
$words = explode(",",$city);
for($i=0;$i<count($words);$i++){$query_string .= "'".$words[$i]."',";}
$query_string = substr($query_string,0,strlen($query_string)-4);
then use your query
SELECT * FROM filter where isdeleted = 0 and twon in ($query_string)
if ($city !="" && $city !="Empty" )
{
$city_exp = explode(',' $city);
$sql .= " and twon in ('".implode("', '", $city_exp)."')";
}
What we are basically doing here is putting the two values in an array by using explode and then separating each item in that array by using implode
DEMO
I have a table "groupdentlink" where I want to delete all the rows that weren't checked in a form.
In essence I want to perform a query like:
DELETE * FROM groupdentlink
WHERE group_id = 'a'
AND dentist_id IS NOT IN ARRAY 'b'
I think I could set a variable with a foreach loop and then keep adding the array values to it so I end up with:
DELETE * FROM groupdentlink
WHERE group_id = 'a'
AND dentist_id != 'D1'
AND dentist_id != 'D5'
AND dentist_id != 'D8'
...and so on.
But is this really the right/best way to do this?
Thanks in advance!
DELETE FROM groupdentlink
WHERE group_id = 'a'
AND dentist_id NOT IN ('D1','D5','D8')
More info here http://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#function_not-in
If you want to execute this query from a Zend Framework driven application please take in consideration the followings :
$where = sprintf('dentist_id NOT IN ("%s")', implode('", "',array_map('mysql_escape_string', $array)));
$this->sqlMapper->delete($where);
If you try . operator for concatenation purposes the query will result in a fatal error because of the quotes. So from my experience using htmlspecialchars or htmlencode along with . operator will only consume your time and patience. The use of sprintf is elegant, helps you keep your code clean.
And I think these observations apply to any application that makes use of php objects.
New user to Stack Exchange, please forgive and instruct if I'm committing a faux pas.
The preceeding answer is incredibly dangerous, because it opens you up to SQL injection attacks.
Always use bind params.
Always use bind params.
Always use bind params.
Hint: if your query does not resemble "DELETE * FROM groupdentlink WHERE group_id = 'a' AND dentist_id IS NOT IN (?, ?, ?);" you are doing it wrong.
An elegant, fully parametrized solution (using PDO):
$dentistIds = ['D1', 'D5', 'D8'];
$query = sprintf(
"DELETE FROM online_order_shipping
WHERE group_id = 'a'
AND dentist_id NOT IN (%s)",
implode(',', array_fill(0, count($dentistIds), '?'))
);
$stmtDelete = $pdo->prepare($query);
$stmtDelete->execute($dentistIds);
The implode function strings ? together with , without adding a comma in the end (source). You could turn that into a function to make it more readable, otherwise the sprintf keeps it nice and tidy without ugly string concatenation.
I found the statement $str = rtrim($str, ",");
didnt remove the trailing comma giving rise to an
error
I came up with this work around:
// string without quotes
$str = array_shift($array);
// string with quotes
$str = "'" . array_shift($array) . "'";
foreach ($array as $item)
{
$str .= ", '" . $item . "'";
}
Here How I do it :
assuming you have an array called $csvstocknumbers = ['0','1'];
$stocknumbers = implode(",",$csvstocknumbers) ; // make the content of the array in one string seprated by ,
$deleteoldvehicles = "DELETE FROM table_name WHERE column_name NOT IN
($stocknumbers ) ;";
mysqli_query($con, $deleteoldvehicles);
You just need to join the ids with a comma:
$myarray = new array('D1', 'D5', 'D8');
$str = "";
foreach ($myarray as $item)
{
$str .= $item . ",";
}
$str = rtrim($str, ",");
$query = "DELETE * FROM groupdentlink
WHERE group_id = 'a'
AND dentist_id NOT IN ($str)";
This will give you a query like this:
DELETE * FROM groupdentlink
WHERE group_id = 'a'
AND dentist_id IS NOT IN (D1, D5, D8);
If you need the quotes around the ids, then change the loop like this:
foreach ($myarray as $item)
{
$str .= "'".$item . "',";
}
I have the following which produces results for me.
foreach($authArray as $key=>$value){
$query = mysql_query("SELECT * FROM table WHERE id='$value' LIMIT 1");
$author = mysql_fetch_assoc($query);
echo $author['fullname'] .', ';
}
It prints it out perfect, except on the last run it still adds the comma and space, is there a way i can strip this from the last result, so its:
name, name, name, name
Instead of the following
name, name, name, name,
Cheers
A better way of doing this would be to separate out the handling of database results from the view/output logic, and then you can sidestep the issue all together, using implode to allow PHP to join each of your authors together into a single string, split by your delimiter of a comma and a space:
// your loop {
$authors[] = $author['fullname'];
}
// your output
echo implode(', ', $authors);
Just concate the data into a string and then remove the last 2 chars using
$author['fullname'] = substr($author['fullname'], 0, -2);
Refer the manual for substr http://php.net/manual/en/function.substr.php
Instead of echoing each author out you could put them in a string and then simply use trim() to take off the trailing comma and finally echo the whole string.
this will probably work
foreach($authArray as $key=>$value){
$query = mysql_query("SELECT * FROM table WHERE id='$value' LIMIT 1");
$author = mysql_fetch_assoc($query);
//echo $author['fullname'] .', ';
}
$name_count = count($author[]);
for($x=0;$x<$name_count ;$x++){
if($x == $name_count -1){
echo $author['fullname'];
}else{
echo $author['fullname'].", ";
}
}
the idea is to detect the last array index, so that we can apply all the commas after each name except to the last one.
don't ever echo inside foreach
$var = '';
foreach($authArray as $key=>$value){
$query = mysql_query("SELECT * FROM table WHERE id='$value' LIMIT 1");
$author = mysql_fetch_assoc($query);
$var .= $author['fullname'] .', ';
}
echo trim($var,', ');