I am testing multiple array insertion into my table, I have try all what I could but I am not getting.Here is my code:
<?php
ini_set('display_errors',1);
//ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$mysqli = new mysqli(HOST,USER,PASS,DB);
$message = array();
$id =1;
$SocialHandle = "Facebook,Twitter,LinkIn";
$SociaUrl ="Url1,Url2,Url3";
$strSocialHandle = explode(',', $SocialHandle);
$strSociaUrl = explode(',', $SociaUrl);
print_r($strSocialHandle);
print_r($strSociaUrl);
$sql = "INSERT INTO `social_table`(`id`, `social_handle`, `handle_url`) VALUES";
foreach($strSocialHandle as $SocialNameValue){
$sql .= "({$id}, '{$SocialNameValue}','{$strSociaUrl}'),";
}
$sql = rtrim($sql, ',');
$result = $mysqli->query($sql);
if (!$result){
$message = array('Message' => 'insert fail or record exist');
echo json_encode($message);
}else{
$message = array('Message' => 'new record inserted');
echo json_encode($message);
}
?>
Here is my goal achievement:
ID social handle
handle url 1 Facebook
url1 1
Twitter url2 1
LinkIn
url3
Please help.
You can use for loop for it as
$id =1;
$SocialHandle = "Facebook,Twitter,LinkIn";
$SocialHandle = explode(",", $SocialHandle);
$SociaUrl = "Url1,Url2,Url3";
$SociaUrl = explode(",", $SociaUrl);
$sql = "INSERT INTO `social_table`(`id`, `social_handle`, `handle_url`) VALUES";
for ($i = 0; $i < count($SocialHandle); $i++) {
$sql .= "({$id}, '$SocialHandle[$i]','$SociaUrl[$i]'),";
}
$sql = rtrim($sql, ',');
echo $sql;
$result = $mysqli->query($sql);
OUTPUT
INSERT INTO social_table(id, social_handle, handle_url)
VALUES(1, 'Facebook','Url1'),(1, 'Twitter','Url2'),(1,
'LinkIn','Url3')
DEMO
UPDATED
Better use prepare and bind statement to prevent form sql injection as
for ($i = 0; $i < count($SocialHandle); $i++) {
$sql = "INSERT INTO `social_table`(`id`, `social_handle`, `handle_url`) VALUES (?,?,?)";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param('iss', $id, $SocialHandle[$i], $SociaUrl[$i]);
$stmt->execute();
}
You're only looping over $strSocialHandle - the $strSociaUrl array isn't affected by the loop, so will still be an array rather than an individual value. You can store the two lists in a single key-value array, and use one loop to iterate over both:
<?php
$id = 1;
$social = [
'Facebook' => 'Url1',
'Twitter' => 'Url2',
'LinkIn' => 'Url3',
];
$sql = "INSERT INTO `social_table`(`id`, `social_handle`, `handle_url`) VALUES";
foreach($social as $handle => $url) {
$sql .= "({$id}, '{$handle}','{$url}'),";
}
echo rtrim($sql, ',');
Related
So it's probably a really stupid/basic question, but i have this simple PHP function (which works) and inserts data into a PostgreSQL DB.
My issue is when it encounters specific data;
function insertData($pg, $csvfile)
{
$x = 0;
foreach ($csvfile as $data)
{
$email = $csvfile[$x]['email'];
$name = $csvfile[$x]['name'];
$surname = $csvfile[$x]['surname'];
$query = "INSERT INTO users (email, name, surname) VALUES ('$email', '$name', '$surname')";
$result = pg_query($pg, $query);
$x++;
}
}
And while this works, it falls over with a surname such as:
O'hare
And obviously this occurs because then the PHP code comes out as:
...VALUES ('john#example.com', 'John', 'O'hare')";
but im not sure of how i should be structuring the PHP to allow for this.
Try this:
function insertData($pg, $csvfile) {
$nbr = count(file($csvfile));
for($i=0; $i<$nbr; $i++) {
$email = pg_escape_string( $csvfile[$i]['email'] );
$name = pg_escape_string( $csvfile[$i]['name'] );
$surname = pg_escape_string( $csvfile[$i]['surname'] );
$query = "INSERT INTO users (email, name, surname) VALUES ('$email', '$name', '$surname')";
$result = pg_query($pg, $query);
if (!$result) {
echo "Error while executing the query: " . $query;
exit;
}
}
}
You need to escape the string parameters. And it is much better if you can use PDO extension, because prepared statements can take care of escaping for you and also helps with preventing SQL injection and some other security concerns.
function insertData(PDO $dbh, $csvfile) {
$x = 0;
foreach ($csvfile as $data)
{
$query = "INSERT INTO users (email, name, surname) VALUES (?, ?, ?)";
$params = [
$csvfile[$x]['email'],
$csvfile[$x]['name'],
$csvfile[$x]['surname']
];
$statement = $pdo->prepare($query);
$statement->execute();
$x++;
}
}
PDO::prepare
PDOStatement::execute
Solution using prepared query
function insertData($dbname, $tbname, $csvfile)
{
$result = [];
// Connect to a database named "mary"
$dbconn = pg_connect("dbname=$dbname");
// Prepare a query for execution
$result = pg_prepare($dbconn, "my_query", 'INSERT INTO $1 (email, name, surname) VALUES ($2, $3, $4)');
// Execute the prepared query. Note that it is not necessary to escape
foreach ($csvfile as $data)
{
$email = $data['email'];
$name = $data['name'];
$surname = $data['surname'];
$query = "";
$result[] = pg_execute($dbconn, "my_query", array($tbname, $email, $name, $surname));
}
if (in_array(false, $result) )
return false;
else
return true;
}
$dbname = "your dbname";
$tbname = "name of table";
$csvFile = [];
if (insertData($dbname, $tbname, $csvFile))
echo "Data inserted";
else
echo "Data not inserted";
So i took note of the suggestions from #Karsten Koop and #TOH19, and came up with this code which is working;
function insertData($pg, $csvfile)
{
$x = 0;
foreach ($csvfile as $data)
{
$email = pg_escape_string($csvfile[$x]['email']);
$name = pg_escape_string($csvfile[$x]['name']);
$surname = pg_escape_string($csvfile[$x]['surname']);
$query = "INSERT INTO users (email, name, surname) VALUES ('".$email."', '".$name."', '".$surname."')";
$result = pg_query($pg, $query);
$x++;
}
}
I have database that hold my data in mysql.
I have already data in my table (call words) and I want to insert new data to this table but before I want to check if this data not already exist.
I have function that insert the data to table but I need sql query that will check if the data not exist?
the colum in my table 'words' are :word , num , hit , instoplist.
I write the code in PHP
Thanks,
this is my code:(insert to table function)
function insert($myWords)
{
global $conn;
$temp1 = $value['document'];
$temp2 = $value['word'];
$sql = "INSERT INTO words (word,num,hit,instoplist) VALUES";
foreach ($myWords as $key => $value) {
$word = $value['word'];
$number = $value['document'];
$hit = $value['hit'];
$stop = $value['stopList'];
$sql .= "('$word', '$number', '$hit','$stop'),";
}
$sql = rtrim($sql,','); //to remove last comma
if($conn->query($sql)!== TRUE)
{
echo "error". $conn->error;
}
}
Before inserting the data make a select query on a column which is unique as per your requirement like:
$chkExist = "select id from table where col_name = '".$value."'";
$res = $conn->query($chkExist);
// Now check if there is some record in $res than stop the entry otherwise insert it
function insert($myWords)
{
global $conn;
$temp1 = $value['document'];
$temp2 = $value['word'];
$sql = "INSERT INTO words (word,num,hit,instoplist) VALUES";
foreach ($myWords as $key => $value) {
$sql2 "SELECT * FROM words WHERE word = '".$value['word']."' OR num = '".$value['document']."'"; //other data if you want
$resultat=mysql_query($query);
if($resultat==""){
$word = $value['word'];
$number = $value['document'];
$hit = $value['hit'];
$stop = $value['stopList'];
$sql .= "('$word', '$number', '$hit','$stop'),";
}
}
$sql = rtrim($sql,','); //to remove last comma
if($conn->query($sql)!== TRUE)
{
echo "error". $conn->error;
}
}
$sel="select * from words where word = '$word' AND document = '$document' AND hit = '$hit' AND stopList ='$stopList'";
$qry=mysqli_query($sel);
$num=mysqli_num_rows($qry);
if($num==0){
$sql = "INSERT INTO words (word,num,hit,instoplist) VALUES";
foreach ($myWords as $key => $value) {
$word = $value['word'];
$number = $value['document'];
$hit = $value['hit'];
$stop = $value['stopList'];
$sql .= "('$word', '$number', '$hit','$stop'),";
}
$sql = rtrim($sql,',');
}else{
echo "Already Exist";
}
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'));
I have a text file, who's value i have put into arrays,
this is the php code:
<?php
$homepage = file_get_contents('hourlydump.txt');
$x = explode('|', $homepage);
$desc = array();
$cat = array();
$link = array();
$m = 1;
$n = 2;
$p = 3;
for ($i = 1; $i <= count($x) / 4; $i++) {
$m = $m + 4;
$desc[] = $x[$m];
$n = $n + 4;
$cat[] = $x[$n];
$p = $p + 4;
if ($x[$p])
$link[] = $x[$p];
}
echo "<pre>";
print_r($desc);
print_r($cat);
print_r($link);
?>
output is like:
Array
(
[0] => Kamal Heer - Facebook Official Video 720p Dual Audio [Hindi + Punjabi]76 mb by rANA.mkv
[1] => 50 HD Game Wallpapers Pack- 1
)
Array
(
[0] => Movies
[1] => Other
)
Array
(
[0] => http://kickass.to/kamal-heer-facebook-official-video-720p-dual-audio-hindi-punjabi-76-mb-by-rana-mkv-t7613070.html
[1] => http://kickass.to/50-hd-game-wallpapers-pack-1-t7613071.html
)
//
//
//
anyone please help me i dont know how to insert the values of these three arrays $desc, $cat and $link
into mysql table, columns named description, category, link
i know simple insert queries but dont how to deal with these arrays.
I will give you an example of how basic database connection is made and the insert is completed, this is for illustrative purpose only. You should reorganize this code inside a class so that every insert statement doesn't create a PDO object but re-use the object created before.
function insertItem($desc, $cat, $link) {
$dbh = new PDO("mysql:host=host;dbname=db", $user, $pass);
$sql = "INSERT INTO table (description, category, link) VALUES (:desc, :cat, :link)";
$sth = $dbh->prepare($sql);
$sth->bindValue(":desc", $desc);
$sth->bindValue(":cat", $cat);
$sth->bindValue(":link", $link);
$sth->execute();
}
You can use a for statement.
for($x =0, $num = count($desc); $x < $num; $x++){
// build you query
$sql = "INSERT into your_table (description, category, link) values ".
"(".$db->quote($desc[$x]).",".$db->quote($cat[$x]).",".
$db->quote($link[$x].")";
$db->query($sql);
}
Of course you will have to use the sanitation/quoting methods appropriate for your chosen database api.
Here is a simple sample to read your file as is from the website you retrieve it as well as inserting it to the database sanitizing the data:
<?php
// fill with your data
$db_host = 'localhost';
$db_user = '';
$db_pass = '';
$db_name = '';
$db_table = 'myTable';
$file = "hourlydump.txt.gz";
if($filehandle = gzopen($file, "r"))
{
$content = gzread($filehandle, filesize($file));
gzclose($file);
}
else
die('Could not read the file: ' . $file);
$con = mysqli_connect($db_host,$db_user,$db_pass,$db_name);
if($con->connect_error)
die('Connect Error (' . mysqli_connect_errno() . ') '. mysqli_connect_error());
$sql = "INSERT INTO $db_table (description, category, link) VALUES (?, ?, ?)";
if (!$insert = $con->prepare($sql))
die('Query failed: (' . $con->errno . ') ' . $con->error);
foreach (explode("\n", $content) as $line)
{
list($md5hash,$desc,$cat,$link,$torrent) = explode("|", $line);
if (!$insert->bind_param('sss',$desc,$cat,$link))
echo 'Binding parameters failed: (', $insert->errno, ') ', $insert->error;
if (!$insert->execute())
echo 'Insert Error ', $insert->error;
}
$insert->close();
$con->close();
NOTE: you may want to check if the file was loaded with success, if the fields from the explode exist or not to prevent further problems but in general this should work just fine.
Also you may want to change the $sql to reflect your MySQL table aswell as the $db_table at the top.
UPDATE: to insert all values change this:
$sql = "INSERT INTO $db_table (description, category, link) VALUES (?, ?, ?)";
To:
$sql = "INSERT INTO $db_table (md5, description, category, link, torrent) VALUES (?, ?, ?, ? ,?)";
And this:
if (!$insert->bind_param('sss',$desc,$cat,$link))
To:
if (!$insert->bind_param('sssss',$md5hash,$desc,$cat,$link,$torrent))
Note above the s for each item you need a s you have 5 items so 5 s's the S means string, D double, I integer, B blob you can read more at about it here.
Also note the $sql for each item we will use on the bind_param we have a ?.
Try this. I am assuming that only these much of values are there for insertion
for($i = 0;$i<2;$++) {
mysqli_query("INSER INTO tablename values(description,category,link) VALUES('$desc[$i]'
,'$cat[$i]','$link[$i]')");
}
You can build your query while you're doing you calculations:
$query = "INSERT INTO `table` (`description`, `category`, `link`) VALUES ";
for ($i = 1; $i <= count($x) / 4; $i++) {
$m = $m + 4;
$query .= "('".$x[$m];
$n = $n + 4;
$query .= "','".$x[$n];
$p = $p + 4;
if ($x[$p]) $query .= "','".$x[$p]."'),";
else $query .= "',NULL),";
}
$query = substr($query, 0, -1);//get rid of last comma
mysqli_query($query);
You can also build the arrays along with the query if you need to:
$query = "INSERT INTO `table` (`description`, `category`, `link`) VALUES ";
for ($i = 1; $i <= count($x) / 4; $i++) {
$m = $m + 4;
$desc[] = $x[$m];
$query .= "('".$x[$m];
$n = $n + 4;
$cat[] = $x[$n];
$query .= "','".$x[$n];
$p = $p + 4;
if ($x[$p]){
$link[] = $x[$n];
$query .= "','".$x[$p]."'),";
} else {
$link[] = $x[$n];
else $query .= "',NULL),";
}
$query = substr($query, 0, -1);//get rid of last comma
mysqli_query($query);
make the array to a string
$description = json_encode($desc);
$category = json_encode($cat);
$link = json_encode($link);
then insert these values to database
At the time of fetching
Use json_decode to get the array again from the string
Hi I have a jqgrid setup with a custom action button that sends selected rows to a database. I have everything working except that it posts the data 7 times per each row select where I only want it posted once per selected row. Please any and all help appreciated. JQGrid, How to post JSON string to PHP to Process and send to Database?
$decarr= array(
['id'] =>
518
['name'] =>
'Brochure for amada'
['id_continent'] =>
' Ramon'
['lastvisit'] =>
'5/15/2013'
['cdate'] =>
'5/29/2013'
['ddate'] =>
'5/31/2013'
['email'] =>
'Files'
)
PHP:
//First decode the array
$arr = $_POST["json"];
$decarr = json_decode($arr, true);
$count = count($decarr);
$values = array(); // This will hold our array values so we do one single insert
for ($x=0; $x < $count; $x++){
$newrec = $decarr;
$id = $newrec['id']; $id = mysql_real_escape_string($id);
$name = $newrec['name']; $name = mysql_real_escape_string($name);
$id_continent = $newrec['id_continent']; $id_continent = mysql_real_escape_string($id_continent);
$email = $newrec['email']; $email = mysql_real_escape_string($email);
$lastvisit = $newrec['lastvisit']; $lastvisit = mysql_real_escape_string($lastvisit);
$cdate = $newrec['cdate']; $cdate = mysql_real_escape_string($cdate);
$ddate = $newrec['ddate']; $ddate = mysql_real_escape_string($ddate);
// Create insert array
$values[] = "('".$id."', '".$name."', '".$id_continent."', '".$lastvisit."','".$cdate."','".$ddate."','".$email."' )";
}
// Insert the records
$sql = "INSERT INTO finish (id, name, id_continent, lastvisit,cdate,ddate, email)
VALUES ".implode(',', $values);
$result = mysql_query($sql, $con) or die(mysql_error());
?>
Fixed! I figured out the the variables were reiterated over and over with the other lines. Much love y'all.
//First decode the array
$arr = $_POST["json"];
$decarr = json_decode($arr, true);
$count = count($decarr);
for ($x=0; $x < $count; $x++){
$newrec = $decarr;
$id = $newrec['id'];
$name = $newrec['name'];
$id_continent = $newrec['id_continent'];
$email = $newrec['email'];
$lastvisit = $newrec['lastvisit'];
$cdate = $newrec['cdate'];
$ddate = $newrec['ddate'];
}
// Create insert array
$values[] = "('".$id."', '".$name."', '".$id_continent."', '".$lastvisit."','".$cdate."','".$ddate."','".$email."' )";
// Insert the records
$sql = "INSERT INTO finish (id, name, id_continent, lastvisit,cdate,ddate, email)
VALUES ".implode(',', $values);
$result = mysql_query($sql, $con) or die(mysql_error());
?>