array from post into a single mysql row - php

I have an array that is built based on dynamic rows that changes every time. I am able to post the array but i get each field in a separate row. How can i insert the array into a single row.
Here is my PHP:
<?php
include_once 'dbconnect.php';
if (isset($_POST['item_name'])) {
$table = $_POST['ItemTypeSelect'];
$array = array();
foreach ($_POST as $key => $variable) {
$chesckColumn = mysql_query("SELECT `$key` from $table");
if (!$chesckColumn) {
echo "column ".$key." does not exist <br/>";
}else{
$results = $variable;
$columnName = $key;
$array[$columnName] = $results;
mysql_query("INSERT INTO $table (`$columnName`) VALUES ('$results') ")or die(mysql_error());
}
}
print_r($array);
}
?>
The print array is :
Array
(
[Server_id] =>
[Server_IP_Address] => 123456789
[Server_IP2] => 123456789
[Server_Name] => Server
)
Any help is appreciated.

$table = $_POST['ItemTypeSelect'];
$isert_vals = "VALUES(";
$insert_table = "INSERT INTO `".$table."` (";
foreach ($_POST as $key => $variable) {
$chesckColumn = mysql_query("SELECT `$key` from $table");
if (!$chesckColumn) {
echo "column ".$key." does not exist <br/>";
} else {
$results = $variable;
$columnName = $key;
$array[$columnName] = $results;
$insert_table.="`".$columnName."`,";
$isert_vals.="'".$results."',";
}
}
$isert_vals = substr($isert_vals , 0 ,-1).") ";
$insert_table = substr($insert_table , 0 ,-1).") ";
$query = $insert_table.$isert_vals;
mysql_query($query);

You need to build one INSERT statement, rather than executing a new one each time you go through your loop.
Also, please note that the mysql_* functions are deprecated - you should use PDO or MySQLi instead.
Finally, you are wide open to SQL injection attacks. Use prepared statements, or all sorts of Very Bad Things will happen to your database, app, server, toaster, and dog.

Something like this should do the trick:
if (isset($_POST['item_name'])) {
$table = mysql_real_escape_string($_POST['ItemTypeSelect']);
$array = array();
$cols = array();
$vals = array();
foreach ($_POST as $key => $variable) {
$key = mysql_real_escape_string($key);
$variable = mysql_real_escape_string($variable);
$chesckColumn = mysql_query("SELECT `$key` from $table");
if (!$chesckColumn) {
echo "column ".$key." does not exist <br/>";
} else {
$cols[] = $key;
$vals[] = $variable;
}
}
$columns = implode(",", $cols);
$values = implode("," , $vals);
mysql_query("INSERT INTO $table ($columns) VALUES ($values)") or die(mysql_error());
}
Be aware that mysql extension is deprecated. Consider using mysqli or PDO.
And note that you should always sanitize your database input to prevent sql-injections.

Related

Same Data is saving two times?

Hi I'm inserting data to database it's saving two time same data only username is saving two times I want save it only one time also I want save address
<?php
$users = array("username"=>"Kaleem", "adrress"=>"abc");
class dbase{
public function dbinsert($table,$users)
{
foreach ($users as $key => $value)
{
$sql = "INSERT INTO $table (`$key`) VALUES ('$value')";
$this->conn->query($sql);
if($this->conn->query($sql))
{
echo "Data inserted";
}
}
}
public function __construct ()
{
$this->conn = new mysqli('localhost','root','','dbase');
if($this->conn)
{
echo "Connected<br>";
}
}
}
$obj = new dbase;
$obj->dbinsert('users',$users);
?>
The problem is that you are calling the query function twice.
$this->conn->query($sql); // saves the first time
if($this->conn->query($sql)) // saves the second time
{
echo "Data inserted";
}
To avoid that the query is called twice you can save the result of the query into a variable and check it in the if.
Currently, you are saving each field of the users array in an own dataset because you are calling the query function on each field from your foreach loop.
Try this:
<?php
$users = array( // this array is for the users
array("username"=>"Kaleem", "adrress"=>"abc"), // this is one user
array("username"=>"Mickey Mouse", "adrress"=>"Test street"),
);
class dbase{
public function dbinsert($table,$users)
{
foreach ($users as $key => $value)
{
// Extract field names
$fields = implode("`, `", array_keys ( $users[$key] );
// Extract values
$values = implode("', '", array_values ( $users[$key] );
$sql = "INSERT INTO $table (`" . $fields . "`) VALUES ('". $values ."')";
// Check if query was succesfull
$success = $this->conn->query($sql);
if($success)
{
echo "Data inserted";
} else { // if no success display error message
echo "Error while saving";
}
}
}
public function __construct ()
{
$this->conn = new mysqli('localhost','root','','dbase');
if($this->conn)
{
echo "Connected<br>";
}
}
}
$obj = new dbase;
$obj->dbinsert('users',$users);
?>
you need name and address together as column name and corresponding values as field values in sql
public function dbinsert($table,$users)
{
$sqlKeys = [];
$sqlValues = [];
foreach ($users as $key => $value)
{
$sqlKeys[] = "'".$key."'";
$sqlValues[] = "'".$value."'";
}
$keys = array_implode(",",$sqlKeys);
$values = array_implode(",",$sqlValues);
$sql = "INSERT INTO $table ($keys) VALUES ($values)";
if($this->conn->query($sql))
{
echo "Data inserted";
}
}
that happen because you using foreach() for single array dimension,
$users = ["username"=>"Kaleem", "adrress"=>"abc"];
foreach($users as $key=>$value){
echo $value."\n";
}
this $success = $this->conn->query($sql); executed twice because array length is 0 and 1 , if you wanna use foreach you have to use multidimensional array like
$users = [
["username"=>"Kaleem", "adrress"=>"abc"]
];
foreach($users as $key=>$value){
$sql = "INSERT INTO $table (`username`, `adrress`) VALUES ('". $value['username'] ."', '". $value['adrress'] ."')";
$this->conn->query($sql);
}

sqlsrv insert when columns vary

I have searched around the web but no luck.
Am new to SQLSRV and i was migrating from PHP MySQL to PHP SQL and am having trouble inserting data from a form as some fields are optional which makes the column number vary. I need help on how i can insert when the column number varies.
thank you
here is how my insert code looks like
// sql fields and values for main table
$in_fields = array();
$in_values = array();
// prepare insertion
foreach ($_POST as $key => $value) {
if (!empty($value)) {
$value = sql_escape($value);
$in_fields[] = "[{$key}]";
$in_values[] = "'{$value}'";
}
}
// prepare sql stmt
if (!empty($in_fields)) {
$sql = "INSERT into [table_name](";
$sql .= implode(", ", $in_fields);
$sql .= ") VALUES ()";
if (executeSql($sql, $in_values)) {
$success = "Successfully Added New Record";
}
}
The executeSql function looks like this
function executeSql($sql, $params) {
global $conndb;
$rs = sqlsrv_query($conndb, $sql, $params)or die("Db query error.<br />".print_r(sqlsrv_errors(), true));
return !$rs ? false : true;
}
You need to add placeholder values (?) in the VALUES part of your query, you will need a placeholder for every value you pass through - i.e. for every value in $in_values.
To do this you could have another array, that will just have a number of ? as values, and then, like you have done for the fields, implode the array into the VALUES. Like so:
$in_fields = array();
$in_values = array();
$placeholders = array(); // new array
foreach ($_POST as $key => $value) {
if (!empty($value)) {
$value = sql_escape($value);
$in_fields[] = "[{$key}]";
$in_values[] = "'{$value}'";
// add a placeholder to the array
$placeholders[] = "?";
}
}
if (!empty($in_fields)) {
$sql = "INSERT into [table_name](";
$sql .= implode(", ", $in_fields);
$sql .= ") VALUES (" . implode(",", $placeholders) . ")";
if (executeSql($sql, $in_values)) {
$success = "Successfully Added New Record";
}
}

PHP insert with array values,tablename

I am struggling with a PHP insert statement. I want it to insert data into the database by using array_keys($values) and array_values($values).
I have tried to work out how I can do this and so far I have this code in my insert and have also included my index page. I need to do it without changing the index page as it is a challenge I have to complete. I have analysed the index page and need to somehow make the function work with that to insert data into my database from the PHP insert command.
I also wonder if there's a way to wrap the PDO connection into one statement which I can use for this and other functions.
Insert Function
<?php
function insert(array $values, $tablename)
{
//cosntruct sql statment
$sql = "INSERT INTO $tablename $values";
//pick apart vaules
//this line fetches the result set and fetch assoc to prevent multiple rows beign fetched
$ResultSet = dbconnect()->query($sql);
//returns the results
return $ResultSet;
//array keys and array vaules
//connection
// checks results
}
?>
Part of the Index page:
if(isset($_POST['table']))
{
$tableName = $_POST['table'];
}
if(isset($_POST['insert']))
{
$values = array();
$tableName = $_POST['tablename'];
foreach($_POST as $key => $value)
{
if(!empty($value) && ($value != "Submit") && ($key != "insert") && ($key != "table") && ($key != "tablename"))
{
$values[$key] = $value;
}
}
$count = insert($values, $tableName);
}
Note that I am quite new at coding. Any suggestions?
try this, it works fine for me. You just have to pass the name of the table and an associative array which has the name of the columns as keys.
public function insert($table, $data)
{
$query='INSERT INTO '.$table.' (';
foreach($data as $key => $value)
{
$query .= $key.',';
}
$query = substr($query, 0, -1);
$query .= ') VALUES (';
foreach($data as $key => $value)
{
$query .= ':'.$key.',';
}
$query = substr($query, 0, -1);
$query .= ');';
$insert = $this->db->prepare($query);
$insert->execute($data);
}

how to make an insert function with in a database class to insert a new record with multiple coloumns and multiple values (using PDO )?

the problem is my function insert inserts my record in two rows.
this is my code to connect to database in a file named :
connect.php
<?php
try{
$db = new PDO("mysql:host=localhost;dbname=NPD" , "root" , "");
echo "connected";
}
catch(Exception $e){
echo $e->getMessage();
}
this is my database class in a file
database.php
<?php
require 'connect.php';
class DB {
public function insertInto($tableName , $info){
global $db;
foreach ($info as $coloumnName => $coloumnValue) {
$stmt = $db->prepare("INSERT INTO $tableName ($coloumnName) VALUES ('$coloumnValue') ");
$stmt->execute();
}
}
}
$da = new DB;
$da->insertInto('tableOne',array('name' => 'lolo' , 'deg' => '100'));
the result in the database is :
tableOne
how can to make the insert function inserts my record in one row.
note : i want to insert any number of columns and values.
try to do something like this:
$arr = array('name' => 'lolo' , 'deg' => '100');
$columns=array_keys($arr);
$values=array_values($arr);
$str="INSERT INTO $tableName (".implode(',',$columns).") VALUES ('" . implode("', '", $values) . "' )";
echo $str;//your sql
// $stmt = $db->prepare($str);
// $stmt->execute();//uncomment to execute
Like this but there are some concerns ( also I haven't tested this )
class DB {
protected $_conn;
public function __construct( $user, $pass, $database='NPD', $host='localhost' ){
try{
$this->_conn = new PDO("mysql:host={$host};dbname={$database}" , $user , $pass);
echo "connected";
}catch(Exception $e){
echo $e->getMessage();
}
}
public function insertInto($tableName , $info){
$sql = 'INSERT INTO $tableName (';
$sql .= '`'implode('`,`', array_keys($info[0])).'`';
$sql .= ')VALUES';
foreach ($info as $index => $row) {
$sql .= '(';
foreach( $row as $column => $value){
$sql .= ':'.$column.$index.',';
$params[':'.$column.$index] = $value;
}
$sql = rtrim($sql, ',');
$sql .= '),';
}
$sql = rtrim($sql, ',');
$stmt = $this->_conn->prepare($sql);
$stmt->execute($params);
}
}
}
$da = new DB('root', '');
$da->insertInto('tableOne',array( array('name' => 'lolo' , 'deg' => '100') ) );
First of all you loose any sql injection protection on the column names. If you can manage the placeholders on the values, then that is ok, but without using them there you loose protection on that as well. This can be solved by using the db schema itself, via Show columns but that gets a wee bit complex.
https://dev.mysql.com/doc/refman/5.7/en/show-columns.html
Second, your input array structure is all wrong, it needs to be array(0=>array(...), 1=>array(...)) instead of just array(...)
Third I would make this class a "Singleton" but that's just me
http://coderoncode.com/design-patterns/programming/php/development/2014/01/27/design-patterns-php-singletons.html
Forth, if you just want to do a single row at a time you can change this method
public function insertInto($tableName , $info){
$sql = 'INSERT INTO $tableName (';
$sql .= '`'implode('`,`', array_keys($info)).'`';
$sql .= ')VALUES(';
$params = array();
foreach( $info as $column => $value){
$sql .= ':'.$column.$index.',';
$params[':'.$column.$index] = $value;
}
$sql = rtrim($sql, ',');
$sql .= ')';
$stmt = $this->_conn->prepare($sql);
$stmt->execute($params);
}
And use the current input array structure you have.
This Is how i coded my own insert function
public function insertRecord($table,$records){
//A variable to store all the placeholders for my PDO INSERT values.
$placeholder = '';
for ($i = 0; $i < sizeof($records); $i++){
$placeholder[$i] = '?';
}
//A FOR-LOOP to loop through the records in the $record array
$placeholder = implode(',', $placeholder);
//Imploding ',' in between the placeholders
$sql = "INSERT INTO ".$table." VALUES ("{$placeholder}")";
$query = $this->dbh->prepare($sql);
$query->execute($records);
}
It Might not be the best..worked for me though.
As some other answers/comments have stated, there are quite a few critiques one could make about this overall process. However, in the interests of simply answering the question, you may want to just build the statement by looping through the columns, then looping through the values, then executing the finished statement (code below is just an example and hasn't been tested):
require 'connect.php';
class DB {
public function insertInto($tableName , $info){
global $db;
$query = "INSERT INTO $tableName (";
$columns = array_keys($info);
// build the columns in the statement
$length = count($columns);
foreach($columns as $index => $column) {
$query .= "$column";
if ($index+1 < $length) {
$query .= ','
}
}
$query .= ") VALUES ("
// build the values in the statement
$i = 1;
$length = count($info);
foreach($info as $value) {
$query .= "'$value'"
if ($i < $length) {
$query .= ","
}
$i++;
}
$query .= ")"
$stmt = $db->prepare($query);
$stmt->execute();
}
}
$da = new DB;
$da->insertInto('tableOne',array('name' => 'lolo' , 'deg' => '100'));

Insert sql query result to a new query

So the task is:
Do a query like Select * from table.
Take some cell value
Insert this value to a new query.
What do I have so far:
$Conn = odbc_connect("...");
$Result = odbc_exec("Select ...");
while($r = odbc_fetch_array($Result))
// showing result in a table
Here it looks like I should use the r array and insert data like
$var = r['some_field'];
$query = 'Select * from table where some_field = {$var}";
But how can I fill this array with values and how to make it available out of while loop?
Here I'm using odbc, but it doesn't matter, I need the algorithm. Thanks.
The whole code looks like:
<?php
$data = array();
$state = 'false';
if($_REQUEST['user_action']=='')
{
$Conn = odbc_connect("...");
$data = array();
if($_REQUEST['name']!='')
{
$Result = odbc_exec($Conn, "select ...");
//Showing result table
while($r = odbc_fetch_array(Result))
{
array_push($data, $r['cardgroup']);
$state = 'true';
}
// print_r($data); WORKS;
}
}
if ($_REQUEST['user_action'] == 'action1')
{
//I need to use $data HERE. Doesn't work
// $state = 'false' here...
}
?>
Define array outside while loop
$data = array();//defining
while($r = odbc_fetch_array($Result))
use array_push() inside while loop
array_push($data, $r['some_field']);
then try to print array of complete data outside loop
print_r($data);
Updates
Place $data = array(); at the top of first IF statement. Try this code:
$data = array();//at top
if($_REQUEST['user_action']=='')
{
$Conn = odbc_connect("...");
if($_REQUEST['name']!='')
{
$Result = odbc_exec($Conn, "select ...");
//Showing result table
while($r = odbc_fetch_array(Result))
{
array_push($data, $r['cardgroup']);
}
// print_r($data); WORKS;
}
}
if ($_REQUEST['user_action'] == 'action1')
{
//print_r($data) works here also
}
try something like this to store data in array
$allrows = array();
while($r = odbc_fetch_array( $result )){
$allrows[] = $r;
}
use foreach loop to print or use as per your choice
foreach($allrows as $singlerow) {
//use it as you want, for insert/update or print all key value like this
foreach($singlerow as $key => $value) {
//echo $key . '=='. $value;
}
}
You can try this as i understand your query hope this is your answer
$arr ='';
while($row = odbc_fetch_array($Result)) {
$arr .= '\''.$row['some_field'].'\',';
}
$arr = trim($arr, ",");
$query = "SELECT * from table where some_field IN ($arr)";
Your all task can be completed in single query
INSERT INTO table2 (col1, col2, ..., coln)
SELECT col1, col2, ..., coln
FROM table1

Categories