i apologize if the question is wrong. i am a still a newbie and a learner however i would appreciate if someone correct me if i am somewhere wrong.
here in the Class method i am using for Inserting the data into the database
public function insert($table,$col,$value)
{
if(is_array($col) && is_array($value))
{
$query = "INSERT INTO ".$table."(" . implode(",",$col) . ") VALUES(" . implode(",",$value) . ")";
}
else
{
$query = "INSERT INTO " . $table . "(" . $col . ") VALUES(". $value . ")";
}
}
now here i am determining if the $col and $value is an array if yes then process it.
however i have a problem here since the VALUES in the Insert statement needs to be represnted in the single or double quote format it will not process the query and hence print the error
for example the below code would print the error
$query = "INSERT INTO users(username,email) VALUES(test,test#test.com)";
and the correct format will be
$query = "INSERT INTO users(username,email) VALUES('test','test#test.com')";
now in the col value i would like to add the single quotes to every value in the array for example the $value array which is like this.
$value = array('test','test#test.com');
should give back the value
'test','test#test.com'
instead of
test,test#test.com
how do i achieve it?
$query = "INSERT INTO $table ('" . implode("','",$col) . "')
VALUES ('" . implode("','",$value) . "')";
Make sure that neither $col nor $value is empty.
Right code:
public function insert($table,$col,$value)
{
if(is_array($col) && is_array($value))
{
$query = "INSERT INTO ".$table."(" . implode(",",$col) . ") VALUES('" . implode("','",$value) . "')";
}
else
{
$query = "INSERT INTO " . $table . "(" . $col . ") VALUES('". $value . "')";
}
}
CHANGE:
VALUES(" . implode(",",$value) . ")
TO
VALUES('" . implode("','",$value) . "')
(Your output:)
VALUES(demo,demo2)
(New Output:)
VALUES('demo','demo2')
you could do this?
$value = array("'test'","'test#test.com'");
You can use array_map() method:
function addQuotes($str)
{
return "'".$str."'";
}
$value = array_map("addQuotes", $value);
or follow a Oswald's answer recommendations.
Related
Whenever I implement this code, I no longer get an error while using a single quote, but the hexstring get's written to the database instead of being converted back to the original characters.
function mssql_escape($data) {
if(is_numeric($data))
return $data;
$unpacked = unpack('H*hex', $data);
return '0x' . $unpacked['hex'];
}
mssql_query('
INSERT INTO sometable (somecolumn)
VALUES (' . mssql_escape($somevalue) . ')
');
This is what I'm trying to do. $suggestTest is the variable I'm using the escape function on.
$nomDept = $_POST['nomDept'];
$subSupervisor = $_POST['subSupervisor'];
$suggestion = $_POST['suggestion'];
$suggestTest = mssql_escape($suggestion);
if ($subSupervisor == "Yes") {
$query = "INSERT INTO dbo.emp_recog (nomDept, nomSuggestion, subSupervisor) VALUES (";
$query .= "'" . $nomDept . "', ";
$query .= "'" . $suggestTest . "', ";
$query .= "'" . $subSupervisor . "');";
$res = mssql_query($query);
}
I've also tried omitting the single quotes around the variable like so
if ($subSupervisor == "Yes") {
$query = "INSERT INTO dbo.emp_recog (nomDept, nomSuggestion, subSupervisor) VALUES (";
$query .= "'" . $nomDept . "', ";
$query .= $suggestTest ", ";
$query .= "'" . $subSupervisor . "');";
$res = mssql_query($query);
}
If you use prepare to build your SQL statement, you do not need to escape the variables.
I originally had this working:
url: http://server/blah.php?FacilityCode=FT
$facilitycode = mysql_real_escape_string($_GET["FacilityCode"]);
$sql = "SELECT ..." .
"FROM ..." .
"WHERE ..." .
"AND ('" . $facilitycode . "' = '' OR Facility.FacilityCode = '". $facilitycode . "')";
$result = mysql_query($sql);
But I want to change this so that people can submit multiple values in the query strying somehow, ie: http://server/blah.php?FacilityCode=FT,CC,DD,EE
I tried changing the query to an "IN" clause instead of an "equals" but I'm not sure how to get the ' marks around each element.
Use implode() function for IN (...).
$a = array('AB', 'CD', 'EF', 'ZE');
echo "field IN ('" . implode("', '", $a) . "')";
... will output:
field IN ('AB', 'CD', 'EF', 'ZE')
+escape every option you get.
$facilitycode = mysql_real_escape_string($_GET["FacilityCode"]);
$array=explode(',',$facilitycode);
foreach ($array as $a){$output.="'$a',";}
$clause=substr($output,0,-1);
If your trying to create a string which looks like this: 'AB', 'CD', 'EF', 'ZE'
Try this before its placed inside the query:
$facilitycode = preg_replace('/([^,]+)/', '\'$1\'', $facilitycode);
I wrote this based on your query, but still I dont get this part of query "AND ('" . $facilitycode . "' = ''", anyway you need to check if $_GET data have "," and if does explode that variable by "," so that you can add an OR clausule for everything that was separated by "," in $_GET data.
After that just form your query by doing a foreach for every element in exploded array like I done below:
<?php
$facilitycode = $_GET["FacilityCode"];
$facility_number_chk = strpos($facilitycode, ",");
if ($facility_number_chk > -1) {
$facilitycode = explode(",", $facilitycode);
$sql = "SELECT ..." .
"FROM ..." .
"WHERE ..." .
"AND ('" . $facilitycode . "' = ''";
foreach($facilitycode as $facode) {
$facode = mysql_real_escape_string($facode);
$sql .= " OR Facility.FacilityCode = '". $facode . "'";
}
$sql .= "')";
}
else {
$facilitycode = mysql_real_escape_string($facilitycode);
$sql = "SELECT ..." .
"FROM ..." .
"WHERE ..." .
"AND ('" . $facilitycode . "' = '' OR Facility.FacilityCode = '". $facilitycode . "')";
}
$result = mysql_query($sql);
And if there is only one element in $_GET data just do an else like I done with your regular query.
I ended up using a combination of a few of the answers. Basically I exploded on the ",", then did a foreach to add the ' marks and call escape_string, and then imploded it back.
$facilitycodes = $_GET["FacilityCode"];
if ($facilitycodes == '') {
$additionalfilter = '';
}
else {
$facilitycodearray = explode(",", $facilitycodes);
foreach($facilitycodearray as &$facilitycode) {
$facilitycode = "'" . mysql_real_escape_string($facilitycode) . "'";
}
$facilitycodesformatted = implode(",", $facilitycodearray);
$additionalfilter = " AND Facility.FacilityCode IN (" . $facilitycodesformatted . ")";
}
$sql = "SELECT ..." .
"FROM ..." .
"WHERE ..." .
$additionalfilter;
I have the following php array that gets all values from a form full of radios and check-boxes.
foreach(array('buss_type','anotherfield','anotherfield','...etc') as $index)
{
if (isset($this->request->post[$index])) {
$this->data[$index] = $this->request->post[$index];
} else {
$this->data[$index] = NULL;
}
}
Now, I am wondering how to write the query to send those values to my database, to a new table I just created (retailer). Every radio/checkform value has its column in my retailer table, how do I write the query so that all the values contained in $index go to their specific column.
The following is an example of how my other queries look like...
public function addCustomer($data) {
//this is the one I am trying to write, and this one works,
//but I'd have to add every single checkbox/radio name to the
//query, and I have 30!
$this->db->query("INSERT INTO " . DB_PREFIX . "retailer SET buss_t = '" .
(isset($data['buss_t']) ? (int)$data['buss_t'] : 0) .
"', store_sft = '" .
(isset($data['store_sft']) ? (int)$data['store_sft'] : 0) .
"'");
//Ends Here
$this->db->query("INSERT INTO " . DB_PREFIX . "customer SET store_id = '" .
(int)$this->config->get('config_store_id') . "', firstname = '" .
$this->db->escape($data['firstname']) . "', lastname = '" .
$this->db->escape($data['lastname']) . "', email = '" .
$this->db->escape($data['email']) . "', telephone = '" .
$this->db->escape($data['telephone']) . "', fax = '" .
$this->db->escape($data['fax']) . "', password = '" .
$this->db->escape(md5($data['password'])) . "', newsletter = '" .
(isset($data['newsletter']) ? (int)$data['newsletter'] : 0) .
"', customer_group_id = '" .
(int)$this->config->get('config_customer_group_id') .
"', status = '1', date_added = NOW()");
Thanks a lot for any insight you can provide.
the best way would be to create a function that accepts an array and table name as an argument and executes a insert query.
function insertArray($table, $array)
{
$keys =""; $values = "";
foreach($table as $k=>$v)
{
$keys.=($keys != "" ? ",":"").$k:
$values .=($values != "" ? "," :"")."'".$v."'";
}
$this->db->query("INSERT INTO ".$table." (".$keys.") VALUES (".$values.");
}
The array has to be structured like this:
array("db_attribute1"=>"value1","db_attribute2"=>"value2");
Store the column names and column values in separate arrays and use implode() to generate a comma-separated list of columns and values
$values = array();
$columns = array('buss_type','anotherfield','anotherfield','...etc');
foreach($columns as $index)
{
if (isset($this->request->post[$index]))
{
$this->data[$index] = $this->request->post[$index];
$values[] = $this->db->escape($this->request->post[$index]);
}
else
{
$this->data[$index] = NULL;
$values[] = "''";
}
}
$this->db->query("INSERT INTO table_name (" . implode(",", $columns) . ") VALUES (" . implode(",", $values) . ");
this function is create sql query with array
function YorumEkle($kitapid,$array)
{
$sql = "INSERT INTO yorumlar ('" . implode(",",array_keys($array)) . "') VALUES ( '" . implode("','",$array) . "' )";
}
But i want to use mysql_real_escape_string() but how?
You can use array_map function
function YorumEkle($kitapid,$array)
{
$array2 = array_map("mysql_real_escape_string",$array);
$sql = "INSERT INTO yorumlar ('" . implode("','",array_keys($array2)) . "') VALUES ( '" . implode("','",$array2) . "' )";
}
Change the implode("','",$array) to implode("','", array_map('mysql_real_escape_string', $array)). The array_map function allows you to apply a callback to each value of an array, in this case mysql_real_escape_string.
Example:
function YorumEkle($kitapid,$array)
{
$sql = "INSERT INTO yorumlar (" . implode(",", array_map('mysql_real_escape_string',array_keys($array))) . ") VALUES ( '" . implode("','", array_map('mysql_real_escape_string', $array)) . "' )";
}
Try:
$sql = "INSERT INTO yorumlar (" . implode(",",array_map('mysql_real_escape_string', array_keys($array))) . ") VALUES ( '" . implode("','",array_map('mysql_real_escape_string', $array)) . "' )";
I am trying to loop through a number of results from a form, but can't get it quite right.
for ($i=1;$i<$total;i++)
{
mysql_query("INSERT INTO MYSQL(value1,value2,value3) VALUES('{$i}','{$_POST['$iH']}', '{$_POST['$iA']}'");
}
I want $_POST['$iH'] to be the same as $_POST['1H'],$_POST['2H'], $_POST['3H'] etc.
Like so:
for ($i = 1; $i < $total; $i++) { // <--- You had a typo here
$sql = "INSERT INTO MYSQL(value1,value2,value3) ";
$sql .= "VALUES('{$i}','" . $_POST[$i . 'H'] . "', '" . $_POST[$i . 'A'] . "')";
mysql_query($sql);
}
But, two big problems.
Multiple queries
Boy, what a waste! Dispatch one instead:
$rows = Array();
for ($i = 1; $i < $total; $i++) {
$rows[] = "('{$i}','" . $_POST[$i . 'H'] . "', '" . $_POST[$i . 'A'] . "')";
}
$sql = "INSERT INTO MYSQL(value1,value2,value3) VALUES('" . implode("','", $rows) . "')";
mysql_query($sql);
SQL injection
It continues to baffle me how, in 2011, people are still not getting this.
If you're going to insist upon using the ancient mysql API (not even the OO version?!) rather than PDO, get into the habit of sanitising your inputs:
$rows = Array();
for ($i = 1; $i < $total; $i++) {
$rows[] = "('{$i}'," .
"'" . mysql_escape_string($_POST[$i . 'H']) . "'," .
"'" . mysql_escape_string($_POST[$i . 'A']) . "')";
}
$sql = "INSERT INTO MYSQL(value1,value2,value3) VALUES('" . implode("','", $rows) . "')";
mysql_query($sql);
OK, so without multi-query support in your API it's unlikely to cause you significant grief here, but it can do in authentication routines. Just get used to scripting properly in this regard.
You really need to escape your post variables with mysql_real_escape_string()... you are seriously looking for trouble like that.
In answer to your question, I think you need to do something like this:
mysql_query("INSERT INTO MYSQL(value1,value2,value3) VALUES('{$i}', '" . $_POST[$i . 'H'] . "', '" . $_POST[$i.'A']. "'");
with the letters rubbing up against your variable, the php engine will assume they are part of the variable name; that variable name does not exist, so you will get some strange results.
You need to escape your quotes because your variable is being passed as a literal:
for ($i=1; $i<$total; $i++)
{
mysql_query('INSERT INTO MYSQL(value1,value2,value3) VALUES("' . $i . '","' . $_POST[$i . 'H'] . '", "' . $_POST[$i . 'A'] . '")');
}