here my code-
$things = mysql_real_escape_string(implode(',', $_POST['things']),$link);
$q = "INSERT INTO tblslider(src) VALUES ('".$things."')";
print_r($q);
$result = $mysqli->query($q) or die(mysqli_error($mysqli));
but my query is getting generated
INSERT INTO tblslider(src) VALUES ('4368122.jpg,5440051.jpg,1047428.jpg') but it should be
INSERT INTO tblslider(src) VALUES ('4368122.jpg'),('5440051.jpg'),('1047428.jpg') thats why it is taking it as one record not three.
You could do:
$things = array_map('mysql_real_escape_string', $_POST['things']);
$q = "INSERT INTO tblslider(src) VALUES ('". implode("'),('", $things)."')";
It generates (with my test data):
INSERT INTO tblslider(src) VALUES ('a.jpg'),('b.jpg'),('c.jpg')
I forgot: Only use functions like mysql_real_escape_string on the real data, not the SQL string. In your example you apply the function on the already concatenated data.
You have imploded things which is now an array, so you need to iterate over this with a foreach loop such as...
foreach ($things as $item) {
$q = "INSERT INTO tblslider(src) VALUES ('".$item."')";
echo '<br />'.$q;
$result = $mysqli->query($q) or die(mysqli_error($mysqli));
}
You could echo $q to make sure you're getting the queries right for each item also.
try this:
$formatVals = function($x){$rx = mysql_real_escape_string($x); return "('$rx')";};
$valString = implode(',', array_map($formatVals, $_POST['things']);
$sql = "INSERT INTO tblslider (src) VALUES $valString";
Related
i have a sql query to insert data without col names :
$sql = "INSERT INTO test_table VALUES (null,1,2,3) ";
if (mysqli_query($conn, $sql)) {echo 'success!';}else {echo 'failed!';}
I want to insert 1,2,3 as array , something like this:
$data = [1,2,3];
$sql = "INSERT INTO test_table VALUES (null,$data) ";
if (mysqli_query($conn, $sql)) {echo 'success!';}else {echo 'failed!';}
I tried php implode function too, but it didn't worked. Any help will be appreciated. Thank you!
You didn't provide the table structure that it is going into, but if all you are wanting to solve for is having the $data array split into constituent parts you could do it several ways:
a) implode(), although you already mentioned trying it, should work just fine:
$data = [1,2,3];
$sql = "INSERT INTO test_table VALUES (null,".implode(',',$data).")";
b) reference each array index:
$data = [1,2,3];
$sql = "INSERT INTO test_table VALUES (null,{$data[0]},{$data[1]},{$data[2]})";
That only works if you have a set amount of values in the array however.
c) loop over the array:
$data = [1,2,3];
$sql = "INSERT INTO test_table VALUES (null"
foreach($data as $value){ $sql .= ",$value"; }
$sql .= ")";
Hope that helps, if not please provide more details about the structure of both the data going in and the database table so we can better understand the issue.
I have the following code which is working fine,
But I need a way to batch process it and
Insert it all in one go.
for($i=0; $i<sizeof($my_array); $i++)
{
$sql = "INSERT INTO exclude_resource (id,resource_id,config_id)
VALUES(DEFAULT, '$my_array[$i]' ,'$insert_id')";
$command = $connection->createCommand($sql);
$result = $command->execute();
}
Your query should resemble something like (see mysql docs):
INSERT INTO table (field1, field2, field3)
VALUES
(value1a, value2a, value3a),
(value1b, value2b, value3b),
(value1c, value2b, value3c),
...
So put the values in an array, join them with commas, and execute the resulting query. Incorporated in PHP:
$values = array();
for($i=0; $i<sizeof($my_array); $i++) {
$values[] = "(DEFAULT, '$my_array[$i]' ,'$insert_id')";
}
$sql =
"INSERT INTO exclude_resource (id,resource_id,config_id) VALUES '.
join(',', $values);
$command = $connection->createCommand($sql);
$result = $command->execute();
$insert_id is needs to have a value, but thats the same with your code snippet.
If you have more than 5k or 10k rows to insert, you should run an INSERT in between and reset the array.
please help me out and sorry for my bad English,
I have fetch data , on basis of that data I want to update the rows,
Follows my code
I fetched data to connect API parameters
<?php
$stmt = $db->stmt_init();
/* publish store for icube*/
$stmt->prepare( "SELECT id,offer_id,name,net_provider,date,visible,apikey,networkid FROM " ."affilate_offer_findall_icube WHERE visible='1' ");
$stmt->execute();
mysqli_stmt_execute($stmt); // <--------- currently missing!!!
mysqli_stmt_store_result($stmt);
$rows = mysqli_stmt_num_rows($stmt);
$stmt->bind_result( $id, $offer_id, $name, $net_provider, $date, $visible,$apikey,$networkid);
$sql = array();
if($rows>0)
{
while($info = $stmt->fetch() ) {
$jsondataicube = file_get_contents('filename/json?NetworkId='.$networkid.'&Target=Affiliate_Offer&Method=getThumbnail&api_key='.$apikey.'&ids%5B%5D='.$offer_id.'');
$dataicube = json_decode($jsondataicube, true);
foreach($dataicube['response']['data'][0]['Thumbnail'] as $key=>$val)
{
$offer_id = $dataicube['response']['data'][0]['Thumbnail']["$key"]['offer_id'];
$display = $dataicube['response']['data'][0]['Thumbnail']["$key"]['display'];
$filename = $dataicube['response']['data'][0]['Thumbnail']["$key"]['filename'];
$url = $dataicube['response']['data'][0]['Thumbnail']["$key"]['url'];
$thumbnail = $dataicube['response']['data'][0]['Thumbnail']["$key"]['thumbnail'];
$_filename = mysqli_real_escape_string($db,$filename);
$_url = mysqli_real_escape_string($db,$url);
$_thumbnail = mysqli_real_escape_string($db,$thumbnail);
$sql[] = '("'.$offer_id.'","icube","'.$_thumbnail.'","'.$_url.'")';
}
}
As I store values which have to be inserted in 'sql'
now
$stmt->prepare( "SELECT offer_id FROM " ."affilate_offer_getthumbnail_icube ORDER BY 'offer_id' ASC");
$stmt->execute();
mysqli_stmt_execute($stmt); // <--------- currently missing!!!
mysqli_stmt_store_result($stmt);
$rows = mysqli_stmt_num_rows($stmt);
$stmt->bind_result($offer_id);
$sqlimplode = implode(',', $sql);
if($rows>0)
{
$query = "UPDATE affilate_offer_getthumbnail_icube WHERE offer_id='".$offer_id."' SET '".$sqlimplode."'";
$stmt->prepare( $query);
$execute = $stmt->execute();
}
else
{
$query= "INSERT INTO affilate_offer_getthumbnail_icube(offer_id, net_provider,logo2020,logo100) VALUES".$sqlimplode;
$stmt->prepare( $query);
$execute = $stmt->execute();
}`
`
Insert query working well,but how can I update all the data like insert query ?
My Answer is refering to a "set and forget"-strategy. I dont want to look for an existing row first - probably using PHP. I just want to create the right SQL-Command and send it.
There are several ways to update data which already had been entered (or are missing). First you should alter your table to set a problem-specific UNIQUE-Key. This is setting up a little more intelligence for your table to check on already inserted data by its own. The following change would mean there can be no second row with the same value twice in this UNIQUE-set column.
If that would occur, you would get some error or special behaviour.
Instead of using PHPMyAdmin you can use this command to set a column unique:
ALTER TABLE `TestTable` ADD UNIQUE(`tablecolumn`);
After setting up your table with this additional intelligence, you alter your Insert-Command a little bit:
Instead of Insert you can drop and overwrite your Datarow with
REPLACE:
$query= "REPLACE INTO affilate_offer_getthumbnail_icube
(offer_id, net_provider,logo2020,logo100) VALUES (".$sqlimplode.")";
See: Replace Into Query Syntax
Secondly you can do this with the "On Duplicate Key"-Commando.
https://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
$query= "INSERT INTO affilate_offer_getthumbnail_icube
(offer_id, net_provider,logo2020,logo100)
VALUES (".$sqlimplode.")
ON DUPLICATE KEY UPDATE net_provider = ".$newnetprovider.",
logo2020 = ".$newlogo2020.",
logo100 = ".$newlogo100.";";
Note: I think you missed some ( and ) around your $sqlimplode. I always put them around your implode. Maybe you are missing ' ' around strings as well.
Syntax of UPDATE query is
UPDATE table SET field1 = value1, field2 = value2 ...
So, you cannot pass your imploded array $sql to UPDATE query. You have to generate another sql-string for UPDATE query.
This is clearly incorrect:
$query = "UPDATE affilate_offer_getthumbnail_icube
WHERE offer_id='".$offer_id."' SET '".$sqlimplode."'";
If the intention is to INSERT offer_id='".$offer_id."' and then UPDATE ... SET offer_id = '".$sqlimplode."'";
You have to use two separate queries, one for INSERT and then another one for UPDATE
An Example:
$query = "INSERT INTO affilate_offer_getthumbnail_icube
(col_name) VALUES('".$col_Value."')";
//(execute it first);
$query2 = "UPDATE affilate_offer_getthumbnail_icube SET
col_name= '".$col_Value."'" WHERE if_any_col = 'if_any_Value';
//(execute this next);
Try this:
$sqlimplode = implode(',', $sql);
if($rows>0)
{
/*$fields_values = explode(',',trim(array_shift($sql), "()"));
$combined_arr = array_combine(['offer_id','net_provider','logo2020','logo100'],$fields_values);
$sqlimplode = implode(', ', array_map(function ($v, $k) { return $k . '=' . $v; }, $combined_arr, array_keys($combined_arr))); */
$query = "INSERT INTO affilate_offer_getthumbnail_icube(offer_id, net_provider,logo2020,logo100) VALUES".$sqlimplode." ON duplicate key update net_provider = values(net_provider),logo2020 = values(logo2020),logo100 = values(logo100)";
$stmt->prepare( $query);
$execute = $stmt->execute();
}
else
{
$sqlimplode = implode(',', $sql);
$query= "INSERT INTO affilate_offer_getthumbnail_icube(offer_id, net_provider,logo2020,logo100) VALUES".$sqlimplode;
$stmt->prepare( $query);
$execute = $stmt->execute();
}
Assuming I have an array as follows:
$array = array('first_value',
'second_value',
'thrid_value', 'and so on');
And a Column in which I'd want to insert those values, but each value in a separate row.
Would it it be possible to do that?
Obviously there are some answers to this one would be just loop thru the array elements and for every loop execute an insert statement, but that just seems unwise.
Or given that I'd have an ID column, that would help a lot(but I don't).
The amount of data to be introduced is not terribly large so the loop is perfectly viable, I just wanna make sure there isn't some easier way to do this that I may not be aware of.
You could use prepared statements; the first query will send the SQL statement and the subsequent calls will only send the data, thereby reducing the load:
$stmt = $db->prepare('INSERT INTO mytable (colname) VALUES (?)');
foreach ($array as $value) {
$stmt->execute(array($value));
}
If you're using PDO, such as the above example, make sure to disable prepared statement emulation.
// connect to database and store the resource in $connection
$array = array('first_value',
'second_value',
'thrid_value', 'and so on');
foreach($array as $value)
{
$value=mysqli_real_escape_string($connection,$value);
mysqli_query($connection,"INSERT INTO yourTABLE(columnName) VALUES('$value')");
}
You can put them all into a single INSERT statement with multiple VALUES lists.
$values = implode(',', array_map(function($v) use ($mysqli) {
return "'" . $mysqli->real_escape_string($v) . "'"; },
$array));
$query = "INSERT INTO yourTable (Column) VALUES $values";
$mysqli->execute($query) or die ($mysqli->error);
From mysql manual for insert,you may try this:
INSERT INTO yourtable (column_name) VALUES (value_a), (value_b), (value_c);
$array = array('first_value','second_value','third_value');
$SQL = "INSERT INTO `table` (column) VALUES('".implode("'),('",$array)."')";
OR
$values = '';
foreach($array as $val){
$values .= !empty($values)? ",('{$val}')" : "('{$val}')";
}
$SQL = "INSERT INTO `table` (column) VALUES{$values}";
<?php
$m = "arushi";
$em = "SELECT emailid FROM tblregister WHERE name='$m'";
$q = mysql_query($em);
$n = mysql_fetch_assoc($q);
$fullName = mysql_real_escape_string($_POST['name']);
$address = mysql_real_escape_string($_POST['address']);
$mobNo = mysql_real_escape_string($_POST['dinner']);
$summary = "jsf";
$sql = "INSERT INTO tbljcustomer VALUES('$m', '$n', '$fullName',
'$address','$mobNo', '$summary')";
if(!(mysql_query($sql)))
{
echo "Sorry!!! we were unable to process please try again";
}
else
{
echo "customized";
}
?>
on executing this everything works fine except that it doesn't fetch emailid from tblregister rather it displays just Array or sometimes resource id#10. Thanks in advance
Use this:
$n=mysql_fetch_assoc($q);
$emailid = $n['emailid'];
and your query will change to
$sql="insert into tbljcustomer values('$m', '$emailid', '$fullName','$address','$mobNo', '$summary')";
$n is an associative array. Look at the documentation for mysql_fetch_assoc. Use var_dump($n); if you want to see the structure of the array. From the documentation:
mysql_fetch_assoc returns an associative array of strings that corresponds to
the fetched row, or FALSE if there are no more rows.
replace
$n
with
$n['emailid']
in your insert query
it will be
$email = $n['emailid'];
$sql="insert into tbljcustomer values('$m', '$email', '$fullName',
'$address','$mobNo', '$summary')";
replace
$sql = "INSERT INTO tbljcustomer VALUES('$m', '$n', '$fullName',
'$address','$mobNo', '$summary')";
with
$sql = "INSERT INTO tbljcustomer VALUES('$m', '".$n['emailid']."', '$fullName',
'$address','$mobNo', '$summary')";
You have to use : $n['emailid']
mysql_fetch_assoc return an array
try:
insert into tbljcustomer values('$m', '".$n['emailid']."', '$fullName',...