I am trying to build some sort of database class (all PDO). All my functions work up till now, but the insert statement runs twice. I really don't see where it goes wrong. When I run the code with some echoes in it, the echoes only appear once so I don't think that it actually gets executed twice...
When I use the getBind function with other statements it works perfectly fine so...
THE CODE
function insert ($p_sTable, $p_aCol, $p_aVal) {
$this->m_sQuery .= "INSERT INTO ".$p_sTable." (";
$queryCols = "";
foreach ($p_aCol as $col) { ... }
$this->m_sQuery .= $queryCols.") VALUES (";
$queryPlaceholders = "";
foreach ($p_aCol as $placeholder) {... }
foreach ($p_aVal as $p_aValtosave) { .... }
$this->m_sQuery .= $queryPlaceholders.")";
echo "m_sQuery:</br>".$this->m_sQuery;
echo "</br>print bindCol</br>";
print_r($this->m_aBindCol);
echo "</br>print bindVal</br>";
print_r($this->m_aBindVal);
return $this;
}
WHERE I CALL THE FUNCTION:
$db = Db::getConnection();
$arr = $db->insert("geprutsvanlisa",["kolom1","kolom2"], ["24", "24"])->getBind();
THE OUTPUT: m_sQuery:
INSERT INTO geprutsvanlisa (kolom1, kolom2) VALUES (:ikolom1, :ikolom2)
print bindCol
Array ( [0] => ikolom1 [1] => ikolom2 )
print bindVal
Array ( [0] => 24 [1] => 24 )
echo i:0
bindvalue(:ikolom1, 24)
echo i:1
bindvalue(:ikolom2, 24)
echo this ms query
INSERT INTO geprutsvanlisa (kolom1, kolom2) VALUES (:ikolom1, :ikolom2)
echo this bindcol Array ( [0] => ikolom1 [1] => ikolom2 )
echo this bindval Array ( [0] => 24 [1] => 24 )
Related
I have a list of serialized data that I unserialize and store into an array.
$employee_data = unserialize($entry, '63');
Which results in an expected output:
Array ( [0] =>
Array ( [First] => Joe
[Last] => Test
[Birth Date] => 01/01/2011
)
[1] =>
Array ( [First] => Mike
[Last] => Miller
[Birth Date] => 01/01/1980
)
)
Ive been trying, unsuccessfully, to insert these records into a table in MySQL using foreach() or something like:
$employee_array = array();
$k = 1;
for($n=0; $n<count($employee_data); $n++ ){
$employee_array['employee_first_name'.$k] = $employee_data[$n]['First'];
$employee_array['employee_last_name'.$k] = $employee_data[$n]['Last'];
$employee_array['employee_birthdate'.$k] = $employee_data[$n]['Birth Date'];
$SQL = "INSERT INTO employee_test (
employee_first_name,
employee_last_name,
employee_birthdate
)
VALUES (
'$employee_first_name.$k',
'$employee_last_name.$k',
'$employee_birthdate.$k'
)"
$k++;
};
Each employee in the array needs to be entered into a new row in the table, however the number of employees will vary from 1 to 10+
We've tried
foreach($employee_array as $key => $value)
with the same results.
The actual results we're hoping for is the SQL Statement to be:
insert into employee_test(
employee_first_name,
employee_last_name,
employee_birthdate)
VALUES(
'Joe',
'Test',
'01/01/2011');
insert into employee_test(
employee_first_name,
employee_last_name,
employee_birthdate)
VALUES(
'Mike',
'Miller',
'01/01/1980');
Keep in mind that your sql statement is not escaped. For example, a name with an apostrophe like "0'neil" will break your sql. I would also familiarise yourself with php's foreach: https://www.php.net/manual/en/control-structures.foreach.php.
I'm not sure exactly what you're trying to accomplish by adding the index to the name and sql value, but I would do something like this:
foreach($employee_data as $key => $value){
// $employee_array is not necessary
$employee_array[$key]['employee_first_name'] = $value['First'];
$employee_array[$key]['employee_last_name'] = $value['Last'];
$employee_array[$key]['employee_birthdate'] = $value['Birth Date'];
// Needs escaping
$SQL = "INSERT INTO employee_test (
employee_first_name,
employee_last_name,
employee_birthdate
)
VALUES (
'{$value['First']}',
'{$value['Last']}',
'{$value['Birth Date']}'
)";
echo $SQL;
};
The first implementation wont work as your calling a variable rather than the key in your array.
'$employee_first_name.$k',
Should be
$employee_array['employee_first_name'.$k]
You are also creating the SQL statement every iteration of the for loop, so in this implementation only the last employee will save.
Also I don't see the reasoning in doing it that way anyway you may as well just use the employee_data array and the $k variable can also be made redundant.
$SQL = "";
for($n=0; $n<count($employee_data); $n++ ){
$SQL .= "INSERT INTO employee_test (
employee_first_name,
employee_last_name,
employee_birthdate
) VALUES (";
$SQL .= "'".$employee_data[$n]['First']."',";
$SQL .= "'".$employee_data[$n]['Last']."',";
$SQL .= "'".$employee_data[$n]['Birth Date']."'";
$SQL .= ");";
};
Ive not tested but it should give you an idea.
You will also have issues with the date formatted that way, Your database would likely require the date in yyyy/mm/dd format
Finally I would not recommend inserting values like this, look at the PDO library for placeholders.
I think I understand what you're trying to do here. You are using the = operator, effectively setting $SQL to a new value each time your loop iterates. If you adapt your code, you will be able to append to $SQL variable each time.
//I used this array for testing. Comment this out
$employee_data = array(
0 => array(
"first" => "test",
"last" => "tester",
"birth date" => "01/01/1970"
),
1 => array(
"first" => "bob",
"last" => "david",
"birth date" => "02/02/1972"
),
);
//Start SQL as a blank string
$SQL = "";
//Do your iteration
foreach( $employee_data as $key=>$value ){
$first = $value['first'];
$last = $value['last'];
$birthDate = $value['birth date'];
//append this query to the $SQL variable. Note I use `.=` instead of `=`
$SQL .= "INSERT INTO employee_test(
`employee_first_name`,
`employee_last_name`,
`employee_birthdate`)
VALUES(
'$first',
'$last',
'$birthDate'
);";
}
//output the query
echo $SQL;
There are much easier ways of doing this though. Look into prepared statements :)
I'm trying to modifiy some code I have that creates and array of objects for a menu from a database I need it to add the SubCategoryID to each item in the array
and for the life of me I'm having a mental blank on how to do it
<?php
include_once ('includes/sqlopen.php');
$sql = mysqli_query($conn, "SELECT CategoryName, SubcategoryName,
SubcategoryID
FROM products
GROUP BY SubcategoryID
ORDER BY CategoryName");
$menu = array();
while ($row = mysqli_fetch_assoc($sql)) {
if (!in_array($row['CategoryName'], $menu['category'])) {
$menu['category'][] = $row['CategoryName'];
}
if (!empty($row['SubcategoryName']))
$menu['SubcategoryName'][$row['CategoryName']][] = $row['SubcategoryName'];
}
echo "Start of Array";
echo "<br>";
foreach ($menu['category'] as $cat) {
echo $cat."<br>";
foreach ($menu['SubcategoryName'][$cat] as $subcat) {
echo "--" . $subcat."<br>";
}
}
echo "<br>";
echo "End of Array";
include_once ('includes/sqlclose.php');
?>
Basically I want to achieve this:
Parent Cat 1 (link to prodlist.php?id=100)
--Child Cat1 (link to prodlist.php?id=103)
--Child Cat2 (link to prodlist.php?id=104)
Parent Cat 2 (link to prodlist.php?id=200)
Parent Cat 3 (link to prodlist.php?id=300)
--Child Cat1 (link to prodlist.php?id=301)
--Child Cat2 (link to prodlist.php?id=302)
and the database is layed out:
CategoryName SubcategoryName ItemName SubCategoryID
ParentCat1, ChildCat1, Item1, 103
ParentCat1, ChildCat1, Item2, 103
ParentCat1, ChildCat2, Item1, 104
ParentCat2, Item1, 200
ParentCat3, ChildCat1, Item1, 301
ParentCat3, ChildCat2, Item2, 302
** UPDATE- Thanks to everyone that is trying to help me, I know I'm probably not that great at explaining what I need help with..
I have been playing around with it for a little bit now and it is kind of doing what I want. I just have a small glitch where if 2 different parent categories have subcategories with the same name it will add both subcat ids to the array
$menu = array();
while ($row = mysqli_fetch_assoc($sql)) {
if (!in_array($row['CategoryName'], $menu['category'])) {
$menu['category'][] = $row['CategoryName'];
}
if (!empty($row['SubcategoryName']))
$menu['SubcategoryName'][$row['CategoryName']][] = $row['SubcategoryName'];
$menu['SubcategoryID'][$row['SubcategoryName']][] = $row['SubcategoryID'];
}
Output
--Accessories
id--766
id--243
id--992
id--871
id--977
Monitor Arms
--Spacedec
id--789
--Visidec
id--791
--Telehook
id--792
--Spacepole
id--804
--Accessory
id--866
--Monitor Accessories
id--990
id--584
--Stands
id--991
id--538
First of all, you can improve your database structure
Like below:
id|category|parent_id
Simple and clean isn't.
Now try this:
//your database records
$rows = [
['id'=>1,'category'=>'Indland','parent_id'=>0],
['id'=>2,'category'=>'Udland','parent_id'=>0],
['id'=>3,'category'=>'Sport','parent_id'=>0],
['id'=>4,'category'=>'Handbold','parent_id'=>3],
['id'=>5,'category'=>'Fodbold','parent_id'=>3],
['id'=>6,'category'=>'Sample','parent_id'=>4]
];
print_r(getList($rows));
// Recursive function
function getList($rows, $id=0){
// Start a new list
$newList = null;
foreach($rows as $key => $row) {
if ($row['parent_id'] == $id) {
// Add an UL tag when LI exists
$newList == null ? $newList = "<ul>" : $newList;
$newList .= "<li>";
$newList .= "{$row['category']}";
// Find childrens
$newList .= getList(array_slice($rows,$key),$row['id']);
$newList .= "</li>";
}
}
// Add an UL end tag
strlen($newList) > 0 ? $newList .= "</ul>" : $newList;
return $newList;
}
This will result in:
The DB structure is the obvious issue here as it's using a fixed structure. While this could be efficient in certain scenarios it's not easily extensible. A way to achieve what you are currently trying to achieve will be this:
Fetch and group all items (in code) by CategoryName (I'm hoping the category name is a slug?)
For each category name, display all subcategories with link to id
Translated to code this will be something like this (Your current SQL query is fine):
$menu = [];
while ($row = mysqli_fetch_assoc($sql)) {
if (!isset($menu[$row['CategoryName']])) {
$menu[] = $row['CategoryName'];
}
if (!empty($row['SubCategoryName']))
$menu[$row['CategoryName']][] = $row['SubcategoryName'];
}
}
echo "Start of Array";
echo "<br>";
foreach ($menu as $cat => $catsubs) {
echo $cat."<br>";
foreach ($catsubs as $sub) {
echo "--" . $sub."<br>";
}
}
echo "<br>";
echo "End of Array";
ok guys I think I have it.. ill post it up so that on the rare chance anyone else can benefit from it.. Thanks again to everyone that helped me
Code
<?php
include_once ('includes/sqlopen.php');
$sql = mysqli_query($conn, "SELECT CategoryName, SubcategoryName, CategoryCode, SubcategoryID
FROM products GROUP BY SubcategoryID ORDER BY CategoryName");
$menu = array();
while ($row = mysqli_fetch_assoc($sql)) {
// Creates First Level Array Items For Parent IDs
if (!in_array($row['CategoryName'], $menu['category'])) {
$menu['category'][] = $row['CategoryName'];
}
if (!empty($row['SubcategoryName']))
// Creates Second Level Array for Child IDs
$menu['SubcategoryName'][$row['CategoryName']][] = $row['SubcategoryName'];
// Creates Third Level Array for Category IDs
$menu['SubcategoryID'][$row['SubcategoryName']][$row['CategoryName']][] = $row['SubcategoryID'];
}
echo "Start of Array";
echo "<br>";
foreach ($menu['category'] as $cat) {
echo $cat."<br>";
foreach ($menu['SubcategoryName'][$cat] as $subcat) {
echo "--" . $subcat."<br>";
foreach($menu['SubcategoryID'][$subcat][$cat] as $id)
echo "id--".$id."<br>";
} echo "<br>";
}
echo "<br>";
echo "End of Array";
include_once ('includes/sqlclose.php');
?>
<pre>
<?php print_r ($menu); ?>
</pre>
Foreach Loop Output
CPU
--AMD Socket FM2
id--778
--Mobile
id--558
--Intel Socket 1150 (4th Gen)
id--825
--Intel Socket 1151 (6th Gen Skylake)
id--945
--AMD Socket AM3
id--693
--Intel Xeon
id--980
--Intel Socket 2011 (3rd and 4th Gen)
id--744
--Intel Socket 1151 (7th Gen Kabylake)
id--1021
--AMD Socket AM4
id--1023
print_r Output
[AMD Socket FM2] => Array
(
[CPU] => Array
(
[0] => 778
)
)
[Mobile] => Array
(
[CPU] => Array
(
[0] => 558
)
)
[Intel Socket 1150 (4th Gen)] => Array
(
[CPU] => Array
(
[0] => 825
)
)
[Intel Socket 1151 (6th Gen Skylake)] => Array
(
[CPU] => Array
(
[0] => 945
)
)
[AMD Socket AM3] => Array
(
[CPU] => Array
(
[0] => 693
)
)
[Intel Xeon] => Array
(
[CPU] => Array
(
[0] => 980
)
)
[Intel Socket 2011 (3rd and 4th Gen)] => Array
(
[CPU] => Array
(
[0] => 744
)
)
I have situation . I want to insert one array element to another array element but could not find the exact method.
This is my function
public function get_applicants($sort_array = array('apply_id DESC'))
{
global $wpdb;
$sql = 'SELECT * FROM ' . $this->tableac . " ORDER BY " . implode(',', $sort_array);
//$sql = 'SELECT c. * , p. * FROM wp_apply c, wp_apply_files p WHERE c.apply_id = p.apply_id';
$educations = $wpdb->get_results($sql);
$getid=array();
foreach($educations as $education){
//print_r($education);
$sqlfile = 'SELECT * FROM wp_apply_files WHERE apply_id = '.$education->apply_id;
$getalls = $wpdb->get_results($sqlfile);
$allvalues="";
foreach($getalls as $getall){
$allvalues= $getall->uploaded_file.", ";
$getid[]=$getall->uploaded_file;
}
$allvaluesnew=rtrim($allvalues,", ");
// echo "<br>";
// Here I want to insert getid into educations array
}
echo "<pre>";print_r($educations);
die();
//return array($educations,$getid);
}
print_r result show this.
Array
(
[0] => stdClass Object
(
[apply_id] => 44
[choose_position] => HR Manager
[title] => testr
[first_name] => waqas
[last_name] => aamer
[current_job] => developer
print_r get id show like this.
Array
(
[0] => a75d138911c55df639fdd09fade511151-23.pdf
[1] => newone3.pdf
[2] => a75d138911c55df639fdd09fade511151-22.pdf
[3] => newone2.pdf
[4] => a75d138911c55df639fdd09fade511151 (2).pdf
[5] => newone.pdf
)
I want to insert these these elements iteration wise. When in the educations first iteration comes than it should insert all the elements at one index of second array separated by comma.
If I understand your question correctly then following might help.
It will insert comma separated values from $getid into new key called "getid" in $educations array.
public function get_applicants($sort_array = array('apply_id DESC'))
{
global $wpdb;
$sql = 'SELECT * FROM ' . $this->tableac . " ORDER BY " . implode(',', $sort_array);
//$sql = 'SELECT c. * , p. * FROM wp_apply c, wp_apply_files p WHERE c.apply_id = p.apply_id';
$educations = $wpdb->get_results($sql);
$getid=array();
foreach($educations as $key => $education){
//print_r($education);
$sqlfile = 'SELECT * FROM wp_apply_files WHERE apply_id = '.$education->apply_id;
$getalls = $wpdb->get_results($sqlfile);
foreach($getalls as $getall){
$getid[]=$getall->uploaded_file;
}
// echo "<br>";
// Here I want to insert getid into educations array
$educations[$key]["getid"] = implode(",", $getid);
}
echo "<pre>";print_r($educations);
die();
//return array($educations,$getid);
}
Hope this helps and this is what you want
I've recently started working with PHP and SQLite and I'm having problems with PHP arrays (I think). This is the code I use:
<?php
$dbo = new SQLiteDatabase("rsc/db.sqlite");
$test = $dbo->arrayQuery("DROP TABLE users;");
$test = $dbo->arrayQuery("CREATE TABLE \"users\"(name text, avatar text);");
$test = $dbo->arrayQuery("INSERT INTO users(name, avatar) VALUES('zad0xsis', 'http://zad0xsis.net/');");
// get number of rows changed
$changes = $dbo->changes();
echo "<br />Rows changed: $changes<br />";
// Get and show inputted data
$tableArray = $dbo->arrayQuery("SELECT * FROM users;");
echo "Table Contents\n";
echo "<pre>\n";
print_r($tableArray);
echo "\n</pre>";
?>
And when showing the data (print_r($tableArray);) I get this array:
Array
(
[0] => Array
(
[0] => zad0xsis
[name] => zad0xsis
[1] => http://zad0xsis.net/
[avatar] => http://zad0xsis.net/
)
)
I don't know why the values are duplicated, like [0] and [name], but it shows the data. Now, when I try to do print_r($tableArray["name"]); I should get the value, but it doesn't prints anything :( What I'm doing wrong? Thanks!
it helps you to select both
$tableArray[0]
or
$tableArray['name'];
it's fine.
to your problem: You'll have to
print_r($tableArray[0]['name'])
or
print_r($tableArray[0][0])
Here is my simplified code:
$connexion = new PDO(SQL_DSN,SQL_USERNAME,SQL_PASSWORD);
$connexion2 = new PDO(SQL_DSN2,SQL_USERNAME2,SQL_PASSWORD2);
[...]
$sqlIndex = "SELECT index_key,index_platforms_code
FROM index
WHERE index_missions_id = :mission";
$initFiches = $connexion->prepare($sqlIndex);
$initFiches->bindParam(":mission" , $_GET['mission']);
$initFiches->execute();
try
{
while ($fiche = $initFiches->fetch(PDO::FETCH_ASSOC))
{
print_r($fiche);
foreach ($structure['champs'] as $masterChamp)
{
//$stmt = $connexion2->prepare($masterChamp['sql']);
}
}
}
catch (exception $e)
{
echo "error".$e->getMessage();
}
My output:
Array
(
[index_key] => 1
[index_platforms_code] => 1
)
Array
(
[index_key] => 2
[index_platforms_code] => 2
)
Array
(
[index_key] => 3
[index_platforms_code] => 3
)
Array
(
[index_key] => 4
[index_platforms_code] => 4
)
All Right, but if I uncomment this line
$stmt = $connexion2->prepare($masterChamp['sql']);
in the foreach, this line broke the while above and here is the new output:
Array
(
[index_key] => 1
[index_platforms_code] => 1
)
Someone have an idea?
Here's a solution that doesn't involve 2 connections and that's more optimized.
$connexion = new PDO(SQL_DSN,SQL_USERNAME,SQL_PASSWORD);
$sqlIndex = "SELECT index_key,index_platforms_code
FROM index
WHERE index_missions_id = :mission";
$initFiches = $connexion->prepare($sqlIndex);
$initFiches->bindParam(":mission" , $_GET['mission'], PDO::PARAM_STR);
$initFiches->execute();
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt = $connexion->prepare("SELECT ...."); // Prepare outside of the loop, you don't have to prepare it X times, once is enough.
if(sizeof($data))
{
foreach($data as $row)
{
// Do your statement binding / executing.
}
}
Alternatively, it seems you might be able to do this with table joining rather than issuing a query for each row you get from the 1st table. Since you haven't posted the structure, I guess there's no much helping it at the moment.