Array into mysql row - php

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);
}

Related

PHP / MySQL: Print specific value from array (query result) based on its ID [duplicate]

This question already has answers here:
Generate PHP array from MySQL with key value from "id" column
(4 answers)
Closed 3 years ago.
I use the following PHP lines to query data from a MySQL table.
I want to store the query results in an array and then later on the same page print specific values from this array based on their ID.
I am new to PHP and hope someone can help me with an explanation on what I am doing wrong or missing here. I am assuming I create the array wrongly.
My PHP (relevant part, variables are defined earlier on this page):
$con = mysqli_connect($host_name, $user_name, $password, $database);
$result = mysqli_query($con, "SELECT id, $col FROM $table ORDER BY id");
$rows = array();
if($result)
{
while($row = mysqli_fetch_array($result))
{
print_r($row);
}
}
var_dump($rows);
My current array (when printed as above):
Array ( [0] => testid1 [id] => testid1 [1] => testval1 [en] => testval1 ) Array ( [0] => testid2 [id] => testid2 [1] => testval2 [en] => testval2 ) Array ( [0] => testid3 [id] => testid3 [1] => testval3 [en] => testval3 ) array(0) { }
Example:
E.g. I want to print the value for the item with ID = "testid2" from this array.
In this case the printed value should be "testval2".
Many thanks in advance,
Mike
Store your data as:
for
(
$set = array();
$row = $result->fetch_assoc();
// use value of `id` as the key in your `$set`
$set[$row['id']] = $row
);
print_r($set);
// later:
$id = 1;
echo $set[$id]['en'];
// or
echo $set[$id][$lang];
You can just use fetch_all() and then column search
$con = mysqli_connect($host, $username, $password, $database);
$result = mysqli_query($con, "SELECT id, $lang FROM $table ORDER BY id");
$set = $result->fetch_all(MYSQLI_ASSOC);
$key = array_search('testid2', array_column($set, 'id'));
echo $set[$key]['en'];
You can use array_combine() with array_column() to convert the query output (in rows and columns) to key-value format (key being the id, and value being the en column):
// $set array is populated using fetch_assoc
// create a new array using $set
$modified_set = array_combine(array_column($set, 'id'),
array_column($set, 'en'));
// Now, you can access the en value for a specific id like this:
// eg: for id = testid2
echo $modified_set['testid2']; // will display testval2

PHP SQL statement using REGEXP to fetch multiple values

How do I use REGEXP to fetch multiple data from the array $vall.
I referred a sample code from:
PHP sql statement where clause to multiple array values
Some of the sample data: CGCG-0025-0,CGCR-0003-0,CGRQ-0163-0
foreach ($list as $value) // this $list is from another array
{
$part = $value[3];
$vall[] = $value[3]; // $list1 is an empty array
}
$partnumber =[];
foreach($vall as $v)
{
$partnumber[] = "*.".$v.".*";
print_r(array_values($partnumber)); // these are some of the values Array ( [0] => *.CGCG-0025-0.* ) Array ( [0] => *.CGCG-0025-0.* [1] => *.CGCG-0025-0.* ) Array ( [0] => *.CGCG-0025-0.* [1] => *.CGCG-0025-0.* [2] => *.CGCR-0003-0.* )
}
foreach($partnumber as $x)
{
echo '<br>'.$partnumber; // shows 'Array' on each lines
}
$fsql="select * from Error where RptDatime = 201706091000 and partnumber REGEXP '".implode("|",$partnumber)."'";
//example 1 $fsql="select * from MPdError where RptDatime = 201706091000 and partnumber = ('CGRQ-0057-0') ";
//example 1 shows the correct data but i need multiple partnumber
$getResults = $conn->prepare($fsql);
$getResults->execute();
$results = $getResults->fetchAll(PDO::FETCH_BOTH);
foreach($results as $row)
{
$mac = $row['Machine'];
$id = $row['Id'];
echo '<br><br><br>ID:'.$id.'<br>Machine Number :'.$mac;
}
Though this may not be a good solution as it contains a huge security risk, I will still post it based on what is needed above.
REGEXP is not needed for data that are not complex in design.
$fsql = "select * from Error where RptDatime = 201706091000 and partnumber in ('" . implode("','", $vall) . "');"

Insert array to mysqldb

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.

php getting values out of an array with same 'id' number

I'm having trouble getting the value out of an array
Array
(
[0] => id
[column_name] => id
)
Array
(
[0] => businessType
[column_name] => businessType
)
Array
(
[0] => name
[column_name] => name
)
Array
(
[0] => city
[column_name] => city
)
...
I'm getting those values from
mysql_query("
SELECT column_name
FROM information_schema.columns
WHERE table_name='businessUpgrade'
")
And in my while loop
while($row = mysql_fetch_array($result)){
while($column = mysql_fetch_array($colName)){
if($row[$i] == 1){
//here comes the missing part
}
$i++;
}
}
I tried diffrent things, but according to print_r, the values I need to get have the same number of id (0). Is there any way, I can get the values out of this array.
I found that I should do it with foreach, but somehow everything I try it fails.
There is no need to use 2 while loops.
The $row array is an associative array, so you can use...
$columns = array();
// {query}
while($row = mysql_fetch_array($result)) {
$columns[] = $row['column_name'];
}
var_dump($columns);
Your $columns array now contains an index of all the columns. It's a zero-index, so these can be pulled individually using:
echo $columns[0]; // The first column from the query "id"
echo $columns[2]; // The third column from the query "name"
You can also loop this array as needed.
foreach ($columns as $id => $column) {
if ($id == 0) {
// Do something with the first column:
echo $column;
} elseif ($id == 2) {
// Do something with the third column:
echo $column;
}
}
try this
$res = mysql_query("
SELECT column_name
FROM information_schema.columns
WHERE table_name='businessUpgrade'
");
while($r = mysql_fetch_row($res)){
$arr[]=$r;
}
NOTE . do not use mysql. Try mysqli or PDO instead.
And with this:
while($row = mysql_fetch_array($result)){
while($column = mysql_fetch_assoc($colName)){
if(($column['0'] == $row[$i]) && ($row[$i] == 1)){
//something like this???
}
}
$i++;
}
Your question is a bit messy XD.....i hope this helps anyway.

save data to table by serialize and php

i am use serialize to get data from page to another page by ajax like this :-
var txtCoursesNamewith = $('#with').serialize();
and get it on php page like this :-
$txtCoursesNamewith = ($_POST['txtCoursesNamewith']);
$unserializedData = array();
parse_str($txtCoursesNamewith,$unserializedData);
when print this array its like this :-
[txtCoursesNamewith] => Array
(
[0] => qq
[1] => ff
)
i need to insert this array to my table by foreach, i am try like this :-
foreach ($unserializedData as $value => $key )
but it store in database like this " Array ", how can i store (qq,ff) on table.
You can use implode() function.
$txtCoursesName = implode(",", $txtCoursesNamewith);
Then insert $txtCoursesName as a string.
use this
foreach ($unserializedData as $key => $val ) {
//your query insert into table_name(column_name) values ($val)
}
'Array' in dbrow means you are inserting unserialized array.
instead of:
INSERT INTO table (column) VALUES ({$value})
do:
INSERT INTO table (column) VALUES ({serialize($value)})
Iterate the query in loop or construct an array and execute a single insert query
foreach ($_POST['txtCoursesNamewith'] as $key => $val ) {
//your query insert into table_name(column_name) values ($val)
}

Categories