How does the mysqli execute function work internally? - php

I have a DB where I have some tables, most of them irrelevant for this question:
Content_handler:
+-------------+-------------------+---------------------------+
| app_data_id | app_menu_entry_id | content_item_container_id |
+-------------+-------------------+---------------------------+
| 0 | 0 | NULL |
| 0 | 1 | bm9zb3Ryb3MtMC0w |
+-------------+-------------------+---------------------------+
App_menu_entry:
+-------------------+----------+---------+--------------+
| app_menu_entry_id | position | name | icon_id |
+-------------------+----------+---------+--------------+
| 0 | 0 | Nombre | asd |
| 1 | 1 | Precios | icontest.png |
+-------------------+----------+---------+--------------+
Content_item_container:
+---------------------------+--------------+
| content_item_container_id | content_name |
+---------------------------+--------------+
| bm9zb3Ryb3MtMC0w | Nosotros |
+---------------------------+--------------+
content_handler.app_menu_entry_id REFERENCES TO app_menu_entry.app_menu_entry_id
content_handler.content_item_container_id REFERENCES TO content_item_container.content_item_container_id
Now, when I want to update app_menu_entry I DELETE all records from this table (with cascade, so also deletes content from content_handler) and then I insert data with PHP from an array so I use a foreach with prepared statements like this:
$menuQuery = $connection->prepare("INSERT INTO app_menu_entry(app_menu_entry_id,position,name,icon_id) VALUES(?,?,?,?)");
$handlerQuery = $connection->prepare("INSERT INTO content_handler(app_data_id, app_menu_entry_id, content_item_container_id) VALUES(?,?,?)");
$id = 0;
if (!$menuQuery || !$handlerQuery) {
ErrorHandler::setError(ErrorHandler::DB_QUERY_ERROR, true);
throw new \Exception('Error al realizar la consulta');
}
foreach ($menu['menu_items'] as $menuItem) {
$name = $menuItem['name'];
$position = $menuItem['position'];
$icon = $menuItem['icon_id'];
$contentId = ($menuItem['content'] != null) ? base64_encode($menuItem['content'] . '-' . $userId . '-' . $appId) : null;
$menuQuery->bind_param('ssss', $id, $position, $name, $icon);
$menuQuery->execute();
$handlerQuery->bind_param('sss', $appId, $id, $contentId);
$handlerQuery->execute();
$id++;
}
The problem is that this loop insert data in app_menu_entry but not in content_handler. This can be solved adding sleep(1000); between execute() function and that make me think how can I prevent using sleep() and how this execute function works? Does it uses a thread, makes a async queue...?

Related

How can I join into insert statement?

Here is my table structure:
// pages
+----+-----------------------+--------+
| id | path | method |
+----+-----------------------+--------+
| 1 | list_role | get |
| 2 | make_role | post |
| 3 | edit_role/id | get |
| 4 | list_voucher/activate | get |
| 5 | list_voucher/activate | post |
| 6 | expire_voucher/id | get |
+----+-----------------------+--------+
// role_page
+---------+---------+
| role_id | page_id |
+---------+---------+
Now I want to insert multiple rows into role_page table according to this array: (noted that I have $role_id)
$arr = [['list_role', 'get'], ['list_voucher/activate', 'get']]
$role_id = 4; // for example
So the expected output is:
// role_page
+---------+---------+
| role_id | page_id |
+---------+---------+
| 4 | 1 |
| 4 | 4 |
+---------+---------+
How can I do that by a join?
Currently I do that by a loop on $arr like this:
$role_id = 4;
foreach($arr as $row) {
// match the page id
$page_id = pages::where('path', row[0])->where('method', row[1])->first();
// insert
$role_page = new role_page;
$role_page->role_id = $role_id;
$role_page->page_id = $page_id;
}
Try this
Page Model (you may have to customize this relation)
public function roles(){
return $this->belongsToMany(Role::class, 'role_page', 'page_id', 'role_id')
}
Then
$arr = [['list_role', 'get'], ['list_voucher/activate', 'get']]
$role_id = 4; // for example
$query = Page::query();
foreach ($arr as $page){
$query = $query->orWhere(function($query){
$query->where('path', $page[0])->where('method', $page[1]);
}
}
$pages =$query->get();
foreach($pages as $page){
$page->roles()->attach($role_id);
}
$page_id = pages::where('path', row[0])->where('method', row[1])->first();
This returns an object.
$page_id = pages::where('path', row[0])->where('method', row[1])->first()->id;
This will return just the id.
And then in your foreach you can:
role_page::create([
'page_id' => $page_id,
'role_id' => $role_id
]);
You do have to explicitly state in your role_page model that it's not plural if your not refering to it in a relationship way:
protected $table = 'role_page';

Code Igniter- Batch Insert function inserts null fields in database

Whenever i try to insert data, the fields of the two of the columns are null. ONLY the auto incremented(of course)MainReqID and the last column had the fields.
Here's my Controller..
public function insert_main($data,$orgs){
$this->db->insert('insert_main',$data);
$getID = $this->db->insert_id();
$ctr=1;
$insertorg = array();
foreach($i=0; $i<count($orgs); $i++){
$insertorg[] = array(
'OrgID'=>$ctr[$i],
'MainID'=>$getID[$i],
'Level'=>'1234'[$i]
);
$ctr++;
}
$this->db->insert_batch('insert_mainreq',$insertorg);
}
here's what it looks like in database...
MainReqID | OrgID | MainID | Level
1 | null | null | 1234
2 | null | null | 1234
3 | null | null | 1234
4 | null | null | 1234
5 | null | null | 1234.. and so on..
i need something like this..
MainReqID | OrgID | MainID | Level
1 | 1 | 3 | 1234
2 | 2 | 3 | 1234
3 | 3 | 3 | 1234
4 | 4 | 3 | 1234
5 | 5 | 3 | 1234.. and so on..
It looks like $getID is not an array but you are adding $getID[i]. This surely will not work. The same with $ctr. This is an integer but you are trying $ctr[i]. The same thing is happening with Level.
public function insert_main($data,$orgs){
$this->db->insert('insert_main',$data);
**$getID** = $this->db->insert_id();
**$ctr=1;**
$insertorg = array();
foreach($i=0; $i<count($orgs); $i++){
$insertorg[] array(
'OrgID'=>**$ctr[$i]**,
'MainID'=>**$getID[$i]**,
'Level'=>**'1234'[$i]**
);
$ctr++;
}
$this->db->insert_batch('insert_mainreq',$insertorg);
}
You could try this, I am not sure what you are trying to do with OrgId and MainID but:
public function insert_main($data,$orgs){
$this->db->insert('insert_main',$data);
$getID = $this->db->insert_id();
$insertorg = array();
foreach($i=0; $i<count($orgs); $i++){
$insertorg[] array(
'OrgID'=> $i,
'MainID'=>$getID,
'Level'=>'1234'
);
}
$this->db->insert_batch('insert_mainreq',$insertorg);
}
Keep in mind that $this->db->insert_id(); will return the id of the last row inserted if there are more than one row.
Try This Code:
public function insert_main($data,$orgs){
$this->db->insert('insert_main',$data);
$getID = $this->db->insert_id();
$insertorg = array();
foreach($i=0; $i<count($orgs); $i++)
{
$insertorg[] = array(
'OrgID'=> $i,
'MainID'=>$getID,
'Level'=>'1234'
);
}
$this->db->insert_batch('insert_mainreq',$insertorg);
}

create a sequence for rows with similar ids using php

i have a datastructure similar to this
+---------+---------+
| id | value |
+---------+---------+
| 1 | value |
1 | value |
| 1 | value |
| 1 | value |
| 1 | value |
| 2 | value |
| 2 | value |
| 2 | value |
| 3 | value |
| 3 | value |
| 3 | value |
| | |
+---------+---------+
I am trying to update this table to look something like this
+---------+---------+
| id | value |
+---------+---------+
| 1 | value 0 |
1 | value 1 |
| 1 | value 2 |
| 1 | value 3 |
| 1 | value 4 |
| 2 | value 0 |
| 2 | value 1 |
| 2 | value 2 |
| 3 | value 0 |
| 3 | value 1 |
| 3 | value 2 |
| | |
+---------+---------+
To achieve this, i have written php script that looks like this
$query = "select count(*) as count,id, value from foo group by id";
$sql=$con->prepare($query);
$sql->execute();
$sql->setFetchMode(PDO::FETCH_ASSOC);
while($row=$sql->fetch()){
$id[] = $row['id'];
$count[] = $row['count'];
$value[] = $row['value'];
echo "<pre>";
}
$c=array_combine($id, $count);
foreach ($c as $key=>$value){
for($i=0;$i<=$value;$i++){
$postid = $key;
if($i==0){
$multiple = "multiple";
$newvalue= $value;
}
else{
$x=$i-1;
$multiple = "multiple_".$x;
echo $multiple . "<br>";
$query2 = "update foo set value = :multiple";
$sql2=$con->prepare($query2);
$sql2->bindValue(':multiple', $multiple);
$sql2->execute();
}
}
}
The problem is that the code returns the following results
+---------+---------+
| id | value |
+---------+---------+
| 1 | value_1 |
1 | value_1 |
| 1 | value_1 |
| 1 | value_1 |
| 1 | value_1 |
| 2 | value_1 |
| 2 | value_1 |
| 2 | value_1 |
| 3 | value_1 |
| 3 | value_1 |
| 3 | value_1 |
| | |
+---------+---------+
What can i be possibly be doing wrong?
Thanks #Shadow
Your query runs fine but returns the following results
+------+-----------------------------------------------+
| id | value |
+------+-----------------------------------------------+
| 1 | multiple_1_0_0_0_0_0_0_0_0_0_0_0_0_0_0_0_0 |
| 1 | multiple_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1 |
| 1 | multiple_1_2_2_2_2_2_2_2_2_2_2_2_2_2_2_2_2 |
| 1 | multiple_1_3_3_3_3_3_3_3_3_3_3_3_3_3_3_3_3 |
| 2 | multiple_1_0_0_0_0_0_0_0_0_0_0_0_0_0_0_0_0 |
| 2 | multiple_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1 |
| 2 | multiple_1_2_2_2_2_2_2_2_2_2_2_2_2_2_2_2_2 |
| 2 | multiple_1_3_3_3_3_3_3_3_3_3_3_3_3_3_3_3_3 |
| 3 | multiple_1_0_0_0_0_0_0_0_0_0_0_0_0_0_0_0_0 |
| 3 | multiple_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1 |
| 3 | multiple_1_0_0_0_0_0_0_0_0_0_0_0_0_0_0_0_0 |
+------+-----------------------------------------------+
You can do the update iterating and creating data in such a way:
<?php
$pdo = new PDO('mysql:host=localhost;dbname=test', 'root', '');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sth = $pdo->prepare("SELECT * FROM foo");
$sth->execute();
$data = $sth->fetchAll(PDO::FETCH_ASSOC);
$response = array();
foreach ($data as $dataIndex => $dataValue) {
if (!isset($response[$dataValue["id"]]["count"])) {
$response[$dataValue["id"]]["count"] = 0;
} else {
$response[$dataValue["id"]]["count"] ++;
}
$response[$dataValue["id"]]["values"][$dataValue["pid"]] = "value_" . $response[$dataValue["id"]]["count"];
$sth = $pdo->prepare("UPDATE foo SET value = '{$response[$dataValue["id"]]["values"][$dataValue["pid"]]}' WHERE pid = {$dataValue["pid"]}");
$sth->execute();
}
?>
But try to do an update using the least iteration not to create as many database queries , example:
<?php
$pdo = new PDO('mysql:host=localhost;dbname=test', 'root', '');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sth = $pdo->prepare("SELECT * FROM foo");
$sth->execute();
$data = $sth->fetchAll(PDO::FETCH_ASSOC);
$response = array();
$update = array();
foreach ($data as $dataIndex => $dataValue) {
$response[$dataValue["id"]]["id"] = $dataValue["id"];
if (!isset($response[$dataValue["id"]]["count"])) {
$response[$dataValue["id"]]["count"] = 0;
} else {
$response[$dataValue["id"]]["count"] ++;
}
$response[$dataValue["id"]]["values"][$dataValue["pid"]] = "value_" . $response[$dataValue["id"]]["count"];
$update[] = "UPDATE foo SET value = '{$response[$dataValue["id"]]["values"][$dataValue["pid"]]}' WHERE pid = {$dataValue["pid"]};";
}
$update = implode("",$update);
$sth = $pdo->prepare($update);
$sth->execute();
?>
Your update query
$query2 = "update foo set value = :multiple";
does not contain any where criteria, each time you call this query it updates the value field's value in all records.
Honestly, I would not really involve php in this update, would do it purely in sql using user defined variables and multi-table join syntax in the update:
update foo inner join (select #i:=0, #previd:=-1) as a
set foo.value=concat(foo.value,'_',#i:=if(id=#previd,#i+1,0),if(#previd:=id,'',''))
The subquery in the inner join initialises #i and #previd user defined variables. The 3rd parameter of the concat function determines the value #i to be concatenated to the value field. The 4th parameter of concat sets the #previd variable and returns an empty string not to affect the overall concatenation. Unfortunately, I do not have access to MySQL to test the query, but it should be a good starting point anyway.
UPDATE
The OP claims in the updated question that the query I provided creates the below resultset:
+------+-----------------------------------------------+
| id | value |
+------+-----------------------------------------------+
| 1 | multiple_1_0_0_0_0_0_0_0_0_0_0_0_0_0_0_0_0 |
| 1 | multiple_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1 |
| 1 | multiple_1_2_2_2_2_2_2_2_2_2_2_2_2_2_2_2_2 |
| 1 | multiple_1_3_3_3_3_3_3_3_3_3_3_3_3_3_3_3_3 |
| 2 | multiple_1_0_0_0_0_0_0_0_0_0_0_0_0_0_0_0_0 |
| 2 | multiple_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1 |
| 2 | multiple_1_2_2_2_2_2_2_2_2_2_2_2_2_2_2_2_2 |
| 2 | multiple_1_3_3_3_3_3_3_3_3_3_3_3_3_3_3_3_3 |
| 3 | multiple_1_0_0_0_0_0_0_0_0_0_0_0_0_0_0_0_0 |
| 3 | multiple_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1 |
| 3 | multiple_1_0_0_0_0_0_0_0_0_0_0_0_0_0_0_0_0 |
+------+-----------------------------------------------+
Tested my solution in sqlfiddle. I had to remove the order by clause, otherwise the query produced the results in line with the requirements stated in the question. See sqlfiddle for details.
The results in the updated question are likely the result of running the query in a loop multiple times. In simple words: you just copy pasted the query into your code and did not remove the loop, even when I pointed out, that this may be the reason of the results you received.

having trouble looping sql insert with php

I'm new to php and sql and what im trying to achieve is loop an sql insert into the same column with different values form another table with different columns i am able to do it without loop but i cant seem to get it to work with this loop. any help would be greatly appreciated.
edited.
i want to insert the sum values of table tblplyrbetlisttemp to tblcollplasada depending if $vresults == 'SK-WALA' or $vresults == 'SK-MERON' the outcome should insert 3 rows with fldM7 fldW7 and fldM7price or fldW7price depending on $vresults value.
table structure listed below
+-----------------------------------------+
| tblplyrbetlisttemp |
+-----------------------------------------+
| fldM7price | fldW7price | fldM7 | fldW7 |
+------------+------------+-------+-------+
+--------------------------------------------------------------------------------------------------------+
| tblcollplasada |
+--------------------------------------------------------------------------------------------------------+
| fldtag | fldtranno | fldfightno | fldtrandate | fldusrcd | fldwinner | fldpercomm | fldSK | fldarenaid |
+--------+-----------+------------+-------------+----------+-----------+------------+-------+------------+
for example $vresults is equals to 'SK-WALA' and table tblplyrbetlisttemp has values fldM7=5 fldW7=5 fldW7price=500
+-----------------------------------------+
| tblplyrbetlisttemp |
+-----------------------------------------+
| fldM7price | fldW7price | fldM7 | fldW7 |
+------------+------------+-------+-------+
| 500 | | 5 | |
+------------+------------+-------+-------+
| | 500 | | 5 |
+------------+------------+-------+-------+
output should be
+--------------------------------------------------------------------------------------------------------+
| tblcollplasada |
+--------------------------------------------------------------------------------------------------------+
| fldtag | fldtranno | fldfightno | fldtrandate | fldusrcd | fldwinner | fldpercomm | fldSK | fldarenaid |
+--------+-----------+------------+-------------+----------+-----------+------------+-------+------------+
| | | | | | SK-WALA | | 500 | |
+--------+-----------+------------+-------------+----------+-----------+------------+-------+------------+
| | | | | | SK-WALA | | 5 | |
+--------+-----------+------------+-------------+----------+-----------+------------+-------+------------+
| | | | | | SK-WALA | | 5 | |
+--------+-----------+------------+-------------+----------+-----------+------------+-------+------------+
code:
function CollectComm ($vresults) {
global $iSqlConnDb;global $varfightno;global $percomm;global $comm ;global $vtagid;global $ActvARenId;
if ($vresults == 'SK-WALA') { $win = 'W';$lose = 'M'; }
if ($vresults == 'SK-MERON') { $win = 'M';$lose = 'W'; }
$winOdd =array('fld' . $win . '7price','fld' . $win . '7','fld' . $lose .'7');
$query_rscoll = "select distinct(fldusrcd) as vuser from tblplyrbetlisttemp where fldarenaid='$ActvARenId'";
$rscoll = mysql_query($query_rscoll, $iSqlConnDb) or die(mysql_error());
$row_rscoll = mysql_fetch_assoc($rscoll);
$totalRows_rscoll = mysql_num_rows($rscoll);
if ($totalRows_rscoll > 0) {
do {
$vhave = false;
$varuserid = $row_rscoll['vuser'];
$vtrandate = date("Y-m-d G:i:s");
for ($i = 0; $i < count($winOdd); $i++) {
$OC[$i] ='';
$varodd = $winOdd[$i];
$rsTotcomm = mysql_query("select SUM($varodd) as totodd FROM tblplyrbetlisttemp where fldarenaid='$ActvARenId' and fldusrcd='$varuserid'");
$vcomm=mysql_fetch_assoc($rsTotcomm);
if ($vcomm['totodd'] > 0 || ) {
$vhave = true;
$OC[$i] =$comm * $vcomm['totodd'] ;
}
if ($vhave == true) {
$vtranno = AutoIDArena('tblcollplasada','fldtranno',$ActvARenId);
$insertSQL = "INSERT INTO tblcollplasada(fldtag,fldtranno,fldfightno,fldtrandate,fldusrcd,fldwinner,fldpercomm,fldSK,fldarenaid)
VALUES(" . $vtagid . "," . $vtranno . "," .$varfightno . ",'" . $vtrandate . "','" . $varuserid . "','" . $vresults . "','" . $percomm . "','" . $OC[$i] . "','" . $ActvARenId . "')";
$Result1 = mysql_query($insertSQL, $iSqlConnDb) or die(mysql_error());
}
}
}
while ($row_rscoll = mysql_fetch_assoc($rscoll)); }
}

getting an empty array when my pdo should be returning many mysql rows

I get array(0){} where I should be returning rows;
<?php
require_once('auth.php');
$conn = new PDO("mysql:host=localhost;dbname=$dbname", $username, $pw);
$file = fopen('nameList1.txt','r');
$firstname = ''; $lastname = ''; $index = -1; $id = -1;
$tab = ' ';
try{
while ($line = fgets($file)) {
$index = strrpos($line, $tab);
$firstname = substr($line, 0, $index);
//var_dump($firstname);
$lastname = substr($line, $index + strlen($tab));
//var_dump($lastname);
$stmt = $conn->prepare("SELECT * FROM dbname WHERE FName = :firstname AND LName = :lastname");
$stmt->bindvalue(':firstname', $firstname);
$stmt->bindvalue(':lastname', $lastname);
$stmt->execute();
$result = $stmt->fetchAll();
var_dump($result);
}
}
catch ( Exception $e )
{
echo "Exception at $i";
}
fclose($file);
?>
********* working SQL *************
mysql> SELECT * FROM list WHERE FName='TARA' AND LName='AABA';
+----+--------------+---------------+-------+-------+-------+-----------+------------+-----------+--------+----------+-----------+-----------+-----------+-------------+-------------------+--------------------+------------+------------+----------+------------+------------+--------------+--------------+---------------------+-----------------------+-------+-------+-------+-------+----------+---------+-------------+------------------+--------------+------------+------------+
| id | StateVoterID | CountyVoterID | Title | FName | MName | LName | NameSuffix | Birthdate | Gender | RegStNum | RegStFrac | RegStName | RegStType | RegUnitType | RegStPreDirection | RegStPostDirection | RegUnitNum | RegCity | RegState | RegZipCode | CountyCode | PrecinctCode | PrecinctPart | LegislativeDistrict | CongressionalDistrict | Mail1 | Mail2 | Mail3 | Mail4 | MailCity | MailZip | MailCountry | Registrationdate | AbsenteeType | LastVoted | StatusCode |
+----+--------------+---------------+-------+-------+-------+-----------+------------+-----------+--------+----------+-----------+-----------+-----------+-------------+-------------------+--------------------+------------+------------+----------+------------+------------+--------------+--------------+---------------------+-----------------------+-------+-------+-------+-------+----------+---------+-------------+------------------+--------------+------------+------------+
| 9 | 0 | 458198 | | TARA | L | AABRA | | 2 | F | 5804 | | 1ST | PL | | | NE | 0 | MARYSVILLE | WA | 98271 | 0 | 101231 | 0 | 39 | 2 | | | | | | | | 05/05/2004 | P | 11/08/2011 | A |
*********** var_dump($result) **************
array(0) { } array(0) { } array(0) { } array(0) { } array(0) { } array(0) { } array(0) { } array(0) { } ....
Empty array returned by fetchAll means there was no data found.
This is a fact. While "working SQL" is working somewhere else.
So - you have to check your input data, database, environment, typos and such.
Sincerely,

Categories