I'm using the following snippet to break up an string array, then insert them into the database.
//split tags into individual words
$tag_array = explode(',', $tags);
foreach($tag_array as $tag){
addslashes($tag);
echo $tag." ";
$addTagsQuery = "INSERT INTO `my_blog`.`tags` (`id`, `name`) VALUES
('".$id."', '".$tag."');";
$tagsResult = $db->query($addTagsQuery);
if($tagsResult){
echo "tag added <br />";
}
else {
echo "tag was not added <br />";
}
}
My problem lies within a scenario where multiple tag (strings) are submitted. Unfortunately, only the first string in the array is inserted. Any insight as to why only the first string in the array is inserted into the MySQL database would be appreciated.
$id is not being incremented in the loop. Chances are you are getting a duplicate error, but for whatever reason it is not telling you (poor error handling?).
$addTagsQuery = "INSERT INTO `my_blog`.`tags` (`name`) VALUES
('".$tag."');";
If the ID is auto_incrementing, just omit and it will handle that for you.
You should use an auto-incrementing id instead of setting the id manually.
You don't need to run multiple insert statements. You can do it in one statement:
INSERT INTO my_blog.tags (name) VALUES ('tag1'), ('tag2')
The function addslashes doesn't modify the string so the way you are using it will have no effect.
You should use bind parameters instead of escaping strings.
$id is the id of the blog entry the tags are submitted for? Do you maybe have turned ID into a primary key or otherwise unique? That could cause the problem.
Try it like this:
$tag_array = explode(',', $tags);
$stmt = $db->prepare("INSERT INTO my_blog.tags (id, name) VALUES (?,?)");
foreach($tag_array as $tag){
if ($stmt->execute(Array($id, $tag))){
echo "tag added <br />";
}
else{
echo "tag was not added <br />";
}
$stmt->closeCursor();
}
Related
I would like to print the links of the images in the database.
https://www.yelp.com/biz_photos/zesty-gyros-and-deli-grand-rapids
I connected using CURL. I took the links to the pictures using Preg_match_all and listed them as "FOR". But I get the error in the INSERT process to the database.
Parse the data
preg_match_all('#<div class="photo-box photo-box--interactive" data-photo-id=(.*?)>#si', $site, $mydata);
for ($a=0; $a<count($mydata[1]); $a++) {
echo $mydata[1][$a].'<br>';
}
25 results are listed below. But I couldn't do mysql insert.
mysqli_query($link,"INSERT INTO myTable (field) VALUES ($mydata[1][$a])") or die(mysqli_error($link));
use single quotations marks around your $mydata[1][$a] and put in mysqli_real_escape_string function.
$value = mysqli_real_escape_string($link, $mydata[1][$a]);
mysqli_query($link,"INSERT INTO myTable (field) VALUES ('".$value."')") or die(mysqli_error($link));
I am new in android development I am sending a json array through android application and insert that data into MySQL database. The problem is that whenever I insert userJSON it entered every time with duplicate entries. So, I want to prevent duplicate entry in mysql how can this possible with php. Please help me to solve this problem.
json string from android side
'[{"type":"Outgoing","duration":"0","number":"XXXXXXXX","date":"Tue Dec 13 15:26:29 GMT+05:30 2016"},
{"type":"Outgoing","duration":"0","number":"XXXXXXXX","date":"Tue Dec 13 13:49:50 GMT+05:30 2016"}]';
Here is my php file for post json:
<?php
require_once('conn.php');
if($_SERVER['REQUEST_METHOD']=='POST')
{
$json = $_POST["usersJSON"];
echo $json;
if (get_magic_quotes_gpc())
{
$json = stripslashes($json);
}
$data = json_decode($json,true);
$query=mysqli_query($con,"SELECT *
FROM users
where number = '$number'
and type = '$type'
and date = '$date'
and duration= '$duration'");
if(mysqli_num_rows($query)>0) {
echo "already exist";
}
elseif(is_array($data))
{
$sql = "INSERT IGNORE INTO users (type, duration, number,date) values ";
$valuesArr = array();
foreach($data as $row)
{
$type = mysqli_real_escape_string( $con,$row['type'] );
$duration = mysqli_real_escape_string($con, $row['duration'] );
$number = mysqli_real_escape_string( $con,$row['number'] );
$date = mysqli_real_escape_string( $con,$row['date'] );
$valuesArr[] = "('$type', '$duration', '$number', '$date')";
}
$sql .= implode(',', $valuesArr);
if(mysqli_query($con,$sql))
{
echo 'Entry Added Successfully';
}
else
{
echo 'Could Not Add Entry';
}
}
//Closing the database
mysqli_close($con);
}
?>
Create a UNIQUE INDEX
Regardless of whatever programming language that you use, all the constraints on the data have to be enforced with in the database and not in your application layer. And the easiest way to do that is to add a UNIQUE KEY on the columns in question.
ALTER TABLE users ADD UNIQUE KEY all_columns(number,type,date,duration)
I am adding all the four columns to the unique index because you seem to want any column to have duplicate values taken in isolation. Please confirm if this is correct or choose the columns appropriately when creating the index.
Simply your code
With a unique key in place, your don't need that SELECT
$data = json_decode($json,true);
if(is_array($data))
{
$sql = "INSERT IGNORE INTO users (type, duration, number,date) values ";
....
}
Use Prepared Statements
Instead of a huge string concatenation as is being currently done and multple calls to mysqli_real_escape, you would be better of using prepared statements. You might even get a tiny increase in performance. However more importantly there is a maximum size of a string that can be passed through to the server, if you get a large array you might go beyond that.
I'm trying to insert multiple rows into MySql with only one INSERT INTO statement using the implode function. It was found from here.
My sample code goes below.
$sql[]=array();
$len=count($colour_id);
for($i=0;$i<$len;$i++)
{
$sql[]='('.$colour_id[$i].', '.$_POST['prod_id'].')';
}
$l=count($sql);
foreach($sql as $temp)
{
echo $temp;
}
echo 'insert into product_colour (colour_id, prod_id)values '.implode(',', $sql);
The above code simply initializes the $sql array and the foreach loop iterates over the array and displays the content of the array as follows.
Array(1, 1)(2, 1)(3, 1)
but while echoing the last statement (insert statement), it shows the following error.
Notice: Array to string conversion in C:\wamp\www\wagafashion\ProductColour.php on line 70
insert into product_colour (colour_id, prod_id)values Array,(1, 1),(2, 1),(3, 1)
(line no 70 means the last line in the above code snippet).
What changes should be made so that I can insert the values stored in the array into MySql database?
your code should be:
$sql=array();
$len=count($colour_id);
for($i=0;$i<$len;$i++)
{
$sql[]='('.$colour_id[$i].', '.$_POST['prod_id'].')';
}
$l=count($sql);
foreach($sql as $temp)
{
echo $temp;
}
echo 'insert into product_colour (colour_id, prod_id)values '.implode(',', $sql);
Take a look at the first line.
I see an extra comma in your statement (between Array and the first ().
Try changing the first line you have there to:
$sql = array();
What you had there sets the first element of $sql to a new array, it doesn't set $sql to a new array.
With this, your query should become: insert into product_colour (colour_id, prod_id)values (1, 1),(2, 1),(3, 1).
Your problem comes from the 1st line of this snippet : you're doing $sql[] = array(); you should write $sql=array(); if you want a good initializatino.
Don't forget to sanitize your input before sending it to Mysql.
i'm having trouble with the code below. it's been simplified to show the problem. i use a loop because the input names are identical and need to create multiple new rows in a mysql table. the problem is i'm using $_POST['name'][$i] and the table won't accept because it doesn't see it as 'text?, ...i think.
like i said, code's been greatly simplified.
for($i=0;$i<count($_POST['url']); $i++) {
$sql = 'INSERT INTO urls (url) VALUES ('. $_POST['url'][$i].')';
if(!mysql_query($sql)) {
echo "error " . mysql_error();
}
}
i tried to rememdy with this -
$sql = 'INSERT INTO urls (url) VALUES ('. '"'. $_POST['url'][$i].'"'. ')';
if i do this it works, there is no error
$sql = 'INSERT INTO urls (url) VALUES (' " hello " ')';
this is probably a newbie type mistake, right? thanks for any help with this.
A cleaner way (and the errors are fixed):
$urls = (isset($_POST['url']) && is_array($_POST['url'])) ? $_POST['url'] : array();
foreach($urls as $url) {
if(!is_string($url)) {
continue;
}
$sql = "INSERT INTO urls (url) VALUES ('" . mysql_real_escape_string($url) . "')";
if(!mysql_query($sql)) {
echo "error " . mysql_error();
}
}
Making sure the $_POST['url'] is an array will keep from trying to treat a non array (or non-existent key) as an array. The is_string is to protect from a user trying to throw in a sub array to get PHP to throw a "using array as string" notice. The escape is to avoid SQL injection, and the single quotes added are so MySQL knows it's a string.
You simply need to add quotes around the POSTed value in your MySQL query like below. Also, if you don't escape the input, it's a massive SQL injection vulnerability:
$data = mysql_escape_string($_POST['url'][$i]);
$sql = 'INSERT INTO urls (url) VALUES ("'.$data.'")';
The query breaks MySQL because MySQL thinks your post value is supposed to be numeric without the quotes.
It would be helpful to see that actual error message returned by mysql_error() but I think your problem is that you're not providing the $_POST value to the sql query as thought it's text.
try replacing
$sql = 'INSERT INTO urls (url) VALUES ('. $_POST['url'][$i].')';
with
$sql = "INSERT INTO urls (url) VALUES ('". mysql_real_escape_string($_POST['url'][$i]) ."')";
You need to escape your $_POST variables before you insert them via an SQL statement, preferably using the mysql_real_escape_string() function to fortify your query against SQL injection attacks.
Answer provided by Corbin is good - however try not to fire insert queries in a loop.
You could create the sql query as one string and then fire the insert query once.
You could change your insert statement from
insert into table (field) values(1);
insert into table (field) values(1);
To:
insert into table (field) values(1), (2), (3), (4)...
This is a more optimal solution - however mysql has a max length to which it can take sql statements - therefore use your best judgement.
try this statement
$sql = "INSERT INTO urls (url) VALUES ('". mysql_real_escape_string($_POST['url'][$i])."')";
I'm trying to add iterate through an object and add those object properties to mysql database. Using:
//This works
$sql = "CREATE TABLE $table ($ID int primary key auto_increment not null)";
mysql_query($sql);
//This works
function iterateObject($obj, $name='') {
foreach ($obj as $key=>$val) {
$myName = ($name !='') ? $name . "_" . $key : $key;
if ( is_object($val) || is_array($val) ) {
iterateObject($val, $myName);
} else {
//This works
$sql = ("ALTER TABLE home_timeline ADD COLUMN $myName VARCHAR(256);");
mysql_query($sql);
//This doesn't work
$sql2 = ("INSERT INTO home_timeline ($myName) VALUES ($val);");
mysql_query($sql2);
print "$myName - $val <br />";
}
}
}
The table is created and altered so that each iteration adds a new column to the table but when I try and add values to that column (second sql statement) everything is null and the script creates 20+ rows rather than having all the values appear on one row in the relevant column. Could someone help?
why not use functions like serialize() and unserialize() when converting objects to/from string?
second: if $val is string, then in the query put the string delimiters
"INSERT INTO home_timeline (`$myName`) VALUES ('$val');"
though inserting parameters via concatenation is a very bad practice prone to SQL injection.
If you have further problems, output the query before execution and put it here. You might be experiencing the case when you got a lot of columns which can't be nulls, and have no default values. Also output the table structure here.