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.
Related
I have a nested array like the following:-
array(
array(
'id' => 45cfeteuid536hjj929,
'name' = 'Cuisines',
'children' => array(
array(
'id' => 45gcfeteuid536hjj929,
'name' = 'Itlaian',
),
array(
'id' => 45bjfe78ng5d536hjj92,
'name' = 'Indian',
'children' => array(
array(
'id' => 457hfe78ng5d53ghy56j,
'name' = 'Punjabi'
)
)
)
)
)
);
I have a table like this:-
|--------------------------------|
| id | name | parent_id |
|--------------------------------|
I want data to be inserted like this:-
|---------------------------------------------------------------|
| id | name | parent_id | api_id |
|---------------------------------------------------------------|
| 1 | Cuisines | 0 | 45cfeteuid536hjj929 |
|---------------------------------------------------------------|
| 2 | Italian | 1 | 45gcfeteuid536hjj929 |
|---------------------------------------------------------------|
| 3 | Indian | 1 | 45bjfe78ng5d536hjj92 |
|---------------------------------------------------------------|
| 4 | Punjabi | 3 | 457hfe78ng5d53ghy56j |
|---------------------------------------------------------------|
The parent_id of the child is the id of the object to which it belongs. The id of the table are autoincrement value generated automatically by the mysql db.
For example:-
Step 1: While saving Cuisine, the id (autoincrement in nature) saved
is 1. Since it is the root, hence parent_id = 0.
Step 2: While saving Italian, the id (autoincrement in nature)
saved is 1. Since it is a child of Cuisines, the parent_id = 1
How can I save the nested array in such way?
One way would be to generate insert statements that look like this (assuming your table is called tab):
insert into tab(name, parent_id, app_id)
select 'Cuisines', coalesce(min(id), 0), '45cfeteuid536hjj929' from tab
where app_id = '';
insert into tab(name, parent_id, app_id)
select 'Itlaian', coalesce(min(id), 0), '45gcfeteuid536hjj929' from tab
where app_id = '45cfeteuid536hjj929';
insert into tab(name, parent_id, app_id)
select 'Indian', coalesce(min(id), 0), '45bjfe78ng5d536hjj92' from tab
where app_id = '45cfeteuid536hjj929';
insert into tab(name, parent_id, app_id)
select 'Punjabi', coalesce(min(id), 0), '457hfe78ng5d53ghy56j' from tab
where app_id = '45bjfe78ng5d536hjj92';
These queries will find the parent ID via the app_id that parent should have. No value for the id column is inserted, as it is assumed that the database will generate it upon insertion.
Here is a recursive PHP function which generates those statements. You'll have to adapt it to actually execute those statements with whatever API you use (PDO, mysqli, ...):
function insertRecords($data, $parent = "") {
foreach($data as $row) {
// Replace next echo statement with the code to actually execute this SQL:
echo "insert into tab(name, parent_id, app_id) select '$row[name]', coalesce(min(id), 0), '$row[id]' from tab where app_id = '$parent';\n";
if (isset($row["children"])) insertRecords($row["children"], $row["id"]);
}
}
Assuming your nested data structure is stored in variable $data, call the above function like this:
insertRecords($data);
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 table:
+---------------+------------------------------+-----+------+
| id_order | id_product | qty | size |
+---------------+------------------------------+-----+------+
| ORD-0413-17-1 | PRD-0408-17-2,PRD-0412-17-11 | 2,3 | M,S |
+---------------+------------------------------+-----+------+
I would like to have an output like this:
+---------------+---------------+-----+-------+
| id_order | id_product | qty | size |
+---------------+----------------+-----+------+
| ORD-0413-17-1 | PRD-0408-17-2 | 2 | M |
| ORD-0413-17-1 | PRD-0412-17-11 | 3 | S |
+---------------+----------------+-----+------+
How I can do this?
Here's one way in which to build a normalized 'result' from your 'data'... I'm using a simple utility table of integers (0-9), but you could just use a bunch of UNIONs instead.
DROP TABLE IF EXISTS my_table;
CREATE TABLE my_table
(id_order VARCHAR(20) NOT NULL
,id_product VARCHAR(255) NOT NULL
,qty VARCHAR(30) NOT NULL
,size VARCHAR(30) NOT NULL
);
INSERT INTO my_table VALUES
('ORD-0413-17-1','PRD-0408-17-2,PRD-0412-17-11','2,3','M,S');
DROP TABLE IF EXISTS ints;
CREATE TABLE ints(i INT NOT NULL PRIMARY KEY);
INSERT INTO ints VALUES (0),(1),(2),(3),(4),(5),(6),(7),(8),(9);
SELECT DISTINCT id_order
, SUBSTRING_INDEX(SUBSTRING_INDEX(id_product,',',i+1),',',-1) id_product
, SUBSTRING_INDEX(SUBSTRING_INDEX(qty,',',i+1),',',-1) qty
, SUBSTRING_INDEX(SUBSTRING_INDEX(size,',',i+1),',',-1) size
FROM my_table,ints;
id_order id_product qty size
ORD-0413-17-1 PRD-0408-17-2 2 M
ORD-0413-17-1 PRD-0412-17-11 3 S
in my case, am using method in class php, this is the method :
public function user_checkout($params){
$date = new DateTime(date('Y-m-d'));
$date->modify('+3 day');
$query = "SELECT * FROM cart WHERE id_session='".$params['id_user']."'";
$sql = $this->db->query($query);
$data1 = array();
$data2 = array();
$data3 = array();
while($result = $sql->fetch_assoc()){
$data1[] = $result['id_product'];
$data2[] = $result['qty'];
$data3[] = $result['size'];
}
$data_insert = array(
"id_order" => $params['id_order'],
"id_product" => implode(',', $data1),
"id_user" => $params['id_user'],
"qty" => implode(',', $data2),
"size" => implode(',', $data3),
"account_name" => $params['name_of_account'],
"account_number" => $params['no_rekening'],
"amount" => $params['amount'],
"total_price" => $params['total_price'],
"out_of_date" => $date->format('Y-m-d'),
"order_date" => date('Y-m-d')
);
$insert = "INSERT INTO `order_product`(`id_order`, `id_product`, `id_user`, `qty`,`size`, `account_name`, `account_number`, `amout`, `total_price`, `out_of_date`, `order_date`, `status`) VALUES ('".$data_insert['id_order']."','".$data_insert['id_product']."','".$data_insert['id_user']."','".$data_insert['qty']."','".$data_insert['size']."','".$data_insert['account_name']."','".$data_insert['account_number']."','".$data_insert['amount']."','".$data_insert['total_price']."','".$data_insert['out_of_date']."','".$data_insert['order_date']."',0)";
$sql_insert = $this->db->query($insert);
$delete = "DELETE FROM cart WHERE id_session = '".$params['id_user']."'";
$sql_delete = $this->db->query($delete);
return true;
}
i have this table produced from the query SELECT * FROM myTable
+--------------------------+---------+--------+
| Name | Version | Detail |
+--------------------------+---------+--------+
| name0 | 10 | xxx |
| name1 | 30 | yyy |
| name2 | 30 | zzz |
| name3 | 30 | kkk |
+--------------------------+---------+--------+
so, i need to have this table in a php array using mysqli function.
//$this->internalDB have the db connection
$result = $this->internalDB->query($query)->fetch_array(MYSQLI_NUM);
print_r($result);
produced
Array ( [Name] => name0 [Version] => 10 [Detail] => xxx )
cycles with the speech does not change ...
how i can do that?
This will query a database and return your values as an associative array in the $arrReturn variable.
$mysqli = new mysqli("host", "user", "password", "database");
$query = "SELECT * FROM myTable";
$sqlRes = $mysqli->query($query);
if (is_object($sqlRes)) {
$arrReturn = array();
while ($row = $sqlRes->fetch_assoc()) {
$arrRow = array();
foreach($row as $field => $value) {
$arrRow[$field] = $value;
}
$arrReturn[] = $arrRow;
}
echo $arrReturn[0]['Name']; // prints 'name0'
}
It might be helpful to read through the mysqli quickstart guide
I have a table "exercise_results". People put in their results at the beginning and then two months later put in their results to see how much they improved. Their beginning set has the exercise_type_id of "1" and the end set has the exercise_type_id of "2".
I need a way to display this out into a HTML table that looks like this:
a foreach loop, but that's with single rows. I'm having trouble combining two rows into one. I think this may be as simple as some kind of MySQL join? We identify each person by their person_unique_id.
Here are my fields:
id | person_unique_id | person_name | exercise_type_id | mile_running_time | bench_press_weight_lbs | squat_weight_lbs | date_of_exercise_performed
Sample rows:
1 | J123 | John Smith | 1 | 8 | 200 | 300 | 2010-03-20
2 | J123 | John Smith | 2 | 7 | 250 | 400 | 2010-05-20
3 | X584 | Jane Doe | 1 | 10 | 100 | 200 | 2010-03-20
4 | X584 | Jane Doe | 2 | 8 | 150 | 220 | 2010-05-20
I've tried a few solutions but I'm lost. Any help would be great. Thanks!
EDIT:
In response to the comment below, I would hope for some data like:
array 0 =>
array
'Exercise' =>
array
'person_unique_id' => string 'J123'
'person_name' => string 'John Smith'
'begin_mile_running_time' => string '8'
'end_mile_running_time' => string '7'
1 =>
array
'Exercise' =>
array
'person_unique_id' => string 'X584'
'person_name' => string 'Jane Doe'
'begin_mile_running_time' => string '10'
'end_mile_running_time' => string '8'
You can use GROUP_CONCAT() to get a two rows result like this:
SELECT person_unique_id, person_name,
group_concat( mile_running_time ) AS miles,
group_concat( bench_press_weight_lbs ) AS bench,
GROUP_CONCAT( squat_weight_lbs ) AS squat
FROM exercise_result
GROUP BY person_unique_id
Your result will be like:
J123 | John Smith | 8,7 | 200,250 | 300,400
X584 | Jane Doe | 10,8 | 100,150 | 200,220
And then you can use php explode with the result fields to get the results for each type.
Extract the whole table, or whichever rows are interesting to you, sort on person id, compare person id of each row with the next to see if there is a result to print for all columns in your HTML table. If not, jump to the next and leave the fields blank(or some other solution, maybe ignore persons who have not filled in both fields?).
My PHP skills are limited, so no code example.
$query = mysql_query("select ...your data");
while ($row = mysql_fetch_assoc ($query) ) {
if ($row['exercise_type_id']==1)
$exe1[]=$row;
else
$exe2[]=$row;
}
print_r($exe1);
print_r($exe2);
from what I've understood
edit:
try this
$query = mysql_query("select ...your data");
while ($row = mysql_fetch_assoc ($query) ) {
$rows[]=array('Exercise'=>$row);
}
print_r($rows);
If you are ordering on person_unique_id then exercise_type_id, you can do this. If you have two rows for everyone, you can leave out the if (only use the else):
for( $i = 0; $i < count($exercise_results); $i++ )
{
$first = $exercise_results[$i];
if( !isset($exercise_results[$i+1])
|| $first['person_unique_id'] != $exercise_results[$i+1]['person_unique_id' ) {
$second = array(
'person_name'=>$other['person_name'],
'mile_running_time' => null // fill in the rest with defaults (like null)
);
} else {
$second = $exercise_results[$i+1];
$i++; // skip ahead one, since you've already used the second result.
}
// perform your normal printing, but use $beginning and $end to get the respective results
}