I would like to change my insert query. But how can i call procedure while using pdo in php. I was inserted table rows one by one with for loop. I want to do this with procedure. So, how should i do the query ? My insert query is below:
$connect = new PDO("mysql:host=;dbname=;charset=utf8", "username", "password");
$query = "
INSERT INTO siparis
(product_id, p_code, p_name, p_type, p_quantity, p_listprice, p_netprice, p_total, preorderno, yetkili)
VALUES (:pid, :p_code, :p_name, :dekorA, :p_quantity, :p_listprice, :p_netprice, :p_total, :preorderno, :yetkili)
";
for($count = 0; $count<count($_POST['hidden_p_code']); $count++)
{
$data = array(
':pid' => $_POST['hidden_pid'][$count],
':p_code' => $_POST['hidden_p_code'][$count],
':p_name' => $_POST['hidden_p_name'][$count],
':dekorA' => $_POST['hidden_dekorA'][$count],
':p_quantity' => $_POST['hidden_p_quantity'][$count],
':p_listprice' => $_POST['hidden_p_listprice'][$count],
':p_netprice' => $_POST['hidden_p_netprice'][$count],
':p_total' => $_POST['hidden_p_total'][$count],
':preorderno' => $_POST['hidden_preorderno'][$count],
':yetkili' => $_POST['hidden_yetkili'][$count]
);
$statement = $connect->prepare($query);
$statement->execute($data);
}
Procedure
DELIMITER //
CREATE PROCEDURE NEWLIST(
IN pid int(11),
IN p_code varchar(100),
IN p_name varchar(100),
IN dekorA varchar(100),
IN p_quantity varchar(100),
IN p_listprice varchar(100),
IN p_netprice varchar(100),
IN p_total varchar(100),
IN preorderno int(11),
IN yetkili varchar(10)
)
BEGIN
INSERT INTO siparis(product_id, p_code, p_name, p_type, p_quantity, p_listprice, p_netprice, p_total, preorderno, yetkili) VALUES( pid, p_code, p_name, dekorA, p_quantity, p_listprice, p_netprice, p_total, preorderno, yetkili);
END //
DELIMITER ;
UPDATE It works with your suggestions, Thanks #Professor Abronsius
$query = "CALL NEWLIST(:pid, :p_code, :p_name, :dekorA, :p_quantity, :p_listprice, :p_netprice, :p_total, :preorderno, :yetkili)";
for($count = 0; $count<count($_POST['hidden_p_code']); $count++)
{
$data = array(
':pid' => $_POST['hidden_pid'][$count],
':p_code' => $_POST['hidden_p_code'][$count],
':p_name' => $_POST['hidden_p_name'][$count],
':dekorA' => $_POST['hidden_dekorA'][$count],
':p_quantity' => $_POST['hidden_p_quantity'][$count],
':p_listprice' => $_POST['hidden_p_listprice'][$count],
':p_netprice' => $_POST['hidden_p_netprice'][$count],
':p_total' => $_POST['hidden_p_total'][$count],
':preorderno' => $_POST['hidden_preorderno'][$count],
':yetkili' => $_POST['hidden_yetkili'][$count]
);
$statement = $connect->prepare($query);
$statement->execute($data);
}
You could be a little creative and build the entire query dynamically by interrogating the database schema and determining the parameters used within the stored procedure and from that build the placeholder string and generate the correctly formatted data parcel used in the execute method. For instance:
Given some source data to emulate the $_POST data in the question.
$_POST=array(
array(
'hidden_pid'=>23,
'hidden_p_code'=>'abc-34',
'hidden_p_name'=>'geronimo',
'hidden_dekorA'=>'blah',
'hidden_p_quantity'=>43,
'hidden_p_listprice'=>99,
'hidden_p_netprice'=>120,
'hidden_p_total'=>150,
'hidden_preorderno'=>2,
'hidden_yetkili'=>'tiger'
),
array(
'hidden_pid'=>65,
'hidden_p_code'=>'def-72',
'hidden_p_name'=>'flatfoot',
'hidden_dekorA'=>'aarrrggghhh',
'hidden_p_quantity'=>643,
'hidden_p_listprice'=>69,
'hidden_p_netprice'=>420,
'hidden_p_total'=>150,
'hidden_preorderno'=>8,
'hidden_yetkili'=>'leopard'
),
array(
'hidden_pid'=>84,
'hidden_p_code'=>'toto-x1',
'hidden_p_name'=>'desperate dan',
'hidden_dekorA'=>'zing',
'hidden_p_quantity'=>98,
'hidden_p_listprice'=>89,
'hidden_p_netprice'=>92,
'hidden_p_total'=>100,
'hidden_preorderno'=>5000,
'hidden_yetkili'=>'lynx'
)
);
And the given table structure
mysql> describe siparis;
+-------------+------------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------------+------------------+------+-----+---------+-------+
| product_id | int(10) unsigned | NO | MUL | 0 | |
| p_code | varchar(50) | YES | MUL | NULL | |
| p_name | varchar(50) | YES | | NULL | |
| p_type | varchar(50) | YES | | NULL | |
| p_quantity | varchar(50) | YES | | NULL | |
| p_listprice | varchar(50) | YES | | NULL | |
| p_netprice | varchar(50) | YES | | NULL | |
| p_total | varchar(50) | YES | | NULL | |
| preorderno | int(11) | YES | | NULL | |
| yetkili | varchar(10) | YES | | NULL | |
+-------------+------------------+------+-----+---------+-------+
And a simple Stored Procedure
DELIMITER //
CREATE PROCEDURE `NEWLIST`(
IN `pid` int(11),
IN `p_code` varchar(100),
IN `p_name` varchar(100),
IN `dekorA` varchar(100),
IN `p_quantity` varchar(100),
IN `p_listprice` varchar(100),
IN `p_netprice` varchar(100),
IN `p_total` varchar(100),
IN `preorderno` int(11),
IN `yetkili` varchar(10)
)
LANGUAGE SQL
NOT DETERMINISTIC
CONTAINS SQL
SQL SECURITY DEFINER
COMMENT ''
BEGIN
INSERT INTO siparis
( `product_id`, `p_code`, `p_name`, `p_type`, `p_quantity`, `p_listprice`, `p_netprice`, `p_total`, `preorderno`, `yetkili` )
VALUES
( pid, p_code, p_name, dekorA, p_quantity, p_listprice, p_netprice, p_total, preorderno, yetkili);
END //
DELIMITER ;
Then, in PHP, to build the query dynamically you could do this:
$sp='NEWLIST'; // The name of the Stored Procedure
$sql=sprintf('SELECT group_concat( ":",`parameter_name` ) as `placeholders`
FROM `information_schema`.`parameters`
WHERE `SPECIFIC_NAME`="%s" and `specific_schema`=database()', $sp );
/*
The above would yield a concatenated string such as
:pid,:p_code,:p_name,:dekorA,:p_quantity,:p_listprice,:p_netprice,:p_total,:preorderno,:yetkili
which looks good as the placeholder argument that you would
supply to the stored procedure.
*/
$res=$connect->query( $sql )->fetch( PDO::FETCH_OBJ );
$placeholders=$res->placeholders;
# create the basic sql string statement
$sql=sprintf( 'call `%s`( %s );', $sp, $placeholders );
# we need the keys to generate the payload data used in `execute`
$keys=explode( ',', $placeholders );
# create the PDO prepared statement
$stmt=$connect->prepare( $sql );
# process the POST data using foreach for simplicity
foreach( $_POST as $arr ){
# combine the keys with the values and execute the query
$data=array_combine( $keys, array_values( $arr ) );
$stmt->execute( $data );
}
This successfully populates the db with 3 records.
mysql> select * from siparis;
+------------+---------+---------------+-------------+------------+-------------+------------+---------+------------+---------+
| product_id | p_code | p_name | p_type | p_quantity | p_listprice | p_netprice | p_total | preorderno | yetkili |
+------------+---------+---------------+-------------+------------+-------------+------------+---------+------------+---------+
| 23 | abc-34 | geronimo | blah | 43 | 99 | 120 | 150 | 2 | tiger |
| 65 | def-72 | flatfoot | aarrrggghhh | 643 | 69 | 420 | 150 | 8 | leopard |
| 84 | toto-x1 | desperate dan | zing | 98 | 89 | 92 | 100 | 5000 | lynx |
+------------+---------+---------------+-------------+------------+-------------+------------+---------+------------+---------+
3 rows in set (0.00 sec)
edit
In response to the update you posted there are a couple of issues that need addressing, hopefully covered in the following. The changes made have not been tested in any way by me so, as you know, there might be errors.
try{
/*
create and prepare SQL that analyses the stored procedure
outside of any loop. Use the info obtained therein to build the
dynamic SQL query that calls the stored procedure.
This shuld be done ONCE, outside the loop. Within the loop that
processes the POST data you only need to create the payload for
the SQL and execute the statement.
As you had written it there was a new `$res=$connect->query( $sql )->fetch( PDO::FETCH_OBJ );`
and `$stmt=$connect->prepare( $sql );` within the loop.
*/
$sp='NEWLIST'; // The name of the Stored Procedure
$sql=sprintf('SELECT group_concat( ":",`parameter_name` ) as `placeholders`
FROM `information_schema`.`parameters` WHERE
`SPECIFIC_NAME`="NEWLIST" and
`specific_schema`=mydbname', $sp );
$res=$connect->query( $sql )->fetch( PDO::FETCH_OBJ );
$placeholders=$res->placeholders;
$sql=sprintf( 'call `%s`( %s );', $sp, $placeholders );
$keys=explode( ',', $placeholders );
$stmt=$connect->prepare( $sql );
for( $count = 0; $count < count( $_POST['hidden_p_code'] ); $count++ ) {
$main_arr = array(
':pid' => $_POST['hidden_pid'][$count],
':p_code' => $_POST['hidden_p_code'][$count],
':p_name' => $_POST['hidden_p_name'][$count],
':dekorA' => $_POST['hidden_dekorA'][$count],
':p_quantity' => $_POST['hidden_p_quantity'][$count],
':p_listprice' => $_POST['hidden_p_listprice'][$count],
':p_netprice' => $_POST['hidden_p_netprice'][$count],
':p_total' => $_POST['hidden_p_total'][$count],
':preorderno' => $_POST['hidden_preorderno'][$count],
':yetkili' => $_POST['hidden_yetkili'][$count]
);
/*
create the payload used in the SQL execute method and then commit to db.
*/
$data=array_combine( $keys, array_values( $main_arr ) );
$stmt->execute( $data );
}
} catch( PDOException $e ){
return "Insert failed: " . $e->getMessage();
}
Im really sorry asking from here, because too long for comment.
i have been using your solution in my for loop and put them all in try catch.
Am i doing wrong in somewhere ?
try{
$sql=sprintf('SELECT group_concat( ":",`parameter_name` ) as `placeholders`
FROM `information_schema`.`parameters` WHERE
`SPECIFIC_NAME`="NEWLIST" and
`specific_schema`=mydbname', $sp );
for($count = 0; $count<count($_POST['hidden_p_code']); $count++)
{
$main_arr = array(
':pid' => $_POST['hidden_pid'][$count],
':p_code' => $_POST['hidden_p_code'][$count],
':p_name' => $_POST['hidden_p_name'][$count],
':dekorA' => $_POST['hidden_dekorA'][$count],
':p_quantity' => $_POST['hidden_p_quantity'][$count],
':p_listprice' => $_POST['hidden_p_listprice'][$count],
':p_netprice' => $_POST['hidden_p_netprice'][$count],
':p_total' => $_POST['hidden_p_total'][$count],
':preorderno' => $_POST['hidden_preorderno'][$count],
':yetkili' => $_POST['hidden_yetkili'][$count]
);
$res=$connect->query( $sql )->fetch( PDO::FETCH_OBJ );
$placeholders=$res->placeholders;
$sql=sprintf( 'call `%s`( %s );', $sp, $placeholders );
$keys=explode( ',', $placeholders );
$stmt=$connect->prepare( $sql );
foreach( $main_arr as $arr ){
$data=array_combine( $keys, array_values( $arr ) );
$stmt->execute( $data );
}
}
}
catch(\PDOException $e){
return "Insert failed: " . $e->getMessage();
}
My second problem and my main problem, i couldn't insert over 83 rows to mysql. Im not taking any error messages. Adding over 100 rows to div table then when i used submit button then just inserts 83 rows, rest of them it doesn't inserted. If my order is under 83 rows, i am not having any problems. It adds directly to mysql.
According to my research on stackoverflow, people have suggested increasing the max_allow_packet.
I also tried increase max_allowed_packet value from default(1048576 bytes) to 500MB(524288000 bytes). It doesn't work.
I can't find the solution to this one, as I don't even know how to properly explain it in one sentence...
I have this kind of SQL table
id name type locale
-----------------------------
1 foo video en
2 bar video en
3 baz pdf fr
And I'd like to query it to end up with this PHP array
$array =
[
'en' =>
[
[
'name' => 'foo',
'type' => 'video',
],
[
'name' => 'bar',
'type' => 'video',
],
],
'fr' => [
'name' => 'baz',
'type' => 'pdf',
]
]
How can I achieve this? Thanks!
Consider the following:
<?php
/*
DROP TABLE IF EXISTS my_table;
CREATE TABLE my_table
(id SERIAL PRIMARY KEY
,name VARCHAR(12) NOT NULL
,type VARCHAR(12) NOT NULL
,locale CHAR(2) NOT NULL
);
INSERT INTO my_table VALUES
(1,'foo','video','en'),
(2,'bar','video','en'),
(3,'baz','pdf','fr');
SELECT id, name, type, locale FROM my_table ORDER BY id;
+----+------+-------+--------+
| id | name | type | locale |
+----+------+-------+--------+
| 1 | foo | video | en |
| 2 | bar | video | en |
| 3 | baz | pdf | fr |
+----+------+-------+--------+
*/
require('path/to/connection/stateme.nts');
$query = "
SELECT id, name, type, locale FROM my_table ORDER BY id;
";
$result = mysqli_query($db,$query) or die(mysqli_error());
$old_array = array();
while($row = mysqli_fetch_assoc($result)){
$old_array[] = $row;
}
$new_array = array();
foreach($old_array as $row){
$new_array[$row['locale']][] = $row['name'];
}
print_r($new_array);
?>
Outputs:
Array
(
[en] => Array
(
[0] => foo
[1] => bar
)
[fr] => Array
(
[0] => baz
)
)
I want to insert array() key value pair data into a table
<?php
$foreignKey = 2;
$array = array(
'availability' => array(
array('day' => 'monday','time' => 'am'),
array('day' => 'wednesday','time' => 'pm'),
),
);
My availability table - in the beginning
table: availability
| id | foreign_id | day | time |
+-----+--------------+--------+--------+
resultant table:
| id | foreign_id | day | time |
+-----+--------------+----------+--------+
| 1 | 2 | monday | am |
+-----+--------------+----------+--------+
| 2 | 2 |wednesday | pm |
+-----+--------------+----------+--------+
$sql = "INSERT INTO availability ";
You could loop through your array and bind and execute
$stmt->prepare("INSERT INTO availability (fld1, fld2) VALUES(?, ?)");
foreach($array as $row)
{
$stmt->bind_param($row['fld1'], $row['fld2']);
$stmt->execute();
}
$array = array(
array('day' => 'monday','time' => 'am'),
array('day' => 'wednesday','time' => 'pm')
);
foreach($array as $key => $value)
{
$sql = "INSERT INTO `availability`(`foreign_id`, `day`,`time`)VALUES($foreignKey, '$value[day]', '$value[time]') ";
}
i have mysql table:
id | nameEng | NameRus
1 | Moscow | Москва
2 | London | Лондон
What i want is:
$result = array (
1 => array (id => 1, Name => "Москва"),
2 => array (id => 1, Name => "Moscow"),
3 => array (id => 2, Name => "London"),
4 => array (id => 2, Name => "Лондон")
)
Here is my query:
mysql_query("SELECT id, nameRus FROM citynames WHERE nameRus LIKE '%".$_GET['chars']."%'
UNION ALL
SELECT id, nameEng FROM citynames WHERE nameEng LIKE '%".$_GET['chars']."%' ORDER BY nameEng LIMIT 0, 10"
Query working but i want to optimize this query
$l = "like '%". $_GET['chars'] ."%'";
$sql = "(select `id` as `id`, `nameEng` as `name` from `citynames `) union (select `id` as `id`, `NameRus` as `name` from `citynames `) where `name` $l order by `id`;";
i want to insert the values of two arrays into a table in a single query . Is it possible to do something like that.
table format
id | product_id | category_id | blog_id | updated_by | created_date
category _id
Array
(
[0] => 4
[1] => 15
[2] => 18
)
Product_id
Array
(
[0] => 2260
[1] => 1401
)
Blog id = mysql_insert_id();
result
id | product_id | category_id | blog_id | updated_by
1 2260 4 15 xyz
2 1401 15 15 xyz
3 null 18 15 xyz
Any suggestions for me also to improve the better insert query for this.
INSERT INTO `Table_Name` (`product_id`, `category_id`, `blog_id`, `updated_by`) VALUES (2260, 4, 15, 'xyz'), (1401, 15, 15, 'xyz'), (, 18, 15, 'xyz');
I assumed that id column is an auto incremented one.
You can insert multiple rows at one go in the same query that you are using now. Just add a comma, and put in more values:
Insert into myTable values ('field1-var1','field2-var2'), ('field1-var2','field2-var2') ..
$combain = array_merge($cat , $proid);
for($i = 0; $i <count($combain); $i++ )
{
if(isset($proid[$i])) {
$product_id = $proid[$i];
}
else{
$product_id = "''";
}
if(isset($cat[$i])){
$category_id = $cat[$i];
}
else{
$category_id = "''";
}
if(!empty($cat[$i]) || !empty($proid[$i])) {
#$values[] ="('',". $blogid.",".$category_id.",".$product_id.","."'".$updated_by."'".",now())";
}
}
$query = $this->db->query("insert into blog_details (id , blog_id , cat_id, pro_id, updated_by , created_date) values" . implode(',', $values));