Fetching data with PDO - php

I'm introducing myself to PDO and i'm trying to fetch data with it. I've done this before, but now i'm getting errors all the time. I've been through this for some hours and didn't find a mistake. If someone could help: my code is:
$tabelas_intervalos_afunda = ($con -> query('CREATE TABLE IF NOT EXISTS afunda_$a
SELECT (L1_forma_tensao_max + L1_forma_tensao_min)/2 as L1_forma_tensao, (L2_forma_tensao_max + L2_forma_tensao_min)/2 as L2_forma_tensao, (L3_forma_tensao_max + L3_forma_tensao_min)/2 as L3_forma_tensao
FROM afundamento
WHERE id > $prevNum AND id < $a');
while($row=$tabelas_intervalos_afunda->fetch(PDO::FETCH_ASSOC))
{
$array_forma_onda_fase1_afund[] = $row['L1_forma_tensao'];
$array_forma_onda_fase2_afund[] = $row['L2_forma_tensao'];
$array_forma_onda_fase3_afund[] = $row['L3_forma_tensao'];
}
My problem is that when i var_dump($array_forma_onda_fase1_afund), it returns me "Undefined variable $array_forma_onda_fase1_afund
NULL
Some additional info: $a is changed always when the loop condition is satisfied. The table afunda_$a is being created as expected, table afundamento exists normally.
Would appreciate any help/suggestions.

You are running a create table statement, which returns no rows. Then running fetch on the result, which doesn't enter the while statement. Hence $array_forma_onda_fase1_afund is never defined.
If you want the records you are inserting, you can select them out of the new table or run the original select query. E.g.:
$con->query('CREATE TABLE IF NOT EXISTS afunda_$a
SELECT (L1_forma_tensao_max + L1_forma_tensao_min)/2 as L1_forma_tensao, (L2_forma_tensao_max + L2_forma_tensao_min)/2 as L2_forma_tensao, (L3_forma_tensao_max + L3_forma_tensao_min)/2 as L3_forma_tensao
FROM afundamento
WHERE id > $prevNum AND id < $a');
$tabelas_intervalos_afunda = $con->query("SELECT * FROM afunda_$a");
while($row=$tabelas_intervalos_afunda->fetch(PDO::FETCH_ASSOC))
{
$array_forma_onda_fase1_afund[] = $row['L1_forma_tensao'];
$array_forma_onda_fase2_afund[] = $row['L2_forma_tensao'];
$array_forma_onda_fase3_afund[] = $row['L3_forma_tensao'];
}

Related

Update multiple rows for 1000 records in one go

I have one table based on which one I have to update 6 rows in the other table for matching ids. It is total of over 1000 records so most of the time I get timeout error with current script.
The way I do it now is, I select the range of ids between two dates from the first table, store it into an array and then run foreach loop making update in the second table where the ids are the same, so basically I run a query for every single id.
Is there anyway I could speed it up the process?
I found only a way to generate the each within the foreach loop
UPDATE product SET price = CASE
WHEN ID = $ID1 THEN $price1
WHEN ID = $ID1 THEN $price2
END
But I don't know how could I modify this to update multiple rows at the same time not just one.
My script code look like that
$sql = "SELECT * FROM `games` where (ev_tstamp >= '".$timestamp1."' and ev_tstamp <= '".$timestamp2."')";
while($row = mysqli_fetch_array($sql1)){
$one_of =[
"fix_id" =>$row['fix_id'],
"t1_res" =>$row['t1_res'],
"t2_res" =>$row['t2_res'],
"ht_res_t1" =>$row['ht_res_t1'],
"ht_res_t2" =>$row['ht_res_t2'],
"y_card_t1" =>$row['y_card_t1'],
"y_card_t2" =>$row['y_card_t2'],
"t1_corners" =>$row['t1_corners'],
"t2_corners" =>$row['t2_corners'],
"red_card_t1" =>$row['red_card_t1'],
"red_card_t2" =>$row['red_card_t2']
];
array_push($today_games,$one_of);
}
foreach($today_games as $key=>$val){
$cards_t1=$val['red_card_t1']+$val['y_card_t1'];
$cards_t2=$val['red_card_t2']+$val['y_card_t2'];
$sql = "Update sights SET t1_res='".$val['t1_res']."',
t2_res='".$val['t2_res']."', ev_tstamp='".$val['ev_tstamp']."',
ht_res_t1='".$val['ht_res_t1']."', ht_res_t2='".$val['ht_res_t2']."',
t1_corners='".$val['t1_corners']."',t2_corners='".$val['t2_corners']."',
t1_cards='".$cards_t1."',t2_cards='".$cards_t2."'
where fix_id='".$val['fix_id']."' "
}
Consider an UPDATE...JOIN query using fix_id as join column. Below runs mysqli parameterized query using timestamps. No loop needed.
$sql = "UPDATE sights s
INNER JOIN `games` g
ON s.fix_id = g.fix_id
AND g.ev_tstamp >= ? and g.ev_tstamp <= ?
SET s.t1_res. = g.t1_res,
s.t2_res. = g.t2_res,
s.ev_tstamp = g.ev_tstamp,
s.ht_res_t1 = g.ht_res_t1,
s.ht_res_t2 = g.ht_res_t2,
s.t1_corners = g.t1_corners,
s.t2_corners = g.t2_corners,
s.t1_cards = (g.red_card_t1 + g.y_card_t1),
s.t2_cards = (g.red_card_t2 + g.y_card_t2)";
$stmt = mysqli_prepare($conn, $sql);
mysqli_stmt_bind_param($stmt, 'ss', $timestamp1, $timestamp2);
mysqli_stmt_execute($stmt);

Timeout Error when doing Large select from loop

I have a simple php code below
$sql_items = "SELECT id FROM item_masterfile"; /* this query has 7000 rows */
$result_items = mysqli_query($con,$sql_items);
while ($row_items = mysqli_fetch_row($result_items)) {
$sql_qty = "SELECT qty FROM inventory WHERE id = ".$row_items[0];
/* rest of the code here */
}
}
this is working but due to a lot data my server cannot handle it and other queries took long to respond. how can I fix this? My target here is like batch select? to prevent clogged?
What I see in the process is a lot of select waiting to initiate.
How can I fix this?
try with batches using limit and offset like below
$offset = $i * 5000; // $i is run batch number .. 1, 2, 3 etc in the foreach() loop.
if ($i == 0) {
$offset = "";
}
$result_items="SELECT id FROM item_masterfile LIMIT 5000 OFFSET $offset;";
The code in your question shows that there is one_to_one or one_to_many relation between tables, so using pagination and join statement would resolve the problem.
Check below code hope to be helpful
$sql = "
SELECT im.id, i.qty
FROM item_masterfile AS im
JOIN inventory AS i ON
im.id = i.item_masterfile_id
LIMIT $offset, $limit
";
$result_items = mysqli_query($con,$sql);
you can set $offset and $limit dynamically in your code and go on ...
Instead of using the loop and providing id in there, you should collect all the ids in an array and then pass all of them to the query in one go using the IN operator.
Example: SELECT qty FROM inventory WHERE id IN (1,2,3,4,5). By doing this you can avoid loop and you code will not exit with timeout error.
OR
You can achieve the same using a subquery with your main query
Example: SELECT qty FROM inventory WHERE id IN (SELECT id FROM item_masterfile)
Try with follow step:
get result of first query and get id values like (1,2,3,4,...)..
and out side where clause execute second query with WHERE condition IN clause
Like
$sql_items = "SELECT id FROM item_masterfile"; /* this query has 7000 rows */
$result_items = mysqli_query($con,$sql_items);
while ($row_items = mysqli_fetch_row($result_items)) {
$ids[] = $row_items['id'];
}
$sql_qty = "SELECT qty FROM inventory WHERE id IN ".$ids;
/* rest of the code here */
}

Laravel - use the Eloquent where method from within View

In Laravel 5.4, I have these tables:
sales_orders : id,order_code, customer_id
out_transactions : id, ref_id
ref_id refers to the primary key (i.e. id) of sales_orders.
First I need to get all the rows from sales_orders with a particular customer_id i.e. 10; Then for each row, I need to query the out_transactions table matching its ref_id against the id of sales_orders table.
Inside the show_all method of the controller RequisitionController, I have :
$query_sales_order=SalesOrder::where('customer_id',10);
$requisitions = $query_sales_order->get();
$model=InventoryOutTransaction::query();
return view('admin.requisition.requisition',compact('requisitions')->withModel($model);
Inside the requisition.blade.php, I have :
foreach($requisitions as $aP) {
$requisition_id = $aP->id;
$inventory_out_info = $model->where('ref_id', $requisition_id);
echo '<br/> sql = '.$inventory_out_info->toSql();
$inventory_out_result = $inventory_out_info->get();
$inventory_out_info_id = 0;
foreach ($inventory_out_result as $inventory_out_result_indiv) {
$inventory_out_info_id = $inventory_out_result_indiv->id;
echo ' inventory_out_info_id = '.$inventory_out_info_id;
}
}
But the sql shows unexpected query .
What I get in a case is
sql = select * from `out_transactions` where `ref_id` = ?
sql = select * from `out_transactions` where `ref_id` = ? and `ref_id` = ?
sql = select * from `out_transactions` where `ref_id` = ? and `ref_id` = ? and `ref_id` = ?
So you can see that the where clause is being concatenated. And the concatenated clause remembers the 1st, 2nd etc values of ref_id from the for loop to use each of them, I guess ( I just cannot print the exact value of ? in the query).
How can I just remove the concatenation ? or Any other way to achieve the same purpose ?
First try this query in your controller and print the answer once your expected result is come change your controller with this query and pass the result into view page and foreach the results with your need.
$result = DB::table('sales_orders')->join('out_transactions','sales_orders.id','=','out_transactions.ref_id')->where('sales_orders.customer_id',10)->get();

Convert Mysql procedure into PHP code

I have a stored procedure on my Mysql DB, but i need to change it to get it done by PHP.
I've been looking around here and i know that is possible to make a SP from PHP, but it requires Mysqli (i don't have it updated, and updating it is not possible for personal reasons) or at least that was the only way i found to do it (source).
So for me that only have Mysql, it's possible to do it from php? or should i just "translate" the procedure into PHP format? I mean not making a procedure but a function instead (php function), that actually do the same with PHP code (loops, selects, calls and so) but not storing the procedure on the DB.
This is my procedure
DELIMITER //
create procedure autor_products (in id int)
begin
update authors set authors_products=
(SELECT DISTINCT count(products_id)
FROM products
INNER JOIN authors_to_manufacturers as am ON am.manufacturers_id = products.manufacturers_id
WHERE authors_id = id)
WHERE manufacturers_id = id;
end
//
DELIMITER $$
CREATE PROCEDURE authors()
BEGIN
DECLARE a INT Default 0 ;
DECLARE manu_length int;
select max(manufacturers_id) into manu_length from authors;
simple_loop: LOOP
SET a=a+1;
call autor_products(a);
IF a >= manu_length THEN
LEAVE simple_loop;
END IF;
END LOOP simple_loop;
END $$
DELIMITER ;
commit;
I managed to do this, which is "working" for at least one update
<?php
require('includes/configure.php'); //To get the DB name, user and pass
require_once (DIR_FS_INC.'xtc_db_connect.inc.php'); //I use this to connect the DB
$conn = xtc_db_connect() or die('Unable to connect to database server!');
$manu_lenght="select max(manufacturers_id) from authors;";
for ($i = 0;$i<=$manu_lenght;$i++){ //"for" not in use nor not working if i replace 1 for $i
$update= " update authors set products_amount = (SELECT DISTINCT count(products_id)
FROM products
INNER JOIN authors_to_manufacturers as am ON am.manufacturers_id = products.manufacturers_id
WHERE authors_id = 1)
WHERE manufacturers_id = 1;";
} //will only update 1 author with authors_id = 1 so i needed to make a loop, but if i replace 1 for $i. it doesn't update at all
$retval = mysql_query( $update, $conn );
if(! $retval )
{
die('Could not update data: ' . mysql_error());
}
echo "Updated data successfully\n";
?>
How may i use the $i variable instead of a specific number? (so it would update all at once because of the loop)
Edit: My manu_lenght is not working (it doesn't show the result of the select) but i just changed that part into a number and it's still not working, any thoughts?
Edit 2: Why is this code not working? It works if it's only $a=1; but not if i loop or make a bucle of $a.
$a = 1;
do{
$update= " update authors set products_amount = (SELECT DISTINCT count(products_id)
FROM products
INNER JOIN authors_to_manufacturers as am ON am.manufacturers_id = products.manufacturers_id
WHERE authors_id =$a)
WHERE manufacturers_id =$a;";
echo $a;
$a++;
}
while($a <= 10);
What im doing wrong?
After several tries i got what i need.
This is my code:
<?php
require('includes/configure.php');
require_once (DIR_FS_INC.'xtc_db_connect.inc.php');
$conn = xtc_db_connect() or die('Unable to connect to database server!');
//getting the total amount of authors into $manu_lenght variable
$manu_lenght = mysql_query("select max(manufacturers_id) as sum from authors;" );
if(!$manu_lenght){
die("DB query failed : " . mysql_error());
$sum = "";
} //needed to fetch the result of the select query
while ( $result = mysql_fetch_assoc($manu_lenght)){
$sum = $result["sum"];
}
do{
$author_update= " update authors set products_amount = (SELECT DISTINCT count(products_id)
FROM products
INNER JOIN authors_to_manufacturers as am ON am.manufacturers_id = products.manufacturers_id
WHERE authors_id =$a)
WHERE manufacturers_id =$a;";
$a++;
//while was here, so that's why it wasn't working
$ret_author = mysql_query( $author_update, $conn );
}
while($a <= $sum); //now is correct, it sends the query now
if(!$ret_author )
{
die('Could not update data: ' . mysql_error());
}
echo "Updated authors successfully\n";
?>
What i was basically doing wrong is ending the loop too early, and not letting the mysql_query function send the query (update in this case)
Instead of calling the procedure, i did the procedure translation through PHP. Hope this is useful for anyone else.

Incorrectly sum in a while loop

$dt = mysql_query("SELECT * FROM `member_territory` mt LEFT JOIN `drug_territory` dt ON mt.mt_ter = dt.t_id");
while($t = mysql_fetch_array($dt)) {
$total +=($t['t_reward']* $t['mt_lev'])*150;
mysql_query("UPDATE `members` SET
`drug_income` = '".$total."',
`drug_incometotal` = `drug_incometotal` + '".$total."',
`wallet` = `wallet` + '".$total."'
WHERE `playerid` = '".$t['mt_playerid']."'");
}
So here is my code rather self explainingtary $total when inserted into drug_income that is correct but when ever it is inserted into drug_incometotal or wallet its incorrect.
im not sure why and i have tried everything to my knowledge to pull my head around it!!.
Any ideas why i am getting this incorrect result ( as i say drug_income is correct) only when i try to '+' it to something in the data base it returns an incorrect result.
i dont want to increment just once after the loop... – user3740302 1 min ago
Okay then. So you should probably move your UPDATE query outside of the loop, right?
You may try this modified update query
mysql_query("UPDATE `members` SET drug_income = ".$total.", drug_incometotal = drug_incometotal + ".$total.", wallet = wallet + ".$total." WHERE `playerid` = '".$t['mt_playerid']."'");
It may resolve your problem..

Categories