PHP save data in sql in multiform - php

I'm using a multiform PHP script given here. It is basically a kind of form completion in multiple steps on the same page. I'm just a beginner in PHP, so I was taking idea from this script.
What I failed to understand is: "How to store the data input by the user in SQL tables?

In the save function, instead of saving data into the $_SESSION (here: $_SESSION[$step][$key] = $val;), save it your SQL database.
But be careful. You will have to update the script to retrieve information from the database instead of from the $_SESSION when you set the value in each input tag.
edit:
The save function is where you will store each data input from user. Instead of :
function save($step, $data) {
//$_SESSION[$step] = $data;
$fields = explode('&',$data);
foreach ($fields as $field) {
$keyVal = explode('=', $field);
$key = urldecode($keyVal[0]);
$val = urldecode($keyVal[1]);
$_SESSION[$step][$key] = $val;
}
}
You should have something like that (the sql queries aren't good, it's just an example):
function save($step, $data)
{
//$_SESSION[$step] = $data;
$fields = explode('&',$data);
$sql = "INSERT INTO `ma_table` (`step`, `key`, `val`) VALUES ";
foreach ($fields as $field)
{
$keyVal = explode('=', $field);
$key = mysql_real_escape_string($keyVal[0]);
$val = mysql_real_escape_string($keyVal[1]);
$sql .= "('" . $step . "', '" . $key . "', '" . $val . "')";
}
mysql_query($sql);
}

Related

WordPress Insert MySQL conversion

I've been working on a simple website heatmap using jQuery & PHP. I've managed to make it work but I would now like to use it in WordPress and I was woundering how to covert the Insert MYSQL function to work with WordPress. See example below:
global $wpdb;
//$clicks = $_POST["clicks"];
$clicks = '.testimonial;1119;316;1663;608;#header;723;66;1663;608';
$keys = array('identifier_name', 'pos_x', 'pos_y','window_width','window_height');
$arr = explode(';', $clicks);
$data = array_chunk($arr, 5);
//Create an array of values for the insert statement
$values = array();
foreach ($data as $rec) {
$values[] = "(1, '" . join("', '", $rec) . "', 'ok')";
}
//Create a single insert statement with all the values
//I am trying to convert this Insert Function
$sql = "INSERT INTO data (user_id, " . join(', ', $keys) . ", status)";
$sql .= "VALUES " . implode(", ", $values);
echo $sql . '<br>';
I am struggeling with the array bit here:
$wpdb->insert(
$table,
array(
/* This is where I struggle */
)
);
Any help much appreceated.
foreach ($data as $rec) {
$wpdb->insert(
$table,
array(
'identifier_name'=> $rec[0],
'pos_x'=>$rec[1],
'pos_y'=>$rec[2],
'window_width'=>$rec[3],
'window_height'=>$rec[4])
);
}
or
$wpdb->query($sql);

Updating via PDO and automatic function

I'm preparing my own function due to hurry the updates automatically.
I have that code:
$allowededitablefields = array('mail');
$userid = $_GET['uid'];
$query = 'UPDATE users SET ';
foreach ($_POST as $key => $value) {
if(!in_array($key,$allowededitablefields)) {
unset($_POST[$key]);
}
else {
$query .= $key.' = :'.$key.',';
}
}
$query = substr($query, 0, -1);
$query .= ' WHERE id='.$userid;
$statement = $this->_db->prepare($query);
foreach ($_POST as $key => $value) {
$statement->bindParam(':'.$key,$value);
}
$statement->execute();
If in $allowededitablefields array, I have only a value, it works properly, but if I push some values to the array, for example $allowededitablefields = array('mail','country',...); the fields in the table take the same values.
$value holds the value of the last iteration when the foreach loop ends.
change the bindParam to this.
$statement->bindParam(':'.$key,$_POST[$key]);
This should work, but your approach is fundamentally flawed. It undermines the whole purpose of prepared statements.

way of doing flexible "INSERT INTO" query with PHP mysqli?

Okay this is going to be a little complex.
But right now i am using a homewritten function to create a query for creating inserting a page into the db.
And i was wondering if there was a smarter way to do a flexible "insert into" method.
The problem is that i have some fields which are optional to type in when creating a page so right now i am using this where i am running through all fields and checks whether they are set or not. :
//creates an Array which can be used to make a MySQL query
function createQueryArray($new) {
if (isset($this->users_id))
$this->query_array['users_id'] = mysql_real_escape_string($this->users_id);
if (isset($this->pagename))
$this->query_array['pagename'] = mysql_real_escape_string($this->pagename);
if (isset($this->seo_pagetitle))
$this->query_array['seo_pagetitle'] = mysql_real_escape_string($this->seo_pagetitle);
if (isset($this->seo_description))
$this->query_array['seo_description'] = mysql_real_escape_string($this->seo_description);
if (isset($this->seo_keywords))
$this->query_array['seo_keywords'] = mysql_real_escape_string($this->seo_keywords);
if (isset($this->seo_robots))
$this->query_array['seo_robots'] = mysql_real_escape_string($this->seo_robots);
if (isset($this->seo_canonical))
$this->query_array['seo_canonical'] = mysql_real_escape_string($this->seo_canonical);
if (isset($this->type))
$this->query_array['page_type'] = mysql_real_escape_string($this->type);
//$this->query_array['last_edited'] = date("Y-m-d H:i:s");
}
Afterwards i am calling this function with the array and the table i wanna insert the page into:
function createInsertStm($arr, $table) {
$mysqlQuery = ("INSERT INTO $table (");
$insert = "";
$values = "";
if (is_array($arr))
foreach ($arr as $key => $value) {
if ($insert == "")
$insert .= $key;
else
$insert .= ', ' . $key;
if ($values == "")
$values .= (preg_match('/(MAX\(id\))(.*?)/', $value)) ? $value : '"' . $value . '"';
else
$values .= (preg_match('/(MAX\(id\))(.*?)/', $value)) ? "," . $value : ',"' . $value . '"';
}
$mysqlQuery .= $insert;
$mysqlQuery .= ') VALUES (';
$mysqlQuery .= $values;
$mysqlQuery .= ')';
return $mysqlQuery;
}
$db->query($queryArray["pages"]);
Is it posible to use a prepared statement and then just skip some of the fields or something similar?
If you setup a default value in the table definition, then you can omit the value on insert.
Check the following page for more info on default values:
http://dev.mysql.com/doc/refman/5.0/en/data-type-defaults.html

Concatenation of string with a specific array elements

the given code below insert data from an array to the mysql table.as its not the full code but what i want to know is available in this code. my question is that there is a field in table named "image_url" but the data in that field only have image name and i want to append http://www.xxxxxx.com at the start of every image name and the replace it with the image name in the field but i dont know how to do that plz help me out
thanks in advance
function putTest($t) {
//$c = connect();
foreach ($t as $k => $v) {
$query = "INSERT INTO test (".implode(',',array_keys($v)).") VALUES ('".implode("','",$v)."')";
//echo "<pre>";
// echo $query;
$r = mysql_query($query);
}
//mysql_close($c);
}
This snippet should do what you want:
if (isset($v['image_url'])) {
$v['image_url'] = 'http://www.xxxxxx.com/' . $v['image_url'];
}
You can concatenate strings with the dot "."!
At first... Is your application protected against SQL injection? If not you should build two methods/functions like this using mysql_real_escape_string():
function sqlSafeKey( $key){
return '`' . mysql_real_escape_string( $key) . `'`;
}
function sqlSafeValue( $value){
return "'" . mysql_real_escape_string( $value) . "'";
}
And than use array_map() to escape your values like this:
$keys = array_map( 'sqlSafeKey', array_keys( $v));
$values = array_map( 'sqlSafeValue', $v);
About your question... The matzino's answer is correct and whole loop should look like this:
function putTest($t) {
//$c = connect();
foreach ($t as $k => $v) {
$v['image_url'] = 'http://www.xxxxxx.com/' . $v['image_url'];
$keys = array_map( 'sqlSafeKey', array_keys( $v));
$values = array_map( 'sqlSafeValue', $v);
$query = "INSERT INTO test (".implode(',', $keys).
") VALUES ('".implode("','",$values)."')";
//echo "<pre>";
// echo $query;
$r = mysql_query($query);
}
//mysql_close($c);
}

insert multiple data

how i do wrong i want insert to db data from array:
$tabb = array(
'name' => 'test',
'login' => 'testt');
but i cant use SET, because end of query is char , .
public function insert($table, $values){
if($this->database){
print_r($values);
$we = 'INSERT INTO '. $table .' SET ';
foreach($values as $value => $key) {
$we .= ' ('. $value .' = "'. $key .'") ';
}
print $we;
mysql_query($we);
}
return true;
}
i do print $we:
INSERT INTO user SET (name = "test") (login = "testt")
not work, please help
php
I really recommend avoiding SET. It is far less common and given the choice between something which is uncommon and something which is common, always go with the common -- it means broader, faster, and better support by your community.
Here's how you'd approach that problem without it:
If you only have two columns in your USER table, you can simply use VALUES followed by a comma delineated list of data sets:
INSERT INTO user VALUES ("test","testt"),("test2","testt2")
Your function doesn't look like it is geared towards this, but it is a good thing to know either way.
But it looks like you are inserting by column name (a good idea in general):
INSERT INTO user (name, login) VALUES ("test","testt")
With PHP this becomes:
$items = array_map('mysql_real_escape_string', $values);
$items = '(\'' . implode( '\',\'', $items ) . '\')';
$q = 'INSERT INTO '.
$table .
// using implode with array_keys assumes that you know all of the keys
// ahead of time. If you don't, I MUST suggest your re-think your code
// omit the following line if you want to follow the first SQL example
' (' . implode( ',', array_keys( $values ) . ') '.
' VALUES ' .
$items;
public function insert($table, $values){
$fields = array();
$data = array();
foreach ($values as $key => $val) {
$fields[] = mysql_real_escape_string($key);
$data[] = mysql_real_escape_string($val);
}
$fields = implode(',', $fields);
$data = implode(',', $data)
$sql = "INSERT INTO $table ($fields) VALUES ($data);"
mysql_query($sql) or die(mysql_error());
}
public function insert($table, $values)
{
if($this->database)
{
print_r($values);
$we = 'INSERT INTO '. $table .' SET ';
$sep = '';
foreach($values as $value => $key)
{
$we .= $sep . ' ('. $value .' = "'. mysql_real_escape_string($key) .'") ';
$sep = ',';
}
print $we;
mysql_query($we);
}
return true;
}
Or, if you want to be tricky:
public function insert($table, $values)
{
if($this->database)
{
print_r($values);
$we = "insert into `".$table. "` (`". implode('`,`',array_keys($fields))."`) values ('".implode("','",array_map('mysql_real_escape_string', $fields))."');";
print $we;
mysql_query($we);
}
return true;
}
You need to seperate (name = "test") (login = "testt") with ", " between them (name = "test"), (login = "testt")
Another way is to do it is:
INSERT INTO user (name, login) VALUES ("test", "testt")

Categories