I'm trying to insert the data in a MYSQL database but it seems that my query is not working i've tried all other methods but nothing is working for me ,Here is the PHP that i'm using
<?php
$server="localhost";
$database="hospital";
$login="root";
$password="";
$connexion=mysql_connect ($server, $login, $password) or die ('Server cannot be found'.mysql_error ( ));
mysql_select_db ($database,$connexion)or die ('database cannot be found'.mysql_error( ));
$a= mysql_real_escape_string($_POST['doctorname']);
$b = mysql_real_escape_string($_POST['writtendate']);
$c = mysql_real_escape_string($_POST['hospitalname']);
$d = mysql_real_escape_string($_POST['patientname']);
$e = mysql_real_escape_string($_POST['dateofbirth']);
$f= mysql_real_escape_string($_POST['cardnumber']);
$g = mysql_real_escape_string($_POST['groupname']);
$h = mysql_real_escape_string($_POST['drug1']);
$i = mysql_real_escape_string($_POST['drug2']);
$j = mysql_real_escape_string($_POST['drug3']);
$k = mysql_real_escape_string($_POST['drug4']);
$l = mysql_real_escape_string($_POST['amount1']);
$m = mysql_real_escape_string($_POST['amount2']);
$n = mysql_real_escape_string($_POST['amount3']);
$f = mysql_real_escape_string($_POST['principalmembersname']);
if(#$_POST['submit'])
{
$query="insert into uap(doctorname,writtendate,hospitalname,patientname,dateofbirth,cardnumber,groupname,principalmembersname,drug1,drug2,drug3,drug4,amount1,amount2,amount3) values ('$_POST[doctorname]','$_POST[writtendate]','$_POST[hospitalname]','$_POST[patientname]','$_POST[dateofbirth]','$_POST[cardnumber]','$_POST[groupname]','$_POST[principalmembersname]','$_POST[drug1]','$_POST[drug2]','$_POST[drug3]','$_POST[drug4]','$_POST[amount1]','$_POST[amount2]','$_POST[amount3]')";
$answer=mysql_db_query ($database, $query);
}
mysql_close ($connexion);
?>
To get you on the right track on using PDO and prepared statements (with named placeholders in this case):
<?php
$pdo = new PDO('mysql:host=localhost;dbname=databasename', 'username', 'password');
$statement = $pdo->prepare("INSERT INTO `uap` (`doctorname`,`writtendate`,`hospitalname`,`patientname`,`dateofbirth`,`cardnumber`,`groupname`,`principalmembersname`,`drug1`,`drug2`,`drug3`,`drug4`,`amount1`,`amount2`,`amount3`) VALUES (:doctorname, :writtendate, :hospitalname, :patientname, :dateofbirth, :cardnumber, :groupname, :principalmembersname, :drug1, :drug2, :drug3, :drug4, :amount1, :amount2, :amount3)");
$result = $statement->execute(
array(
'doctorname' => $_POST['doctorname'],
'writtendate' => $_POST['writtendate'],
'hospitalname' => $_POST['hospitalname'],
'patientname' => $_POST['patientname'],
'dateofbirth' => $_POST['dateofbirth'],
'cardnumber' => $_POST['cardnumber'],
'groupname' => $_POST['groupname'],
'principalmembersname' => $_POST['principalmembersname'],
'drug1' => $_POST['drug1'],
'drug2' => $_POST['drug2'],
'drug3' => $_POST['drug3'],
'drug4' => $_POST['drug4'],
'amount1' => $_POST['amount1'],
'amount2' => $_POST['amount2'],
'amount3' => $_POST['amount3']
)
);
if (!$result)
{
echo "SQL Error <br/>";
echo $statement->queryString."<br/>";
echo $statement->errorInfo()[2];
}
Although I still think your schema could use some optimization (eg. a dedicated drug table with a many-to-many relation to patients or whatever this is)
The problem with the code that you have above mainly lies in string concatenation. In your $query variable you have two primary issues:
First you have combined array syntax within a quoted string:
$query = "insert into uap (...) values ('$_POST[doctorname]')"
Second the when you reference arrays like $_POST[doctorname] (without the quotes around the keys) PHP assumes that the unquoted string is a constant that contains the same value as its name. That makes this seem like proper code, but it is actually very, VERY messy.
The PHP interpreter cannot understand exactly what you are trying to do in this case and ends up stopping concatenation at the $_POST variable. So your resultant string probably looks something like this: insert into uap (...) values ('array[doctorname]'). You can correct this by using braces to tell the PHP interpreter to use the whole array syntax in the string:
$query = "insert into uap (...) values ('{$_POST['doctorname']}')" or by using the concatenation . operator to perform proper string concatenation: $query = 'insert into uap (...) values ('".$_POST['doctorname']."')".
You simplest solution however, is to use the variables that you had specified above in your code. You final $query variable should look something like this (which will also use the `mysql_escape_string() function that you used above):
<?php
$server="localhost";
$database="hospital";
$login="root";
$password="";
$connexion=mysql_connect ($server, $login, $password) or die ('Server cannot be found'.mysql_error ( ));
mysql_select_db ($database,$connexion)or die ('database cannot be found'.mysql_error( ));
$doctorname = mysql_real_escape_string($_POST['doctorname']);
$writtendate = mysql_real_escape_string($_POST['writtendate']);
$hospitalname = mysql_real_escape_string($_POST['hospitalname']);
$patientname = mysql_real_escape_string($_POST['patientname']);
$datofbirth = mysql_real_escape_string($_POST['dateofbirth']);
$cardnumber = mysql_real_escape_string($_POST['cardnumber']);
$groupname = mysql_real_escape_string($_POST['groupname']);
$drug1 = mysql_real_escape_string($_POST['drug1']);
$drug2 = mysql_real_escape_string($_POST['drug2']);
$drug3 = mysql_real_escape_string($_POST['drug3']);
$drug4 = mysql_real_escape_string($_POST['drug4']);
$amount1 = mysql_real_escape_string($_POST['amount1']);
$amount2 = mysql_real_escape_string($_POST['amount2']);
$amount3 = mysql_real_escape_string($_POST['amount3']);
$principlemembersname = mysql_real_escape_string($_POST['principalmembersname']);
if(#$_POST['submit'])
{
$query = "insert into uap(doctorname,writtendate,hospitalname,patientname,dateofbirth,cardnumber,groupname,principalmembersname,drug1,drug2,drug3,drug4,amount1,amount2,amount3)
values ('$doctorname','$writtendate','$hospitalname','$patientname','$datofbirth','$cardnumber','$groupname','$principlemembersname','$drug1','$drug2','$drug3','$drug4','$amount1','$amount2','$amount3')";
$answer=mysql_db_query ($database, $query);
}
mysql_close ($connexion);
?>
As noted by other users it would be a good idea to convert this code to use PDO and prepared statements as the mysql functions in PHP are deprecated.
Good luck! I hope this helps!
Related
This question already has answers here:
How to insert multiple rows using prepared statements
(1 answer)
Best way to INSERT many values in mysqli?
(4 answers)
Closed 4 months ago.
I know this has been asked so many times but I can't seem to figure the issue out. Im running the following code, but it just returns the fail. When I run the output of
$query1 --> INSERT INTO number (count,code,prize,printed) VALUES ('1','Q0stZr0g8uc4syE','','0');
straight into phpmyadmin it inserts fine. I must be doing something stupid... Any ideas?
$times_to_run = 100;
$prize='';
for($i=1;$i<=$times_to_run;$i++){
$array[] = array(
'count' => $i,
'code1' => randomString(),
'prize' => $prize
);
}
$codes = $array;
foreach ($codes as $code){
$query1 = "INSERT INTO number (count,code,prize,printed) VALUES ('". $code['count']."','". $code['code1']."','". $code['prize']."','0');";
$q = mysqli_query($query1) or die (mysql_error());
}
EDIT: I changed the query to use mysqli and got the full error which is:
the actual error is:
Warning: mysqli_query() expects at least 2 parameters, 1 given and the line it points to is: $q = mysqli_query($query1) or die (mysql_error());
** If I change
'". $code['prize']."'
to '0' I still get the same error.
To make things clear, here is the corrected version of your code:
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
$times_to_run = 100;
$prize='';
for($i=1;$i<=$times_to_run;$i++){
$array[] = array(
'count' => $i,
'code1' => randomString(),
'prize' => $prize
);
}
$codes = $array;
foreach ($codes as $code){
$query1 = "INSERT INTO number (count,code,prize,printed) VALUES ('". $code['count']."','". $code['code1']."','". $code['prize']."','0')";
$q = mysqli_query($link, $query1) or die (mysqli_error($link));
}
I might be wrong here but I think there are spaces needed after ] and after that .
Like this:
'" . $code['count'] . "'
instead of
'". $code['count']."'
Oh and just something that might be handy and good to know, mysql_query is deprecated and unsafe, unles you are using it for yourself at a local host I would suggest you take a look at mysqli_, which works basicly the same.
http://php.net/manual/en/function.mysql-query.php
I have a PHP script to post the following data to add-rma-process.php after submission:
$_POST['rmanumber']
$_POST['parent']
$_POST['qty']
However, there are also other fields which are to be posted but will depend on the $_POST['qty'] variable. Say, the $_POST['qty'] = 5 then I will have $_POST['pn1'], $_POST['sn1'], $_POST['rm1'] up to $_POST['pn5'], $_POST['sn5'], $_POST['rm5']. I think you guys get the logic.
Once add-rma-process.php receives these data, I am doing this:
require("common.php");
for($i=0; $i<$_POST['qty']; $i++) {
$count = $i+1; // to start with 1 instead of 0
$query = "INSERT INTO rmadb (rmanumber, parent, childpn, childsn, remarks, user, date) VALUES (:rmanumber, :parent, :childpn, :childsn, :remarks, :user, NOW())";
$query_params = array(
":rmanumber" => $_POST['rmanumber'],
":parent" => $_POST['parent'],
":childpn" => $_POST['pn$count'],
":childsn" => $_POST['sn$count'],
":remarks" => $_POST['rm$count'],
":user" => $_SESSION['user']['fname']." ".$_SESSION['user']['lname']
);
try {
$stmt = $db->prepare($query);
$res = $stmt->execute($query_params);
} catch(PDOException $ex) {
die("Failed to run query: " . $ex->getMessage());
}
}
What I was trying to do is do a for loop to execute the query until the condition is met but it is not working. What seems to be wrong?
You should use double quotes here so that key can be evaluated
$_POST["pn$count"]
^ ^
You don't need to introduce $count variable. Change condition in for
You should prepare your query once and then execute it multiple times with different parameters. That's the whole point behind prepared statements. Preventing sql injections is just a beautiful side effect.
That being said your might look something like this
require("common.php");
$query = "INSERT INTO rmadb (rmanumber, parent, childpn, childsn, remarks, user, date) VALUES (:rmanumber, :parent, :childpn, :childsn, :remarks, :user, NOW())";
$stmt = $db->prepare($query);
for ($i = 1; $i <= $_POST['qty']; $i++) {
$query_params = array(
":rmanumber" => $_POST['rmanumber'],
":parent" => $_POST['parent'],
":childpn" => $_POST["pn$i"],
":childsn" => $_POST["sn$i"],
":remarks" => $_POST["rm$i"],
":user" => $_SESSION['user']['fname']." ".$_SESSION['user']['lname']
);
$res = $stmt->execute($query_params);
}
Anytime you see yourself naming inputs like rm1, rm2, etc. know that that this is a clear anti-pattern. You should be using array access notation for your input names like:
<input name="rm[]" ... />
PHP will automatically take all inputs with same name and compile into an array that is available in $_POST - so $POST['rm'] and so forth.
This would simplify you loop to something like
$count = $_POST['qty']; // not shown you probably want to validate this value before using it
for ($i = 0; $i < $count; $i++) {
$query_params = array(
":rmanumber" => $_POST['rmanumber'],
":parent" => $_POST['parent'],
":childpn" => $_POST['pn'][$i],
":childsn" => $_POST['sn'][$i],
":remarks" => $_POST['rm'][$i],
":user" => $_SESSION['user']['fname']." ".$_SESSION['user']['lname']
);
$res = $stmt->execute($query_params);
}
Note that since I am guessing you are using some kind of javascript in your form to create X number of input fields based on the value in qty, this saves you a lot of headache in javascript in trying to number each input field. You can easily just clone the same input field (or template for the input field) and insert it into the DOM X times without the need to individually change it's one's name property.
I have an array like this
$a = array( 'phone' => 111111111, 'image' => "sadasdasd43eadasdad" );
When I do a var-dump I get this ->
{ ["phone"]=> int(111111111) ["image"]=> string(19) "sadasdasd43eadasdad" }
Now I am trying to add this to the DB using the IN statement -
$q = $DBH->prepare("INSERT INTO user :column_string VALUES :value_string");
$q->bindParam(':column_string',implode(',',array_keys($a)));
$q->bindParam(':value_string',implode(',',array_values($a)));
$q->execute();
The problem I am having is that implode return a string. But the 'phone' column is an integer in the database and also the array is storing it as an integer. Hence I am getting the SQL error as my final query look like this --
INSERT INTO user 'phone,image' values '111111111,sadasdasd43eadasdad';
Which is a wrong query. Is there any way around it.
My column names are dynamic based what the user wants to insert. So I cannot use the placeholders like :phone and :image as I may not always get a values for those two columns. Please let me know if there is a way around this. otherwise I will have to define multiple functions each type of update.
Thanks.
Last time I checked, it was not possible to prepare a statement where the affected columns were unknown at preparation time - but that thing seems to work - maybe your database system is more forgiving than those I am using (mainly postgres)
What is clearly wrong is the implode() statement, as each variable should be handled by it self, you also need parenthesis around the field list in the insert statement.
To insert user defined fields, I think you have to do something like this (at least that how I do it);
$fields=array_keys($a); // here you have to trust your field names!
$values=array_values($a);
$fieldlist=implode(',',$fields);
$qs=str_repeat("?,",count($fields)-1);
$sql="insert into user($fieldlist) values(${qs}?)";
$q=$DBH->prepare($sql);
$q->execute($values);
If you cannot trust the field names in $a, you have to do something like
foreach($a as $f=>$v){
if(validfield($f)){
$fields[]=$f;
$values[]=$v;
}
}
Where validfields is a function that you write that tests each fieldname and checks if it is valid (quick and dirty by making an associative array $valfields=array('name'=>1,'email'=>1, 'phone'=>1 ... and then checking for the value of $valfields[$f], or (as I would prefer) by fetching the field names from the server)
SQL query parameters can be used only where you would otherwise put a literal value.
So if you could see yourself putting a quoted string literal, date literal, or numeric literal in that position in the query, you can use a parameter.
You can't use a parameter for a column name, a table name, a lists of values, an SQL keyword, or any other expressions or syntax.
For those cases, you still have to interpolate content into the SQL string, so you have some risk of SQL injection. The way to protect against that is with whitelisting the column names, and rejecting any input that doesn't match the whitelist.
Because all other answers allow SQL injection. For user input you need to filter for allowed field names:
// change this
$fields = array('email', 'name', 'whatever');
$fieldlist = implode(',', $fields);
$values = array_values(array_intersect_key($_POST, array_flip($fields)));
$qs = str_repeat("?,",count($fields)-1) . '?';
$q = $db->prepare("INSERT INTO events ($fieldlist) values($qs)");
$q->execute($values);
I appreciated MortenSickel's answer, but I wanted to use named parameters to be on the safe side:
$keys = array_keys($a);
$sql = "INSERT INTO user (".implode(", ",$keys).") \n";
$sql .= "VALUES ( :".implode(", :",$keys).")";
$q = $this->dbConnection->prepare($sql);
return $q->execute($a);
You actually can have the :phone and :image fields bound with null values in advance. The structure of the table is fixed anyway and you probably should got that way.
But the answer to your question might look like this:
$keys = ':' . implode(', :', array_keys($array));
$values = str_repeat('?, ', count($array)-1) . '?';
$i = 1;
$q = $DBH->prepare("INSERT INTO user ($keys) VALUES ($values)");
foreach($array as $value)
$q->bindParam($i++, $value, PDO::PARAM_STR, mb_strlen($value));
I know this question has be answered a long time ago, but I found it today and have a little contribution in addition to the answer of #MortenSickel.
The class below will allow you to insert or update an associative array to your database table. For more information about MySQL PDO please visit: http://php.net/manual/en/book.pdo.php
<?php
class dbConnection
{
protected $dbConnection;
function __construct($dbSettings) {
$this->openDatabase($dbSettings);
}
function openDatabase($dbSettings) {
$dsn = 'mysql:host='.$dbSettings['host'].';dbname='.$dbSettings['name'];
$this->dbConnection = new PDO($dsn, $dbSettings['username'], $dbSettings['password']);
$this->dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
function insertArray($table, $array) {
$fields=array_keys($array);
$values=array_values($array);
$fieldlist=implode(',', $fields);
$qs=str_repeat("?,",count($fields)-1);
$sql="INSERT INTO `".$table."` (".$fieldlist.") VALUES (${qs}?)";
$q = $this->dbConnection->prepare($sql);
return $q->execute($values);
}
function updateArray($table, $id, $array) {
$fields=array_keys($array);
$values=array_values($array);
$fieldlist=implode(',', $fields);
$qs=str_repeat("?,",count($fields)-1);
$firstfield = true;
$sql = "UPDATE `".$table."` SET";
for ($i = 0; $i < count($fields); $i++) {
if(!$firstfield) {
$sql .= ", ";
}
$sql .= " ".$fields[$i]."=?";
$firstfield = false;
}
$sql .= " WHERE `id` =?";
$sth = $this->dbConnection->prepare($sql);
$values[] = $id;
return $sth->execute($values);
}
}
?>
dbConnection class usage:
<?php
$dbSettings['host'] = 'localhost';
$dbSettings['name'] = 'databasename';
$dbSettings['username'] = 'username';
$dbSettings['password'] = 'password';
$dbh = new dbConnection( $dbSettings );
$a = array( 'phone' => 111111111, 'image' => "sadasdasd43eadasdad" );
$dbh->insertArray('user', $a);
// This will asume your table has a 'id' column, id: 1 will be updated in the example below:
$dbh->updateArray('user', 1, $a);
?>
public function insert($data = [] , $table = ''){
$keys = array_keys($data);
$fields = implode(',',$keys);
$pre_fields = ':'.implode(', :',$keys);
$query = parent::prepare("INSERT INTO $table($fields) VALUES($pre_fields) ");
return $query->execute($data);
}
Hay All,
I cant seem to get my head around this dispite the number to examples i read. Basically I have a 2d array and want to insert it into MySQL. The array contains a few strings.
I cant get the following to work...
$value = addslashes(serialize($temp3));//temp3 is my 2d array, do i need to use keys? (i am not at the moment)
$query = "INSERT INTO table sip (id,keyword,data,flags) VALUES(\"$value\")";
mysql_query($query) or die("Failed Query");
Thanks Guys,
Not sure it's be a full answer to your question, but here at least a couple of possible problems :
You should not use addslashes ; instead, use mysql_real_escape_string
It knows about the things that are specific to your database engine.
In your SQL query, you should not use double-quotes (") arround string-values, but single-quotes (')
In your SQL query, you should have as many fields in the values() section as you have in the list of fields :
Here, you have 4 fields : id,keyword,data,flags
but only one value : VALUES(\"$value\")
You should use mysql_error() to know what was the precise error you've gotten while executing the SQL query
This will help you find out the problems in your queries ;-)
<?php
// let's assume we have a 2D array like this:
$temp3 = array(
array(
'some keywords',
'sme data',
'some flags',
),
array(
'some keywords',
'sme data',
'some flags',
),
array(
//...
),
);
// let's generate an appropriate string for insertion query
$aValues = array();
foreach ($temp3 as $aRow) {
$aValues[] = "'" . implode("','", $aRow) . "'";
}
$sValues = "(" . implode("), (", $aValues) . ")";
// Now the $sValues should be something like this
$sValues = "('some keywords','some data', 'someflags'), ('some keywords','some data', 'someflags'), (...)";
// Now let's INSERT it.
$sQuery = "insert into `my_table` (`keywords`, `data`, `flags`) values $sValues";
mysql_query($sQuery);
As an addition to the useful answers already given, if you have a big table that you need to insert it might not fit in one SQL statement. However, making a separate transaction for each row is also slow. In that case, we can tell MySQL to process multiple statements in one transaction, which will speed up the insertion greatly for big tables (>1000 rows).
An example:
<?php
function dologin() {
$db_username = 'root';
$db_password = 'root';
$db_hostname = 'localhost';
$db_database = 'logex_test';
mysql_connect($db_hostname, $db_username, $db_password);
mysql_select_db($db_database);
}
function doquery($query) {
if (!mysql_query($query)) {
echo $query.'<br><br>';
die(mysql_error());
}
}
function docreate() {
doquery("drop table if exists mytable");
doquery("create table mytable(column1 integer, column2 integer, column3 integer)");
}
function main() {
$temp3 = array(
array('1','2','3',),
array('4','5','6',),
array('7','8','9',),
);
dologin();
docreate();
doquery("start transaction");
foreach($temp3 as $row)
doquery("insert into mytable values('" . implode("','", $row) . "')");
doquery("commit") or die(mysql_error());
}
main();
?>
Try this :
// lets array
$data_array = array(
array('id'=>1,'name'=>'a'),
array('id'=>2,'name'=>'b'),
array('id'=>3,'name'=>'c'),
array('id'=>4,'name'=>'d'),
array('id'=>5,'name'=>'e')
)
;
$temp_array = array_map('implode', $data_array, array('","' ,'","','","','","','","'));
echo $query = 'insert into TABLENAME (COL1, COL2) values( ("'.implode('"),("', $temp_array).'") )';
mysql_query($query);
Is there a function in PHP that adds quotes to a string?
like "'".str."'"
This is for a sql query with varchars. I searched a little, without result...
I do the following:
$id = "NULL";
$company_name = $_POST['company_name'];
$country = $_POST['country'];
$chat_language = $_POST['chat_language'];
$contact_firstname = $_POST['contact_firstname'];
$contact_lastname = $_POST['contact_lastname'];
$email = $_POST['email'];
$tel_fix = $_POST['tel_fix'];
$tel_mob = $_POST['tel_mob'];
$address = $_POST['address'];
$rating = $_POST['rating'];
$company_name = "'".mysql_real_escape_string(stripslashes($company_name))."'";
$country = "'".mysql_real_escape_string(stripslashes($country))."'";
$chat_language = "'".mysql_real_escape_string(stripslashes($chat_language))."'";
$contact_firstname = "'".mysql_real_escape_string(stripslashes($contact_firstname))."'";
$contact_lastname = "'".mysql_real_escape_string(stripslashes($contact_lastname))."'";
$email = "'".mysql_real_escape_string(stripslashes($email))."'";
$tel_fix = "'".mysql_real_escape_string(stripslashes($tel_fix))."'";
$tel_mob = "'".mysql_real_escape_string(stripslashes($tel_mob))."'";
$address = "'".mysql_real_escape_string(stripslashes($address))."'";
$rating = mysql_real_escape_string(stripslashes($rating));
$array = array($id, $company_name, $country, $chat_language, $contact_firstname,
$contact_lastname, $email, $tel_fix, $tel_mob, $address, $rating);
$values = implode(", ", $array);
$query = "insert into COMPANIES values(".$values.");";
Rather than inserting the value directly into the query, use prepared statements and parameters, which aren't vulnerable to SQL injection.
$query = $db->prepare('SELECT name,location FROM events WHERE date >= ?');
$query->execute(array($startDate));
$insertContact = $db->prepare('INSERT INTO companies (company_name, country, ...) VALUES (?, ?, ...)');
$insertContact->execute(array('SMERSH', 'USSR', ...));
Creating a PDO object (which also connects to the DB and is thus a counterpart to mysql_connect) is simple:
$db = new PDO('mysql:host=localhost;dbname=db', 'user', 'passwd');
You shouldn't scatter this in every script where you want a DB connection. For one thing, it's more of a security risk. For another, your code will be more susceptible to typos. The solution addresses both issues: create a function or method that sets up the DB connection. For example:
function localDBconnect($dbName='...') {
static $db = array();
if (is_null($db[$dbName])) {
$db[$dbName] = new PDO("mysql:host=localhost;dbname=$dbName", 'user', 'passwd');
$db[$dbName]->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
return $db[$dbName];
}
If you're working with an array of more than two or three elements, you should use loops or array functions rather than a long sequence of similar statements, as is done in the sample code. For example, most of your sample can be replaced with:
$array = array();
foreach ($_POST as $key => $val) {
$array[$key] = "'" . mysql_real_escape_string(stripslashes($val)) . "'";
}
Here's a more comprehensive example of creating an insert query. It's far from production ready, but it illustrates the basics.
$db = localDBconnect();
// map input fields to table fields
$fields = array(
'company' => 'company_name',
'country' => 'country',
'lang' => 'chat_language',
'fname' => 'contact_firstname',
'lname' => 'contact_lastname',
'email' => 'email',
'land' => 'tel_fix',
'mobile' => 'tel_mob',
'addr' => 'address',
'rating' => 'rating',
);
if ($missing = array_diff_key($fields, $_POST)) {
// Form is missing some fields, or request doesn't come from the form.
...
} else {
$registration = array_intersect_key($_POST, $fields);
$stmt = 'INSERT INTO `dbname`.`Companies` (`'
. implode('`, `', $fields) . '`) VALUES ('
. implode(', ', array_fill(0, count($registration), '?')) . ')';
try {
$query = $db->prepare($stmt);
$query->execute(array_values($registration));
} catch (PDOException $exc) {
// log an
error_log($exc);
echo "An error occurred. It's been logged, and we'll look into it.";
}
}
To make it production ready, the code should be refactored into functions or classes that hide everything database related from the rest of the code; this is called a "data access layer". The use of $fields shows one way of writing code that will work for arbitrary table structures. Look up "Model-View-Controller" architectures for more information. Also, validation should be performed.
Firstly, I see you're using stripslashes(). That implies you have magic quotes on. I would suggest turning that off.
What you might want to do is put some of this in a function:
function post($name, $string = true) {
$ret = mysql_real_escape_string(stripslashes($_POST[$name]));
return $string ? "'" . $ret . "'" : $ret;
}
and then:
$company_name = post('company_name');
All this does however is reduce the amount of boilerplate you have slightly.
Some have suggested using PDO or mysqli for this just so you can use prepared statements. While they can be useful it's certainly not necessary. You're escaping the fields so claims of vulnerability to SQL injection (at least in the case of this code) are misguided.
Lastly, I wouldn't construct a query this way. For one thing it's relying on columns in the companies table being of a particular type and order. It's far better to be explicit about this. I usually do this:
$name = mysql_real_escape_string($_POST['name']);
// etc
$sql = <<<END
INSERT INTO companies
(name, country, chat_language)
VALUES
($name, $country, $language)
END;
That will sufficient for the task. You can of course investigate using either mysqli or PDO but it's not necessary.
Thought I'd contribute an option that answers the question of "Is there a function in PHP that adds quotes to a string?" - yes, you can use str_pad(), although it's probably easier to do it manually.
Benefits of doing it with this function are that you could also pass a character to wrap around the variable natively within PHP:
function str_wrap($string = '', $char = '"')
{
return str_pad($string, strlen($string) + 2, $char, STR_PAD_BOTH);
}
echo str_wrap('hello world'); // "hello world"
echo str_wrap('hello world', '#'); // #hello world#
Create your own.
function addQuotes($str){
return "'$str'";
}
Don't do this. Instead use parametrized queries, such as those with PDO.
This isn't a function - but it's the first post that comes up on google when you type "php wrap string in quotes". If someone just wants to wrap an existing string in quotes, without running it through a function first, here is the correct syntax:
echo $var // hello
$var = '"'.$var.'"';
echo $var // "hello"