How to dump PHP object into an SQL Table? - php

I'm wondering if there is a quick way to do the following:
I have a PHP object with multiple attributes. For example
$person;
$person->height = 165;
$person->name = 'john';
I would like to dump this into an SQLite MySQL DB while creating each column automatically from the attribute names of the PHP object. So for example, if I were to dump the above object into mySQL, it would look something like this:
Table : people
Name(Column, VARCHAR) - "John"
Height(Column, INT) - 165
The reason I am asking this is because the number of attributes is growing constantly, and having to create and manage the table columns manually is a lot of work. I am wondering if there is an automated way of doing this.

First you need to convert object into array and then you can iterate through it and can create table and insert values in it.
Something like below:
Step 1: Convert object to array
Step 2: Get keys(fields) and values out of array
Step 3: Generate sql queries
<?php
//Step 1: convert object to array
//$persion = (array) $yourObject;
//Step 2: get keys(fields) and values out of array
$person = array(
"height" => "165",
"name" => "john",
"age" => "23"
);
function data_type($val) {
if(is_numeric($val)) {
return "int";
}
else {
return "varchar(15)";
}
}
//Step 3: sql query, only including sql query
function create_table($person) {
$create = "CREATE TABLE IF NOT EXISTS people";
$ctr = 0;
foreach($person as $key => $value) {
if($ctr == 0) {
$field_query = $key." ".data_type($value);
} else {
$field_query .= ", ".$key." ".data_type($value);
}
$ctr++;
}
echo $create .= " (".$field_query.")";
echo "<br/>";
}
create_table($person);
function insert_table($person) {
$ctr = 0;
foreach($person as $key => $value) {
if($ctr == 0) {
$field_query = $key;
$value_query = $value;
} else {
$field_query .= ", ".$key;
$value_query .= ", ".$value;
}
$ctr++;
}
echo $insert = "INSERT INTO people"." (".$field_query.") VALUES (".$value_query.")";
}
insert_table($person);
?>
Hope this will help you in some way(y).

Related

how to use two arrays or three arrays in the foreach loop in php for insert to database

How to insert multiple arrays with a foreach in rows of databases?
It's not a problem with an array, but my problem is to use two arrays or more.
my php code:
$checkBox1 = implode(',', $_POST['goinput1']);
$checkBox2 = implode(',', $_POST['goinput3']);
$mark3=explode(',', $checkBox1);
$mark4=explode(',', $checkBox2);
foreach($mark3 as $out3)
{
$sql_sub = "INSERT INTO sub_forms
(bord_mizban,bord_mihman)
VALUES ('$out3','$out4')";
if ($conn->query($sql_sub) === TRUE) {
} else {
}
}
**
I want the out 4 variable insert to the database with the out 3 variable
**
Iterate over $mark3 using indexes ($key) and get element under same key:
foreach($mark3 as $key => $out3)
{
echo $out3 . '; ' . $mark4[$key];
}
The short answer is:
foreach($mark3 as $key => $out3) {
$values = "'$out3."','".$mark4[$key]."'"
$sql_sub = "INSERT INTO sub_forms
(bord_mizban,bord_mihman)
VALUES ($values)";
if ($conn->query($sql_sub) === TRUE) {
} else {
}
}
That would fix your actual question. However, there is a better way to do this, with only 1 sql query.
foreach($mark3 as $key => $out3) {
$valuesArray[] = "('$out3."','".$mark4[$key]."')" // this makes an array of your value sets.
}
$values = join(", ", $valuesArray) // this joins your array to one string, with each entry separated by a comma.
$sql_sub = "INSERT INTO sub_forms
(bord_mizban,bord_mihman)
VALUES $values";
if ($conn->query($sql_sub) === TRUE) {
} else {
}

PHP update statement with arrays

Hi so I have an insert statement which works well, but need to create a separate update function which uses array keys and array values, which would be quite like the insert function but updates.
I have this for my insert
$sql = "INSERT INTO $tablename (".implode(",", array_keys($DATA).")" . " DATA ('".implode("','",array_values($DATA))."')";
connect()->query($sql);
This is what I have for my update so far but am stuck with it,
<?php
function updatethis (array $id, array $values, $tablename)
{
$sql = "UPDATE $tablename SET (".implode(",", array_keys($DATA)).")" . " DATA ('".implode("','",array_values($DATA))."')";
dbconnect()->query($sql);
}
?>
Therefore I would like help on the update feature please .
So I am getting an error with the UPDATE syntax
This is the part i am struggling with, i cna give further explanation, but i must have put in the wrong syntax to update the database after i click edit on the index page it calls the function just the syntax is incorrect.
also its php to mySQL
index page for PHP updatee fucntion
{
$values = array();
$idValues = array($idColumn => $id);
foreach($_POST as $key => $value)
{
if(!empty($value) && ($value != "Submit"))
{
$values[$key] = $value;
}
}
$result = update($idValues, $values, $tableName);
}
Edit: Error I am getting
edit has not been successfull from below
if(isset($_POST['Submit']))
{
if($result>0)
{
echo 'Edit has been successful. Return to index page';
}
else
{
echo 'Edit has not been successful.';
}
}
My code
function updateAll(array $id, array $values, $tablename)
{
$sIDColumn = key($id);
$sIDValue = current($id);
$arrayValues = $values;
array_walk($values, function(&$value, $key){
$value = "{$key} = '{$value}'";
});
$sUpdate = implode(", ", array_values($values));
$sql = "UPDATE {$tablename} SET {$sUpdate} WHERE {$sIDColumn} = '{$sIDValue}'";
connect()->query($sql);
}
My aim: takes the input of the unique identifier of the row to be edited as an array of 1 then the value plus the name of the column representing the primary key, an array containing the values indexed by the column names as well as a string representing the table name useing array_keys and array_vaules like th insert but to update
You cannot UPDATE in the same way of INSERT. It should be like this :
$valueSets = array();
foreach($values as $key => $value) {
$valueSets[] = $key . " = '" . $value . "'";
}
$conditionSets = array();
foreach($id as $key => $value) {
$conditionSets[] = $key . " = '" . $value . "'";
}
$sql = "UPDATE $tablename SET ". join(",",$valueSets) . " WHERE " . join(" AND ", $conditionSets);
See details here http://dev.mysql.com/doc/refman/5.7/en/update.html
I believe the pattern you are using is incorrect?
UPDATE table SET (rows) DATA ('values');
I think updates look more like this:
UPDATE table SET row1 = 'value1', row2 = 'value2';
In which case, this may be closer to what you are looking for.
function updatethis(array $id, array $values, $tablename)
{
$sIDColumn = key($id);
$sIDValue = current($id);
$arrayValues = $values;
array_walk($values, function(&$value, $key){
$value = "{$key} = '{$value}'";
});
$sUpdate = implode(", ", array_values($values));
$sql = "UPDATE {$tablename} SET {$sUpdate} WHERE {$sIDColumn} = '{$sIDValue}'";
dbconnect()->query($sql);
}
Using it, I get this query:
$testArray = array(
"id" => 19,
"username" => "test"
);
updatethis(array("id" => 9), $testArray, "users");
UPDATE users SET id = '19', username = 'test' WHERE id = '9'
I hope this at least helps but when it comes to databases, I only know MySQL and it is possible you are using another language.
I think you can try something like this :
$champs : Array of fields to update
$valeurs : Array of value to update fields
$conditions : Array of conditions
protected function modify($table,$champs,$valeurs,$conditions){
$Requete = "UPDATE ".$table." SET ";
$nbChamps = count($champs);
$nbValeurs = count($valeurs);
if($nbChamps == $nbValeurs){
for($i = 0; $i < $nbChamps ; $i++){
if($i < ($nbChamps - 1)){
if(is_numeric($valeurs[$i]))
$Requete = $Requete.$champs[$i]." = ".$valeurs[$i].",";
else
$Requete = $Requete.$champs[$i]." = '".$valeurs[$i]."',";
}
else
if(is_numeric($valeurs[$i]))
$Requete = $Requete.$champs[$i]." = ".$valeurs[$i]." ";
else
$Requete = $Requete.$champs[$i]." = '".$valeurs[$i]."' ";
}
$Requete = $Requete.$this->genereConditions($conditions);
$this->db->query($Requete);
}
else
throw new Exception("Le nombre de champs n'est pas identique au nombre de valeurs", 1);
}
private function genereConditions($conditions){
$condition = "WHERE ";
for($i = 0 ; $i < count($conditions); $i++){
if($i < (count($conditions)) - 1)
$condition = $condition.$conditions[$i]." AND ";
else
$condition = $condition.$conditions[$i];
}
return $condition;
}

php array keys array values insert

Update:
Index page is performs the action of the function,
Below is my current code, above this i have a fetch all which works well, but this insert isnt working as it doesn't insert into the database, is it because i need an update all after it before i can test insert?
<?php
function insert(array $values, $tablename)
{
$key = "";
$val = "";
foreach($values as $keys=>$record){
if($keys == ""){
$key .= $keys;
}
else{
$key .= ','.$keys;
}
if($val == ""){
$val .= $record;
insert into $tablename($keys)values($val);
}
else{
$val .= ','.$record;
insert into $tablename($keys)values($val);
}
}
}
?>
Here you have few mistakes
function insert(array $values, $tablename)
$sql = "INSERT INTO $tablename ("$vaules". implode(",", array_keys($pr1)) .") VALUES ('$vaules$, ". implode(",", array_values($pr1)) ")";
Maybe you want something like this
function insert(array $values, $tablename){
$sql = "INSERT INTO $tablename (".implode(",", array_keys($values)).") VALUES ('".implode("','",array_values($values))."')";
}
You are using some $pr1 value that do not exist in function. But also I woul like that you will do something with this query in this function.
let me to be specific.
for example you have a table employee with emp_id, emp_first_name,emp_last_name and email_id fields.
and you have array for values like this
$values = array(
emp_first_name => John,
emp_last_name => Malick,
email_id => john#gmail.com
)
now call insert function from index page using below code
first of all include file in which you placed a insert function.
for example in File1.php you placed a insert function then
include 'File1.php';
$result = insert('employee',$values);
now in insert function,
function insert($tablename,$values){
foreach($values as $keys=>$record){
$key_array[] = $keys;
$myvalue = $record;
if($record == ''){
$value_array[] = "'NULL'";
}else{
$value_array[] = "'".$myvalue."'";
}
}
$keys = implode(",", $key_array);
$values = implode(",", $value_array);
insert into $tablename($keys)values($val);
}

mongodb in php-insert array to mongo db collection

i use mongodb in php and have a problem to insert $subitems array to mongodb collection.
php code:
if($_SERVER["REQUEST_METHOD"] == "POST"){
$errors = array();
$alarm = array();
$item_name = data::test_input($_POST["item_name"]);
$folder_name = data::test_input($_POST["folder_name"]);
$subitem_num = data::test_input($_POST["subitem_num"]);
for($i=1;$i<=$subitem_num;$i++){
${"subitem_name$i"} = data::test_input($_POST["subitem_name".$i]);
${"subitem_file$i"} = data::test_input($_POST["subitem_file".$i]);
if(count($errors)==0){
$subitems = array(${"subitem_name$i"}=>${"subitem_file$i"});
}
}
if(empty($item_name)){
$errors['item_name']= "insert item";
}
if(empty($folder_name)){
$errors['folder_name']= "insert folder";
}
if(count($errors)==0){
$query = array(
"item_name" => $item_name,
"status" => 0,
"folder_name" => $folder_name,
"subitem" => $subitems
);
$result = items::insert($query);
if($result) $alarm['success_additem'] = "submit done";
}
}
i want record values to mongodb collection like this:
{ "_id" : ObjectId("542e71b333e916542a00002e"), "item_name" : "users management", "status" :0, "folder_name" : "users", "subitem" : { "a" : "a.php","b" : "b.php" },"c" : "c.php" }
how to write php code for insert to mongodb collection?
I assume your problem is that the subitem field in your document never contains more than a single key/value pair when inserted into the database.
for($i=1;$i<=$subitem_num;$i++){
${"subitem_name$i"} = data::test_input($_POST["subitem_name".$i]);
${"subitem_file$i"} = data::test_input($_POST["subitem_file".$i]);
if(count($errors)==0){
$subitems = array(${"subitem_name$i"}=>${"subitem_file$i"});
}
}
Based on that for loop, you're over-writing $subitems in each iteration. I assume you mean to assign a key within it, in which case you'd be better served with the following:
$subitems = array();
for($i = 1; $i <= $subitem_num; $i++) {
$key = data::test_input($_POST["subitem_name".$i]);
$value = data::test_input($_POST["subitem_file".$i]);
if (count($errors) == 0) {
$subitems[$key] = $value;
}
}
For the record, I have no idea why you're checking $errors here, as it's assigned once at the top of this function and doesn't appear to be modified within the for loop; however, I left it in place so it lines up with the original example you've provided.
Also, there is really no reason to use dynamically-named variables here. Fixed terms such as $key and $value make the code much more readable.

For each PHP multi dimension array returns 1 character

For some reason the both code upon killing the query var returns:
SELECT client_fname FROM client WHERE c=:l AND f=:n
Instead of:
SELECT client_fname FROM client WHERE client_id=:id AND client_id=:fname
Notice that only the first character of the column name strings is output.
Where am I going wrong? :S
PHP 5.4, will be using PDO SQL.
public function getField($_field, $_id, $_type) {
$_args = array(
array($_type.'_id', 'id'),
array($_type.'_fname', 'fname')
);
//var_dump($_args);
echo $this->dbSelect($_type.'_'.$_field, $_type, $_args);
}
protected function dbSelect($_select, $_from, $_args) {
$i = 0; //var_dump($_args);
$query = 'SELECT '.$_select.' FROM '.$_from.' WHERE ';
foreach ($_args as $_where) {
if($i == 0) {
$query .= $_where[$i][0] .'=:'. $_where[$i][1];
} else {
$query .= ' AND '.$_where[$i][0] .'=:'. $_where[$i][1];
}
$i++;
}
die($query);
}
$_args was a 2D array. However, your foreach is using $_where as its iteration variable. $_where is itself a one-dimensional array, so you don't need $i here at all. Instead just use $_where[0]
$_where[0] should refer to the column, and $_where[1] refers to its bound placeholder. $i is unrelated to the contents of $_where.
foreach ($_args as $_where) {
if($i == 0) {
$query .= $_where[0] .'=:'. $_where[1];
} else {
$query .= ' AND '.$_where[0] .'=:'. $_where[1];
}
$i++;
}
Otherwise, you are getting the result of an array key access of a string. For example:
$str = "Hello world";
echo $str[0];
// "H"

Categories