How to do foreach loop through different variable in php - php

I have a dynamic form which have dynamic input of textbox and variable of date,float and time.I want to insert those input dynamically into my sql table.
So here is the part of my code.I'm only able to loop through one variable,When i want to loop through the time and float,it face the conversion problem on float and time.(If any picture needed just let me know )
$ct = 0;
if ($_POST['Dates'] && $_POST['slct']) {
foreach ($_POST['Dates'] as $value) {
$values = $value;
$dates = $_POST['Dates']; // for leave date
$datess = $_POST['datess']; // for created date
$Area = $_COOKIE['cooAreaCode'];
$days = $_POST['slct'];
$time = date("h:i a", strtotime($frtime));
$times = date("h:i a", strtotime($totime));
$frtime = $_POST['frtime'];
$totime = $_POST['totime'];
$link_mssql = odbc_connect(DB_HSATTEND, DB_USER, DB_PASS);
$sql = "SELECT MAX(RefNo) as val from tblLeaveHeader";
$res = odbc_exec($link_mssql, $sql);
while (odbc_fetch_row($res)) {
$count = odbc_result($res, "val");
}
odbc_free_result($res);
$temp = sprintf('%08d', $count + 1);
if (empty($_POST['frtime']) && empty($_POST['totime'])) {
$sql3 = "INSERT INTO tblLeaveDetails (RefNo, LeaveType, Leavedd, Leaveday, LeaveFrmTime, LeaveToTime)
VALUES('$temp','$Leave','$values', '$days[$ct]', NULL, NULL)";
$res = odbc_exec($link_mssql, $sql3);
$ct++;
} else {
$sql2 = "INSERT INTO tblLeaveDetails (RefNo, LeaveType, Leavedd, Leaveday, LeaveFrmTime, LeaveToTime)
VALUES('$temp','$Leave','$values', '$days[$ct]', '$frtime[$ct]', '$totime[$ct]')";
$res = odbc_exec($link_mssql, $sql2);
$ct++;
}
}
}
Example of result in sql table
| ID | Refno | Leavetype | Leaveday | Leavdd |frtime|totime
| 1 | 00001 | Annual Leave | 1 | 2017-07-17 |3.00 | 7.00
| 2 | 00001 | Annual Leave | 1 | 2017-07-18 |4.00 | 6.00

Related

How to select and assign to a specific $key, a specific $value, among multiple choices?

I have a MySQL table with multiple columns, from which I need to select all of them of each record, and to create a specific $key=>$value from it.
for example
TABLE
ID | group_cat | group_sec | group_name | enabled | sent
-------------------------------------------------------------------------------------
1 | C | sct_a | Project_A | 1 | no
2 | C | sct_b | Project_B | 1 | no
3 | P | sct_c | Moderators | 1 | no
4 | C | sct_d | Ambassad | 1 | no
5 | P | sct_e | PMP | 0 | no
The MySQL query I need is "SELECT * FROM groups WHERE sent = 'no' "
By PHP is
PHP Code
$query = "SELECT * FROM `groups` WHERE `sent`= 'no' ";
$sth = $sql->prepare($query);
$sth->execute();
while($row = $sth->fetch(PDO::FETCH_ASSOC)) {
foreach($row as $key => $value) { $$key = $value; }
...
...
...
}
Here my question:
I need that the $key is from the column 'group_sec' and the related $value is from the column 'group_name'. So that the couple $$key=>$value can return this result (for instance)
echo $sec_b;
returns: Project_B
Could you help me to get this done please?
Thank you in advance
This will do the job for you:
${$row['group_sec']} = $row['group_name'];
echo $sct_b;
Output:
Project_B
You would use this in your while loop (the foreach can probably be deleted):
while($row = $sth->fetch(PDO::FETCH_ASSOC)) {
${$row['group_sec']} = $row['group_name'];
...
// do something with $sct_b
...
}
Alternatively, if your column names might change, but the positions will stay the same, you can use
while($row = $sth->fetch(PDO::FETCH_NUM)) {
${$row[2]} = $row[3];
...
// do something with $sct_b
...
}
You can build an array based on key and value you prefer using $row['group_sec'] for key and $row['group_name'] eg:
$query = "SELECT * FROM `groups` WHERE `sent`= 'no' ";
$sth = $sql->prepare($query);
$sth->execute();
while($row = $sth->fetch(PDO::FETCH_ASSOC)) {
$myArray[$row['group_sec']] = $row['group_name'];
}
and you can see the result
foreach($myArray as $key => $value){
echo $key . ' - ' . $value . '<br>';
}
$sql = "SELECT * FROM groups WHERE sent= 'no'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
$list=[];
while($row = $result->fetch_assoc()) {
$list{$row['group_sec']} = $row['group_name'];
}
}

Format array outputs in form serialize PHP

Im currently using the json_encode in converting array to strings
which outputs data in a straight pattern in my table
user
-----------
id | name
-------------------------------------------
1 |"name1","name2","name3","name4","name5"
But i want to have an output where the table data will look like this.
user
-----------
id | name
-----------
1 | name1
2 | name2
3 | name3
4 | name4
5 | name5
My PHP code
<?php
$connect = mysqli_connect("localhost", "root", "", "dbsample");
if(isset($_POST["check_val"])){
$check_val = htmlspecialchars(strip_tags("check_val"));
$number = json_encode($_POST["name"]);
for ($i = 0; $i < count($number); $i++) {
if ($number[$i] != "") {
$query = "INSERT INTO tbl_name(name) VALUES (?)";
$stmt = $connect->prepare($query);
$number[$i] = htmlspecialchars(strip_tags($number[$i]));
$stmt->bind_param("s", $number);
if($stmt->execute()) {
echo "SUCCESS";
# code...
}else
{
echo "ERROR";
}
}
else{
echo "Please Enter Name";
}
}
}
?>

php mysql match value from multiple values a column

I want to find a value from a column which has multiple values like (23,24,25), Using php mysqli query.
Table:
+-----------------+
id | tag_ids |
+-----------------+
1 | 3,4,5 |
2 | 3,7,8,9 |
3 | 4,5,10 |
Curent query:
$value = '3';
$query = "SELECT tag_ids FROM table WHERE FIND_IN_SET($value, tag_ids)";
$result = mysqli_query($query);
$count = mysqli_num_rows($result);
echo count;
Result will be: YES/NO or 1/0, if the Given value is match any value with tag_ids.
I found the result my self and here is code:
function statusvalues() {
$query = "SELECT tag_ids FROM tblname WHERE tag_ids !=''";
$result = mysqli_query($query, DBCONN);
$idarray = array();
while($row = mysqli_fetch_array($result)) {
array_push($idarray, $row['tag_ids']);
}
return $idarray;
}
function status($ID) { //Passing tag id
$set_of_numbers = statusvalues();
$reset_numbers = implode(", ", $set_of_numbers);
$values = explode(", ", $reset_numbers);
if (in_array($ID, $values)){
return "disabled";
}
}

How to create a JSON from table PHP

How to create a json like this in php;
[{"idorder":"34",
"totalOrder":"55",
"products":[{"idproduct":"5","price":"10"},{"idproduct":"4","price":"45"}]
}]
from table mysql;
+---------+-----------+--------------+
| idorder | idproduct | priceproduct |
+---------+-----------+--------------+
| 1 | 4 | 45 |
| 1 | 5 | 10 |
+---------+-----------+--------------+
my current code something.php;
...
$result = $conn->query($pendientesq);
$return_arr = array();
$productos = array();
$r1=$result->fetch_array();
$return_arr['idorder'] = $r1['idorder'];
$return_arr['totalOrder'] = '55';
//But now????How to create sub array with multiples products.
echo json_encode($return_arr);
you need to try something like this:
$r1=$result->fetch_array();
$return_arr['idorder'] = $r1['idorder'];
$return_arr['totalOrder'] = '55';
// suposse total products are 10
$product=10;
for($i=0;$i<product;$i++){
$return_arr['product'][] = array("idproduct"=>$i,"price"=>$i);//use your price and idproduct.
}
echo json_encode($return_arr);
I don't know how Your table looks like because You've not described it.
But I got for example "orders" table with idorder,idproduct,priceproduct fields.
And wrote this code:
// $q = "SELECT * FROM orders WHERE idorder = 5"; // for single order
$q = "SELECT * FROM orders";
$result = $conn->query($q);
$orders = [];
while($record=$result->fetch_array()) {
if(!isset($orders[$record['idorder']])) {
$orders[$record['idorder']] = [];
$orders[$record['idorder']]['idorder'] = $record['idorder'];
$orders[$record['idorder']]['totalOrder'] = 0;
$orders[$record['idorder']]['products'] = [];
}
$orders[$record['idorder']]['products'][] = ['idproduct' => $recrod['idproduct'],
'price' => $record['priceproduct']];
$orders[$record['idorder']]['totalOrder'] += $record['priceproduct'];
}
$orders = array_values($orders);
echo json_encode($orders);

Best way of getting a row result with out having to do several querys?

One of the fields coming from the db is separated by "," eg(1,2,3,4,5)
This is the code I'm using:
$result = mysqli_query($con, "SELECT * FROM login WHERE phone=$user");
while ($row = mysqli_fetch_array($result)) {
$friends = $row['friends'];
$data = $friends;
$arr = explode(',', $data);
$today = date("d F", strtotime($row['time']));
$hour = date('g:i',
strtotime($row['time']));
if ($today < $row['time']) {
$today;
} else {
$today = $hour;
};
for ($i = 0; $i < count($arr); $i++) {
$friend = array($data);
foreach($friend as $value) {
echo "
<div class='contacts_item sep_cont'>
<img class='user_img' src='".$row['picture']."'>
<div class='contacts_title'>".$arr[$i]."<div class='time'>".$today."</div></div>
<div>".$row['name']."</div> </div> ";
}
}
}
Any advice?
If I understand what you want I think you can create a table with only the relation between login and friends like
TABLE login_friends
id | login_id | friend_id |
1 | 1 | 2 |
2 | 1 | 3 |
3 | 2 | 3 |

Categories