I have 2 foreach loop which gets colors and sizes. I also have for loop which generate the material number. I'm trying to achieve distribute the variables well for example I have 2 colors with 3 sizes.
This is the desired output
Material# | Color | Size
1001 | Blue | Small
2001 | Blue | Medium
3001 | Blue | Large
4001 | Green | Small
5001 | Green | Medium
6001 | Green | Large
Here's my code:
//insert material number
for($x = 1; $x <= $matnumbersize; $x++ )
{
$matnummm= str_pad($x, 3, '0', STR_PAD_LEFT);
$materialnumber = $newgennumber.$matnummm;
$matnumberr[] = $materialnumber; //materialnumber
$stmt = $db->prepare("INSERT INTO materialnumber(productID,stylecodeID,genericnumberID,materialnumber) VALUES(:pid,:scode,:gcode,:matnum)");
$stmt->execute(array(':pid' => $productID, ':scode' => $styleID, ':gcode' => $gennumID, ':matnum' => $materialnumber));
}
print_r($matnumberr);
$statement = $db->prepare("SELECT * FROM productcolor a, color b where a.productID = :pid and a.colorID = b.colorID ");
$statement->execute(array(':pid' => "$productID"));
foreach ($statement->fetchAll() as $row)
{
$colorcode = $row['colorCode'];
$statement = $db->prepare("SELECT * FROM productsizes where productID = :pid ");
$statement->execute(array(':pid' => "$productID"));
foreach ($statement->fetchAll() as $row)
{
$sizeCde = $row['sizeName'];
echo $colorcode.$sizeCde.'<br/>';
}
}
I tried my best but I cant think a fix of it. Thank you!
I fixed it and manage to make it shorter so here's my code
$y = 1;
$statement = $db->prepare("SELECT * FROM productcolor a, color b where a.productID = :pid and a.colorID = b.colorID ");
$statement->execute(array(':pid' => "$productID"));
foreach ($statement->fetchAll() as $row)
{
$colorcode = $row['colorCode'];
$statement = $db->prepare("SELECT * FROM productsizes where productID = :pid ");
$statement->execute(array(':pid' => "$productID"));
foreach ($statement->fetchAll() as $row)
{
$sizeCde = $row['sizeName'];
echo $colorcode.$sizeCde.'<br/>';
$yy= str_pad($y, 3, '0', STR_PAD_LEFT);
$newmaterialnum = $newgennumber.$yy;
$stmt = $db->prepare("INSERT INTO materialnumber(productID,stylecodeID,genericnumberID,materialnumber,color,size)
VALUES(:pid,:scode,:gcode,:matnum,:color,:size)");
$stmt->execute(array(':pid' => $productID, ':scode' => $styleID, ':gcode' => $gennumID, ':matnum' => $newmaterialnum,
':color' => $colorcode, ':size' => $sizeCde));
$y++;
}
}
Related
I have my 3 arrays which I put into these variables:
$title = $_REQUEST['test_bestellte_title'];
$anzahl = $_REQUEST['test_bestellte_anzahl'];
$groesse = $_REQUEST['test_bestellte_groesse'];
I want to insert this array of values into the sql table like
ID | Anzahl | title | groesse
-----------------------------------------
1 | 4 | Schulkind Shirt gelb | S
1 | 5 | Friends Shirt lila | M
1 | 3 | Shirt Sesamstraße | S
1 | 4 | Shirt Sesamstraße | L
But I have no clue how to insert it like shown above
I split them up with for each so far, that's where I'm stuck
foreach ($anzahl as $einzelanzahl) {
echo $einzelanzahl['test_bestellte_anzahl'];
}
foreach ($title as $einzeltitle) {
echo $einzelname['test_bestellte_groesse'];
}
foreach ($groesse as $einzelgroesse) {
echo $einzelgroesse['test_bestellte_artikel'];
}
Thanks in advance!
If all arrays with the same length:
$title = $_REQUEST['test_bestellte_title'];
$anzahl = $_REQUEST['test_bestellte_anzahl'];
$groesse = $_REQUEST['test_bestellte_groesse'];
$mysqli = new mysqli("localhost","my_user","my_password","my_db");
// Check connection
if ($mysqli -> connect_errno) {
echo "Failed to connect to MySQL: " . $mysqli -> connect_error;
exit();
}
$stmt = $mysqli->prepare("INSERT INTO MyTable (`Anzahl`, `title`,
`groesse`) VALUES (?, ?, ?)");
for ($i = 0; $i < count($title); $i) {
// prepare and bind
$stmt->bind_param($title[$i], $anzahl[$i], $groesse[$i]);
$stmt->execute();
}
$stmt->close();
$mysqli->close();
Assuming the three arrays are always keyed identically, use a single loop:
$arrayOne = array('a', 'b', 'c', 'd');
$arrayTwo = array('w', 'x', 'y', 'z');
$arrayThree = array('m', 'n', 'o', 'p');
foreach ($arrayOne as $key => $valueOne) {
$valueTwo = $arrayTwo[$key];
$valueThree = $arrayThree[$key];
// save your table row to database...
echo "key: $key one: $valueOne two: $valueTwo three: $valueThree<br/>";
}
/* output:
key: 0 one: a two: w three: m
key: 1 one: b two: x three: n
key: 2 one: c two: y three: o
key: 3 one: d two: z three: p
*/
I mean you can use next peace of code:
<?php
$title = $_REQUEST['test_bestellte_title'];
$anzahl = $_REQUEST['test_bestellte_anzahl'];
$groesse = $_REQUEST['test_bestellte_groesse'];
$query = "INSERT INTO the_table (ID, Anzahl, title, groesse) VALUES (?, ?, ?, ?)";
$stmt = $pdo->prepare($query);
foreach ($title as $id=>$einzelanzahl) {
$stmt->execute([1, $title[$i], $anzahl[$i], $groesse[$i]]);
}
PHP PDO online
I have problems with the following code. I get duplicate entries of the content in the database.
I think it has something to do with the for loop, but I don't know how I could correct it.
SQL query:
public function getConfRoomList()
{
$arr = array();
$statement = $this->conn->prepare("SELECT id, name, roomnbr, location, seats, utilities from moterom order by name ASC");
$statement->bind_result($id, $name, $roomnbr, $location, $seats, $utilities);
$statement->execute();
while ($statement->fetch()) {
$arr[] = [ "id" => $id, "name" => $name, "roomnbr" => $roomnbr, "location" => $location, "seats" => $seats, "utilities" => $utilities];
}
$statement->close();
return $arr;
}
public function joinDevRoom()
{
$arr = array();
$statement = $this->conn->prepare("SELECT r.name,GROUP_CONCAT(u.device) FROM moterom r LEFT JOIN utilities u ON FIND_IN_SET(u.id,r.utilities)>0 GROUP BY r.id");
$statement->bind_result($id, $utilities);
$statement->execute();
while ($statement->fetch()) {
$utilities = str_replace(',','<br />',$utilities);
$arr[] = [ "id" => $id, "utilities" => $utilities];
}
$statement->close();
return $arr;
}
public function getDeviceList()
{
$arr = array();
$statement = $this->conn->prepare("SELECT id, device, model, img, supplier from utilities order by device ASC");
$statement->bind_result($id, $device, $model, $img, $supplier);
$statement->execute();
while ($statement->fetch()) {
$arr[] = [ "id" => $id, "device" => $device, "model" => $model, "img" => $img, "supplier" => $supplier];
}
$statement->close();
return $arr;
}
The content:
<?php
require_once("db.php");
$arr = $conn->getConfRoomList();
$join = $conn->joinDevRoom();
$dev = $conn->getDeviceList();
?>
<div class="add_dev_header">Møterom</div>
<?php
if (!empty($arr)) { ?>
<table border='1'>
<tr>
<th>Conference room</th>
<th>Room number</th>
<th>Location</th>
<th>Number of seats</th>
<th>Available utilities</th>
<th>Edit</th>
<th>Delete</th>
</tr>
<?php for( $i=0; $i < count($arr); $i++) {
for( $u=0; $u < count($join); $u++) {
print_r ("<tr>
<td>".$arr[$i]['name']."</td>
<td>".$arr[$i]['roomnbr']."</td>
<td>".$arr[$i]['location']."</td>
<td>".$arr[$i]['seats']."</td>
<td>".$join[$u]['utilities']."</td>
<td><a href='?p=editconfroomv2&id=".$arr[$i]['id']."'>Edit</a></td>
<td><a href='?p=deleteconfroomdb&id=".$arr[$i]['id']."' class='delete'>Delete</a></td>
</tr>"); } } ?>
</table>
<?php } else {
echo "<div id='db_empty'>Database is empty...<br>
You can be the first to <a href='?p=addconfroom'>register a conference room</a>.</div>";
}
?>
I have two rooms and one utility in the databases, and the printed result looks something like this:
Room 1 | Room number 1 | Location 1 | Seats 23 | Gear 1 | Edit | Delete
Room 1 | Room number 1 | Location 1 | Seats 23 | Gear 1 | Edit | Delete
Room 2 | Room number 2 | Location 2 | Seats 6 | Gear 1 | Edit | Delete
Room 2 | Room number 2 | Location 2 | Seats 6 | Gear 1 | Edit | Delete
I'm trying to remove duplicate results from my SQL query using PHP.
table categories:
id | name
1 | sony
2 | nintendo
table subcategories:
id | name | category_id
1 | playstation | 1
2 | playstation2 | 1
3 | wii | 2
table video_games
id | name | subcategories
1 | grand theft auto | 1,2
2 | super mario | 3
My PHP code:
$query = $database->query('SELECT id FROM subcategories WHERE category_id = "'.$_GET['id'].'"');
while($return = $query->fetch()) {
$subcategories = $return['id'];
$request = '%'.$subcategories.'%';
$game_query = $database->prepare('SELECT * FROM video_games WHERE subcategories LIKE :request');
$game_query->bindValue('request', $request);
$game_query->execute();
if($game_query->rowCount() > 0) {
while($game_return = $game_query->fetch()) {
echo $game_return['name'];
}
}
}
My code works but I have duplicate video games when there have multi subcategories.
I tried using SELECT DISTINCT * FROM video_games WHERE subcategories LIKE :request but same problem.
Any idea to remove duplicate results using SQL or PHP ?
MySql is able to solve this problem by its own means.
Use 'DISTINCT' and 'FIND_IN_SET'.
Like this:
"SELECT DISTINCT
vg.id,
vg.name,
vg.subcategories
FROM
video_games vg
WHERE
FIND_IN_SET( (SELECT id FROM subcategories WHERE category_id='".$_GET['id'])."' , vg.subcategories ) > 0 "
and also you can use array_unique at first save video game names in an array and next remove duplicate value.
.
.
.
your code
.
.
$game_query->execute();
if($game_query->rowCount() > 0) {
$fetch =array_unique($game_query->fetch());
foreach ($fetch as $key => $value){
echo $value;
}
}
test
<pre>
<?php
$arr=array("name"=>"1","name2"=>"2","name1"=>"2","name3"=>"3","name4"=>"1","name5"=>"2","name6"=>"3","name7"=>"22");
print_r($arr);
$fetch =array_unique($arr);
print_r($fetch);
foreach ($fetch as $key => $value)
echo $key."=>".$value."<br>";
?>
</pre>
You can save video game names in an array, and print it afterwards. For example:
$games = array();
$query = $database->query('SELECT id FROM subcategories WHERE category_id = "'.$_GET['id'].'"');
while($return = $query->fetch()) {
$subcategories = $return['id'];
$request = '%'.$subcategories.'%';
$game_query = $database->prepare('SELECT * FROM video_games WHERE subcategories LIKE :request');
$game_query->bindValue('request', $request);
$game_query->execute();
if($game_query->rowCount() > 0) {
while($game_return = $game_query->fetch()) {
if (!in_array($game_return['name'], $games)) {
$games[] = $game_return['name'];
}
}
}
}
//now print the games
foreach ($games as $game) {
echo $game;
}
EDIT If you want more than just 'name', you can expand $games array with $key => $value combination. For example:
. . .
while($game_return = $game_query->fetch()) {
foreach ($games as $game) {
if ($game['name'] === $game_return['name']]) {
continue 2;
}
}
$games[] = array(
'name' => $game_return['name'],
'price' => $game_return['price'],
)
}
And afterwards print it like:
foreach ($games as $game) {
echo $game['name'];
echo $game['price'];
}
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
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);