This is my current output from a preg_match_all
Array
(
[0] => Array
(
[0] => 2 Sentence text here
)
)
Array
(
[0] => Array
(
[0] => 3 Sentence text here.
[1] => 4 Sentence text here.
[2] => 5 Sentence text here.
)
)
I'm trying to insert each output as a new row in a table but it's thinking that each [0] [1] [2] is a new column. How do I insert the array into mysql?
$query = "INSERT INTO table (col1) VALUES ";
foreach ($matches as $item) {
$query .= "('".$item[0]."'),";
}
$query = rtrim($query,",");
$result = mysql_query($query);
The above obviously only inserts the first row in of the array
Well, you have an array in other array, so...
$query = "INSERT INTO table (col1) VALUES ";
if(!empty($matches))
{
foreach ($matches as $item) {
foreach ($item[0] as $items) {
$query .= "('".$items."'),";
}
}
}
if(!empty($matches))
{
foreach ($matches[0] as $item) {
$query .= "('".$item."'),";
}
}
Depends on how you are getting your array matches.
$query = rtrim($query,",");
$result = mysql_query($query);
That way you'll get this query:
INSERT INTO table (col1) VALUES ('2 Sentence text here'), ('3 Sentence text here'), ('4 Sentence text here'), ('5 Sentence text here')
Which is a valid way to insert several values in one column with a single INSERT statement.
Note:
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
Related
I am using PDO statement like below
$sql1 = "select food_typename from foodtypes WHERE 1";
$statement1 = $pdo->prepare($sql1);
$statement1->execute();
$results1 = $statement1->fetchAll(PDO::FETCH_ASSOC);
print_r($results1);
I am getting output as below:
Array
(
[0] => Array
(
[food_typename] => Punjabi
)
[1] => Array
(
[food_typename] => Indian
)
)
I want it be like
Array('Punjabi','Indian')
Any suggestions please?
If you're running PHP >= 5.5
$results = array_column($results1, 'food_typename');
If you're running earlier versions of PHP,
$results = array_map(
$results1,
function($value) {
return $value['food_typename'];
}
);
Though I don't really understand why you can't work with the original array in the first place
You can use array_map but foreach works just as well and actually runs faster than array_map for cases like this:
// Set a test array.
$results1 = array();
$results1[] = array('food_typename' => 'Punjabi');
$results1[] = array('food_typename' => 'Indian');
// Set the final reults in an array.
$results_final = array();
foreach ($results1 as $results1_value) {
$results_final[] = $results1_value['food_typename'];
}
// Dump the line array for debugging.
echo '<pre>';
print_r($results_final);
echo '</pre>';
And the output of that would be:
Array
(
[0] => Punjabi
[1] => Indian
)
The query way:
SELECT GROUP_CONCAT(food_typename), 1 AS dummy
FROM foodtypes
GROUP BY dummy
Then you need to retrieve the first field of the only record you will get back from mysql, and turn it into an array: see return group_concat data as array
I have the following array named $people and this is the output I get with a print_r():
Array (
[0] => "Zyzz","fitness","21","Male"
[1] => "Arnold","bodybuilder","23","Male"
[2] => "Jeff","fitness","19","Male"
)
How can I insert these values to my MySQL Database?
I have a vague idea wich is:
$sql=" INSERT INTO famous (name,type,age,sex) VALUES ($people)";
mysql_query($sql);
How can I accomplish this correctly?
Thanks in advance
What if you made a foreach loop like
foreach($people as $person)
And then used the $person variable in your query. The foreach will just iterate your array. However, the values of your array don't seem right. Are you sure that is the exact print_r?
$sql = "INSERT INTO famous (name,type,age,sex) VALUES ";
foreach($people as $p)
{
$sql .= '('.$p.'),';
}
$sql = rtrim($sql,',');
mysql_query($sql);
Just do the following:
foreach($people as &$person) {
$person = '('.$person.')';
}
$sql = "INSERT INTO famous (name,type,age,sex) VALUES " . implode (",", $people);
mysql_query($sql);
I'm trying to insert the following array ( from a html form ) but i believe i'm working with this array in a very awful way
The array:
Array (
[0] => Array (
[0] => local
[1] => file
[2] => a
)
[1] => Array (
[0] => remote
[1] => image
[2] => b
)
)
Actual code:
<?php
if(isset($_POST)==true && empty($_POST)==false){
$dataa = ($_POST['code_list']);
}
$data = array_chunk($_POST['code_list'],6);
foreach ($data as $type=>$ba) {
echo "INSERT INTO table(f1, f2, f3,) values (";
foreach ($ba as $a) {
echo "'$a',";
}
echo ");<br>";
}
?>
current output:
INSERT INTO table(f1, f2, f3,) values ('local','file','a',);
INSERT INTO table(f1, f2, f3,) values ('remote','image','b',);
What would be a decent way to do it?
EDIT : No need to show how to connect to a database, i just need to deal with the array data.
A few comments:
You should switch to PDO or mysqli and use prepared statements with bound variables. Now you have a serious sql injection problem;
You can combine multiple inserts in one insert statement: INSERT ... VALUES ('local','file','a'),('remote','image','b'),(etc.).You could also prepare your statement once and then execute it multiple times but combining would be more efficient, especially with a growing number of inserts.
A simple (uncomplete and untested...) example in PDO:
$sql = 'INSERT INTO table(f1, f2, f3) VALUES ';
$values = array();
$valCount = 1;
foreach ($data as $type=>$ba) {
$row = array();
foreach ($ba as $a) {
$val = ":value{$valCount}";
$row[] = $val;
$values[$val] = $a;
$valCount++;
}
$sql .= '(' . implode(', ', $row) . '),';
}
$sql = rtrim($slq, ',');
// execute the sql statement using PDO
$stmt = $db->prepare($sql);
$stmt->execute($values);
At the end of the loop and the trim, the sql should look like:
INSERT INTO table(f1, f2, f3) VALUES (:value1, :value2, :value3),(:value4, :value5, :value6)
And the value array should have the keys of :value1 - :value6 with your values.
Hello i have a dynamic form that can change field names upon user selection. i would like for the form result to be inserted into one mysql row.. i create an array as follows:
<?php
include_once 'dbconnect.php';
if (isset($_POST['item_name'])) {
$table = $_POST['ItemTypeSelect'];
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[] = array($columnName => $results);
}
}
mysql_query("INSERT INTO $table (`$columnName`) VALUES ('$results') ")or die(mysql_error());
}
?>
my array result are
(
[0] => Array
(
[Server_id] =>
)
[1] => Array
(
[Server_IP_Address] => 12345
)
[2] => Array
(
[Server_IP] => 12345
)
[3] => Array
(
[Server_Name] => dad
)
)
How can i have the array be inserted in one table row and reference the $results and the field value and $columnName as the field value.
You could use a few php built in functions:
function put_quotes(&$item){
$item = "'$item'";
}
$columns = implode(",",array_walk(array_keys($_POST),'put_quotes'));
$values = implode(",",array_walk(array_values($_POST),'put_quotes'));
mysql_query("INSERT INTO $table (columns) VALUES ($values) ")or die(mysql_error());
Where :
array_walk executes a function over all array, here put quotes over the item.
array_keys gets the keys from an array
array_values gets the values from an array
implode joins an array to a string with a separator
Use PDO because mysql_* functions are depreceated.
Connect to MySQL in PDO :
$db="database";
$host="127.0.0.1";
$usr="username";
$pass="password";
$dbh=new PDO("mysql:dbname=$db;host=$host", $usr, $pass);
First convert the array to JSON and save it on the table :
$json=json_encode($array);
$sql=$dbh->prepare("INSERT INTO ? (?) VALUES (?)");
$sql->execute(array($table,$columnName,$json));
If you want to retrieve the array back, decode the JSON data got from table:
$sql=$dbh->prepare("SELECT ? FROM ?");
$sql->execute(array($columnName,$table));
while($r=$sql->fetch()){
$array=json_decode($r[$columnName],true);
print_r($array);
}
I'm trying to preg_match_all the first 12 digit number found in a mysql field, and insert that number in another field, looping through all results from the Select statement.
I have the following, which puts only the first result it finds in all the fields, so every field3 gets the same 12 digit number inserted, that 12 digit number being from the lowest unique ID field found by the Select statement. Any help with this would be greatly appreciated.
<?php
$query = mysql_query("SELECT * FROM `dbase`.`table` WHERE field1 IS NOT NULL AND field3 IS NULL");
$regexp ='/[0-9]{12}/';
while ($row = mysql_fetch_assoc($query)){
$result=($row["field1"]);
preg_match_all($regexp,$result,$matches,PREG_PATTERN_ORDER);
foreach($matches[0] as $match => $where){
$id=($row["field2"]);
$sql="UPDATE `dbase `.`table ` set field3 = $where WHERE field2 = '$id'";
mysql_query($sql);
}
}
?>
I added
print_r( $matches );
and the output was an array with one result, the number being place in all the fields:
Array
(
[0] => Array
(
[0] => 290970571788
)
)
The curly bracket change fixed the print_r output to show the the list of 12 digit numbers in this format (only first two are shown):
Array
(
[0] => Array
(
[0] => 151104658286
)
)
Array
(
[0] => Array
(
[0] => 271249191324
)
)
Thanks for that.
Utilizing the answers and suggestions given here, I've edited the code to show the final working version. The last big issue was getting the 2nd select statement to use the array result, properly looping and inserting each value in the proper row. Also cleaned up the 1st select statement and changed from preg_set_order to preg_pattern_order.
It shouldn't be
{while ($row = mysql_fetch_assoc($query))
}
but
while ($row = mysql_fetch_assoc($query)) {
}
You don't want to create code block with while statement but you want to provide code block for it.
And also you're using same WHERE condition in SELECT and UPDATE so it'll update all selected rows with same value (all will match that condition).