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);
}
Related
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";
}
}
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'));
So I'm trying to send 3 data values from an Arduino Mega to MySQL database using PHP for my senior design project but I'm encountering an issue. I found an example doing this with 1 data value that would also timestamp the data as it was received. For the life of me I can't figure out how to change the PHP code to pass through 3 values into 3 columns. Here is the PHP script for one data value being sent through:
<?php
foreach ($_REQUEST as $key => $value)
{
if ($key == "yourdata") {
$yourdata = $value;
}
// Check Connection to Database
if (mysql_connect($localhost, $username, $password))
{
#mysql_select_db($database) or die ("Unable to select database");
// Next two lines will write into your table 'test_table_name_here' with 'yourdata' value from the arduino and will timestamp that data using 'now()'
$query = "INSERT INTO $tablename VALUES ($yourdata)";
$result = mysql_query($query);
} else {
echo('Unable to connect to database.');
}
?>
And this is what I thought would work for 3 values but just doesn't end up working:
<?php
foreach ($_REQUEST as $key => $value)
{
if ($key == "yourdata") {
$yourdata = $value;
}
if ($key === "yourdata1"){
$yourdata1 = $value;
}
if ($key === "yourdata2){
$yourdata2 = $value;
}
// Check Connection to Database
if (mysql_connect($localhost, $username, $password))
{
#mysql_select_db($database) or die ("Unable to select database");
// Next two lines will write into your table 'test_table_name_here' with 'yourdata' value from the arduino and will timestamp that data using 'now()'
$query = "INSERT INTO $tablename(yourdata, yourdata1, yourdata2) VALUES ($yourdata, $yourdata1, $yourdata2)";
$result = mysql_query($query);
} else {
echo('Unable to connect to database.');
}
?>
I tried testing by entering the address in the URL like so
http://hydrosen.byethost11.com/insert_mysql1.php?yourdata=23&yourdata1=43&yourdata2=555
Like I said if I try it with one data value it works but it doesn't for three values. The table's column names are "yourdata" "yourdata1" and yourdata2".
Any help with this frustrating issue would be greatly appreciated
try this:
$yourdata = "";
$yourdata1 = "";
$yourdata2 = "";
foreach ($_REQUEST as $key => $value)
{
if ($key == "yourdata") {
$yourdata = $value;
}
if ($key === "yourdata1"){
$yourdata1 = $value;
}
if ($key === "yourdata2){
$yourdata2 = $value;
}
// Next two lines will write into your table 'test_table_name_here' with 'yourdata' value from the arduino and will timestamp that data using 'now()'
$query = "INSERT INTO $tablename('yourdata', 'yourdata1', 'yourdata2') VALUES ('$yourdata', '$yourdata1', '$yourdata2')";
Okay here goes. Connect.inc.php has credential info and functions .php just routes the data to another table I believe.I'm not sure if all this is necessary to post the data but my friend wrote all the additional code and we've been busy trying to get the rest of the project to work so I haven't gotten a full understanding of how this works yet.
<?php
//ob_start();
include_once 'functions.php';
include_once 'connect.inc.php';
$id =2; // Id of sensor
$yourdata = "";
$yourdata1 = "";
$yourdata2 = "";
foreach ($_REQUEST as $key => $value)
{
if ($key == "yourdata") {
$yourdata = $value;
}
if ($key === "yourdata1"){
$yourdata1 = $value;
}
if ($key === "yourdata2"){
$yourdata2 = $value;
}
$tot_data= $yourdata.','. $yourdata1.','.$yourdata2.';';}
//$tot_data= $yourdata.','. $yourdata1.','.$yourdata2.';';
if ($select_stmt = $connection->prepare("SELECT `sensor_id`, `wifidata` FROM `wifi` WHERE `sensor_id` = ? "))
{
//$id = $_SESSION['user_id'];
$select_stmt->bind_param('d', $id);
$select_stmt->execute(); // Execute the prepared query.
$res = $select_stmt->get_result();
if($res->num_rows==0)
{
if ($insert_stmt = $connection->prepare("INSERT INTO
`wifi`(`sensor_id`,`wifidata`)
VALUES(?,?) "))
{
Currently I'm stuck on how to add the values of my array into a variable, to output in a query.
Here are my data stored in:
try {
$link->create(array(
'uid' => $user->data()->id,
'name' => Input::get('name'),
'hyperlink' => Input::get('hyperlink')
));
} catch (Exception $e) {
die($e->getMessage());
}
And with this function I'm trying to get the values from that array into 1 variable:
public function insert($table, $fields = array()) {
if (count($fields)) {
$keys = array_keys($fields);
$x = 1;
foreach ($fields as $field => $values) {
if ($x < count($fields)) {
$values .= ', ';
}
$x++;
}
$sql = "INSERT INTO `$table` (`" . implode('`, `', $keys) . "`) VALUES ({$values})";
die($sql);
if (!$this->query($sql, $fields)->error()) {
return true;
}
}
return false;
}
But when I echo the sql it only gives the last value of the array. What am I doing wrong?
Thanks!
You could try something like this, cuts down on the looping a bit, and could be combined into a single line actually... EDIT: neglected to quote the values... updated appropriately
if (count($fields)) {
$field_list = implode(", ", array_keys($fields));
$value_list = implode("', '", array_values($fields));
$sql = "insert into `$table` ($field_list) values('$value_list')";
}
Here is another option and I couldn't figure out what was wrong with your script, it looks correct but wasn't able to find the problem. I always use this class method when inserting db values dynamically.
function insertRecord ($fieldarray)
{
$this->errors = array();
//Connect to the DB for table insert
global $dbconnect, $query;
$dbconnect = db_connect($this->dbname) or trigger_error("SQL", E_USER_ERROR);
//Now, using the contents of $fieldlist which was set in the class constructor we can edit the input array to filter out any items which do not belong in this database table. This removes the SUBMIT button, for example.
$fieldlist = $this->fieldlist;
foreach ($fieldarray as $field => $fieldvalue) {
if (!in_array($field, $fieldlist)) {
unset ($fieldarray[$field]);
} // if
} // foreach
//Now construct the query string to insert a new
//record into the database:
$query = "INSERT INTO $this->tablename SET ";
foreach ($fieldarray as $item => $value) {
$query .= "$item='$value', ";
} // foreach
//You may have noticed that each 'name=value' pair was appended
//to the query string with a trailing comma as a separator,
//so we must remove the final comma like so:
$query = rtrim($query, ', ');
//Now execute the query. Notice here that instead of the default
//error checking I look specifically for a 'duplicate key' error
//and return a simple error message rather terminating the whole
//script with a fatal error.
$result = #mysql_query($query, $dbconnect);
if (mysql_errno() <> 0) {
if (mysql_errno() == 1062) {
$this->errors[] = "A record already exists with this ID.";
} else {
trigger_error("SQL", E_USER_ERROR);
} // if
} // if
//Last act is to return control to the calling script.
return;
} // insertRecord
IMHO the function above has the necessary checks for an insert statement and error handling which I found useful.
I think you can use the function array_values like you use the function array_keys to do this easier.
public function insert($table, $fields = array()) {
if (count($fields)) {
$keys = array_keys($fields);
$values = array_values($fields); // why another logic for the same result.. ?
$sql = "INSERT INTO `$table` (`" . implode('`, `', $keys) . "`) VALUES (`" . implode('`, `', $values) . "`)";
die($sql);
if (!$this->query($sql, $fields)->error()) {
return true;
}
}
return false;
}
The problem is the $values = $values is inside the foreach loop.
foreach ($fields as $field => $values) {
// The problem is right here, each time this loops, you are
// setting the entire $values variable to be just the current iteration
// of the $fields variable.
$values = $values;
if ($x < count($fields)) {
$values .= ', ';
}
$x++;
}
Try this instead:
$sql_values = '';
foreach ($fields as $field => $values) {
if ($x < count($fields)) {
$sql_values.= $values.', ';
}
$x++;
}
$sql = "INSERT INTO `$table` (`" . implode('`, `', $keys) . "`) VALUES ($sql_values)";
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.