How to deal with arrays in PHP language - php

<?php
$con = mysqli_connect('localhost', 'root', '');
if(!$con)
{
die("not ok");
}
mysqli_select_db($con,"uoh");
$q1 = "SELECT * FROM student_record INNER JOIN degree_plan ON
student_record.course_number = degree_plan.course_number
INNER JOIN courses ON student_record.course_number =
courses.course_number where student_record.id = 201102887 AND degree_plan.major='COE'";
$result = mysqli_query($con , $q1 ) ;
$data = array();
while($row = mysqli_fetch_array($result))
{
$data[$row["term_no"]][] = array(
'code' => $row["code"],
'grade' => $row["grade"]
);
}
echo '<table width="200" border="1">';
echo "<tr>";
echo "<th>courses</th>";
echo "<th>terms</th>";
echo "<th>grades</th>";
echo "</tr>";
foreach($data as $term=>$otherrow) {
$count = 0;
foreach ($otherrow as $data) {
if($count == 0) {
echo "<tr>";
echo "<td>" . $data["code"]. "</td>";
echo '<td rowspan="'.count($otherrow).'">' . $term. '</td>';
echo "<td>" . $data["grade"]. "</td>";
echo "</tr>";
}
else
{
echo "<tr>";
echo "<td>" . $data["code"]. "</td>";
echo "<td>" . $data["grade"]. "</td>";
echo "</tr>";
}
$count++;
}
}
echo "</table>";
?>
I have this code and it work very well but I faced problem when I want to add more column .
I tried to add fourth column(echo "<td>" . $row["crd"]. "</td>"; ) but there is no result .It give me empty cells. how I can do that?
I want add add this echo "<td>" . $row["crd"]. "</td>"; column to my code.

As mentioned in the comments, there are two errors that have been noticed.
You are re-declaring $data in your second foreach loop
You don't have $row initiated anywhere, and atempting to echo $row["crd"] will result in an empty cell.
Proposed Solution:
Change the name of the $data value in the foreach loop to $row and hence solve both problems at the same time:
foreach($data as $term=>$otherrow) {
$count = 0;
foreach ($otherrow as $row) {
if($count == 0) {
echo "<tr>";
echo "<td>" . $row["code"]. "</td>";
echo '<td rowspan="'.count($otherrow).'">' . $term. '</td>';
echo "<td>" . $row["grade"]. "</td>";
echo "</tr>";
}
else
{
echo "<tr>";
echo "<td>" . $row["code"]. "</td>";
echo "<td>" . $row["grade"]. "</td>";
echo "</tr>";
}
$count++;
}
}
And when you add echo "<td>" . $row["crd"]. "</td>"; now it should echo the value stored in the $row array (as long as the value was extracted from the table in the database in the first place of course).
Let me know if this worked for you.

Related

How do I grab all rows from a single column from multiple tables, based on user input?

I am building a Process selection app and I'm not even sure if my approach is correct (I'm new, sorry!). I have a form with 5 input parameters using radio buttons (choose 1-10).
I have 5 tables setup for each of those parameters that stores the name of the process and fields set as 1 - 10 to correspond to the user input...One of them looks like this:
enter image description here
I am looking to store each parameters user input (1-10) as a session variable to output to an array for further calculation.
I have the following code that sets the session variables from the form and returns only those records that match user input from only one parameter:
<?php
session_start();
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "selectionapp";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
if (isset($_POST['Submit'])) {
$_SESSION['temperature'] = $_POST['temperature'];
$_SESSION['partSize'] = $_POST['partSize'];
$_SESSION['volume'] = $_POST['volume'];
$_SESSION['stiffness'] = $_POST['stiffness'];
$_SESSION['weight'] = $_POST['weight'];
}
echo $_SESSION['temperature'];
echo $_SESSION['partSize'];
echo $_SESSION['volume'];
echo $_SESSION['stiffness'];
echo $_SESSION['weight'];
$result = mysqli_query($conn, "SELECT * FROM processes WHERE temperature LIKE '%{$_SESSION['temperature']}%'");
$row = mysqli_fetch_assoc($result);
echo "<table border='1'>";
while ($row = mysqli_fetch_assoc($result)) {
echo '<tr>';
echo '<td>' . $row['score'] .'</td>';
echo "<td>" . $row['type'] . "</td>";
echo "<td>" . $row['temperature'] . "</td>";
echo "<td>" . $row['partSize'] . "</td>";
echo "<td>" . $row['volume'] . "</td>";
echo "<td>" . $row['stiffness'] . "</td>";
echo "<td>" . $row['weight'] . "</td>";
echo "<td>" . $row['tool'] . "</td>";
echo "<td>" . $row['paint'] . "</td>";
echo "<td>" . $row['notes'] . "</td>";
echo '<tr/>';
}
echo '</table>';
?>
<?php
// close connection
mysqli_close($conn);
?>
Except, what I think I really need is to grab the one column that matches the user input (1-10) from each of the 5 tables, to create anew array so that I can use those values in a calculation that will score/rank that process type.
Appreciate any help. Thanks!
Im not entirely sure if this is what you need:
// You can start to create an array:
$array = [];
// Next is to set the $array with data
$array = [
'temperature' => (int) $_POST['temperature'],
'partSize' => (int) $_POST['partSize'],
];
// In case you want to echo a piece of the array simply do this:
echo $array['temperature'];
// If you want to 'add' a number to the current one you can do this:
$array['partSize'] = ($array['partSize'] + (int) $_POST['partSize']);
// Do a check if $_POST data actually exist and/or is valid:
$array = [
'temperature' => (isset($_POST['temperature'])) ? (int) $_POST['temperature'] : 0,
'partSize' => (isset($_POST['partSize'])) ? (int) $_POST['partSize'] : 0,
];
To be honest, I would personally not store this within a session everytime you get new data. Simply do one query and get all data into one array, and calculate these.
For example:
// Set $temperature
$temperature = [];
// Query to get all temperature's and put into an array:
$temperature = [1, 6, 3, 8, 2, 9, 10, 3, 7, 9];
// Count how many items you've got
$count_temperature = count($temperature); // = 10
// Now calculate and get an average
$sum_temperature = 0;
foreach ($temperature as $temp)
{
$sum_temperature = ($sum_temperature + $temp);
}
echo $sum_temperature; // 58
$avg_temperature = ($sum_temperature / $count_temperature);
echo $avg_temperature; // 5.8
I hope you get the idea behind it and this answers your question. You are not forced to use a database connection, it could be stored into a $_SESSION. But please let me reminder you once the session is destroyed, the input will be lost. If this DOES NOT answer your question, please let me know and I will help you find for a solution!
I did it! It is NOT pretty nor concise nor elegant...but it works. Thank you #RonnieOosting! While I did not go the array route, you helped point me in the right direction.
<?php
session_start();
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "selectionapp";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
if (isset($_POST['Submit'])) {
$_SESSION['temperature'] = $_POST['temperature'];
$_SESSION['partSize'] = $_POST['partSize'];
$_SESSION['volume'] = $_POST['volume'];
$_SESSION['stiffness'] = $_POST['stiffness'];
$_SESSION['weight'] = $_POST['weight'];
}
echo $_SESSION['temperature'];
echo $_SESSION['partSize'];
echo $_SESSION['volume'];
echo $_SESSION['stiffness'];
echo $_SESSION['weight'];
if ($result_temp = mysqli_query($conn, "SELECT * FROM temperature WHERE '%{$_POST['temperature']}%' LIKE '%{$_SESSION['temperature']}%'"));
echo "<table border='1'>";
echo '<tr>';
echo "<td>" . 'Process Type' . "</td>";
echo "<td>" . 'Temperature Score' . "</td>";
echo '<tr/>';
while ($row = mysqli_fetch_assoc($result_temp)) {
echo '<tr>';
echo "<td>" . $row['type'] . "</td>";
echo "<td>" . $row[$_SESSION['temperature']] * 10 . "</td>";
echo '<tr/>';
}
echo '</table>';
$result_size = mysqli_query($conn, "SELECT * FROM partSize WHERE '%{$_POST['partSize']}%' LIKE '%{$_SESSION['partSize']}%'");
//$row = mysqli_fetch_assoc($result);
echo "<table border='1'>";
echo '<tr>';
echo "<td>" . 'Process Type' . "</td>";
echo "<td>" . 'Part Size Score' . "</td>";
echo '<tr/>';
while ($row = mysqli_fetch_assoc($result_size)) {
echo '<tr>';
echo "<td>" . $row['type'] . "</td>";
echo "<td>" . $row[$_SESSION['partSize']] . "</td>";
echo '<tr/>';
}
echo '</table>';
$result_vol = mysqli_query($conn, "SELECT * FROM volume WHERE '%{$_POST['volume']}%' LIKE '%{$_SESSION['volume']}%'");
//$row = mysqli_fetch_assoc($result);
echo "<table border='1'>";
echo '<tr>';
echo "<td>" . 'Process Type' . "</td>";
echo "<td>" . 'Volume Score' . "</td>";
echo '<tr/>';
while ($row = mysqli_fetch_assoc($result_vol)) {
echo '<tr>';
echo "<td>" . $row['type'] . "</td>";
echo "<td>" . $row[$_SESSION['volume']] . "</td>";
echo '<tr/>';
}
echo '</table>';
$result_stiff = mysqli_query($conn, "SELECT * FROM stiffness WHERE '%{$_POST['stiffness']}%' LIKE '%{$_SESSION['stiffness']}%'");
//$row = mysqli_fetch_assoc($result);
echo "<table border='1'>";
echo '<tr>';
echo "<td>" . 'Process Type' . "</td>";
echo "<td>" . 'Stiffness Score' . "</td>";
echo '<tr/>';
while ($row = mysqli_fetch_assoc($result_stiff)) {
echo '<tr>';
echo "<td>" . $row['type'] . "</td>";
echo "<td>" . $row[$_SESSION['stiffness']] . "</td>";
echo '<tr/>';
}
echo '</table>';
$result_wght = mysqli_query($conn, "SELECT * FROM weight WHERE '%{$_POST['weight']}%' LIKE '%{$_SESSION['weight']}%'");
//$row = mysqli_fetch_assoc($result);
echo "<table border='1'>";
echo '<tr>';
echo "<td>" . 'Process Type' . "</td>";
echo "<td>" . 'Weight Score' . "</td>";
echo '<tr/>';
while ($row = mysqli_fetch_assoc($result_wght)) {
echo '<tr>';
echo "<td>" . $row['type'] . "</td>";
echo "<td>" . $row[$_SESSION['weight']] . "</td>";
echo '<tr/>';
}
echo '</table>';
echo "<table border='1'>";
echo '<tr>';
echo "<td>" . 'LFI Results' . "</td>";
echo "<td>" . 'Score' . "</td>";
echo '<tr/>';
echo '<tr>';
echo "<td>" . $row['type'] . "</td>";
echo "<td>" . $row[$_SESSION['weight']] . "</td>";
echo '<tr/>';
echo '</table>';
?>
<?php
// close connection
mysqli_close($conn);
?>
This outputs:
Process Type Temperature Score
LFI 5
DCPD 5
SMC 10
Process Type Part Size Score
LFI 0.0
DCPD 0.0
SMC 1.0
Process Type Volume Score
LFI 0.5
DCPD 0.5
SMC 1.0
Process Type Stiffness Score
LFI 1.0
DCPD 1.0
SMC 1.0
Process Type Weight Score
LFI 1.0
DCPD 1.0
SMC 1.0

Get data from SQL database of multiple columns stored in explode function using PHP

I am using this code to get that data from SQL Server database using PHP
<?php
foreach ($dbDB->query($query) as $row) {
echo "<tr>";
echo "<td>" . $row['Country'] . "</td>";
echo "<td>" . $row['OrderNumber'] . "</td>";
echo "<td>" . $row['Region'] . "</td>";
echo "<td>" . $row['ShipDate'] . "</td>";
echo "<td>" . $row['ProducedDate'] . "</td>";
echo "</tr>"; }
?>
I am trying to replace these multiple lines but storing the columns' names in a string for example $_POST['SelectedColumns'].
The values coming into post as comma separated string, For example : Country,OrderNumber,Region,ShipDate,ProducedDate
I have tried this solution but still not working for me.
<?php
$ser="********";
$db="******";
$user="******";
$pass="******";
$query = 'SELECT '.$_POST['SelectedColumns'].' FROM reporting.REPORT_ALL';
$dbDB = new PDO("odbc:Driver=ODBC Driver 13 for SQL Server;Server=*******;Database=******;Port=1456", $user, $pass);
$row = $_POST["SelectedColumns"];
$rows = explode(",",$row);
/*Here I have the another html code independent of this part */
foreach ($dbDB->query($query) as $dataRow) {
echo "<table>";
echo "<tr>";
foreach ($rows as $r ) {
echo "<td>" . $dataRow[$r] . "</td>"; }
echo "</tr>";
echo "</table>"; }
?>
Any suggestions please ?

PHP : Fetching data and storing into variables

I wanted to fetch the data from the database and wants to store into an array and after storing the data into the array i want to access particular index of the array.
I'm a java developer need to do this in php (which I don't know much).
Basically there are 250 strings in a table i wanted to fetch those 250 strings into and array and wants to access some particular row.
for example :
<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM Persons");
echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "</tr>";
}
echo "</table>";
**$uname100 = $row[100]; // this is not getting assigned to $uname100 variable**
**echo $row[100]; // here this is not printing**
**echo $uname100; // not even this printing**
mysqli_close($con);
?>
Please check the bold part in the code and help me out. I'm new to php so please dont panic over this.
And also wanted to do something like this :
$ctr=0;
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "</tr>";
$uname[$ctr++] = $row['FirstName']; // AND USING THIS OUTSIDE LOOP
}
echo $uname[90];
Use array construction
$counter=0;
$data = array();
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "</tr>";
$data[] = $row['FirstName'];
$counter++;
}
print_r($data);
First solution
$counter=0;
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "</tr>";
$counter++;
$varName='uname'.$counter;
$$varName=$row['FirstName'];
}
echo echo $uname100;
You cannot access the variable $row[100] outside the while loop.
Also $row will not contain an index 100.
It will be containing only $row['FirstName'] or $row['LastName'] inside the while loop
Answer for second part:
$uname = array();
$ctr=0;
while($row = mysqli_fetch_array($result)) {
....
....
$uname[$ctr++] = $row['FirstName']; // AND USING THIS OUTSIDE LOOP
}
if(isset($uname[90])) echo $uname[90];

PHP - Display SQL results in multiple tables

I have a database table with student room assignments. Each student has a specific hall, floor, and apartment. I need to display each student in a specific table so the results look like a floor layout. Below is an example. The student ID needs to be in the correct Apartment slot. There could be several ID's per apartment. Right now it just lists them down the page.
Apartment 102 Apartment 101
Apartment 104 Apartment 103
Apartment 106 Apartment 105
$query = "select res.ID_NUM as ID, res.APARTMENT
From Residents res
Where res.sess_cde = '$pulledsession'
and res.ROOM_ASSIGN_STS = 'A'
and res.BLDG_CDE = '$pulledhall'
and res.FLOOR = '$pulledfloor'";
$result = odbc_exec($connect, $query);
echo "<table style='padding:25;'>
<tr>
<th>Apartment</th>
<th>ID</th>
</tr>";
while(odbc_fetch_row($result)){
$ID = odbc_result($result,ID);
$APARTMENT = odbc_result($result,APARTMENT);
if ($APARTMENT == $pulledfloor.'01')
{
echo "<tr >";
echo "<td>" . $pulledfloor.'01' . "</td>";
echo "<td>" . $ID . "</td>";
echo "</tr>";
}
else if ($APARTMENT == $pulledfloor.'02')
{
echo "<tr>";
echo "<td>" . $pulledfloor.'02' . "</td>";
echo "<td>" . $ID . "</td>";
echo "</tr>";
}
else if ($APARTMENT == $pulledfloor.'03')
{
echo "<tr>";
echo "<td>" . $pulledfloor.'03' . "</td>";
echo "<td>" . $ID . "</td>";
echo "</tr>";
}
else if ($APARTMENT == $pulledfloor.'04')
{
echo "<tr>";
echo "<td>" . $pulledfloor.'04' . "</td>";
echo "<td>" . $ID . "</td>";
echo "</tr>";
}
else if ($APARTMENT == $pulledfloor.'05')
{
echo "<tr>";
echo "<td>" . $pulledfloor.'05' . "</td>";
echo "<td>" . $ID . "</td>";
echo "</tr>";
}
else if ($APARTMENT == $pulledfloor.'06')
{
echo "<tr>";
echo "<td>" . $pulledfloor.'06' . "</td>";
echo "<td>" . $ID . "</td>";
echo "</tr>";
}
}
echo "</table>";
You would need to retrieve the room number as well. After that, one way to do it would be to load the results into an associated array:
$rooms[$row['roomNumber']] = $resName; // Example
Once you have the array built, then you can echo it back out into a table, either manually (build the full table and echo each one with
echo "<tr><td>".$rooms['102']."</td><td>".$rooms['101']."</td></tr>";
or similar, or do it dynamically by incrementing two room numbers in a loop.
If you have multiple students in a room, then tack on more depth to the array:
$rooms[$row['roomNumber']][] = $resName;
Then use a loop in each cell to echo it back out.

Find last value of array in foreach cicle

I've data stored in a array ($rows).
For read the array and genarate a dinamic table I use foreach function.
<table>
foreach ($rows as $row) {
echo "<tr>";
echo "<td>" . $row['field1'] . "</td>";
echo "<td>" . $row['field2'] . "</td>";
echo "<td>" . $row['filed3'] . "</td>";
echo "</tr>";
}
</table>
My goal is to find the last value of the array (the end) in order to change the class of TR element for the last line displayed.
How could I do this?
Thanks
Try this:
foreach ($rows as $key => $row) {
$end = end($rows) === $row ? 'class="last"' : '';
echo "<tr $end>";
echo "<td>" . $row['field1'] . "</td>";
echo "<td>" . $row['field2'] . "</td>";
echo "<td>" . $row['filed3'] . "</td>";
echo "</tr>";
}
This method works for multidimentional arrays as well.
http://codepad.org/HQG9ytBX
Edit. As pointed in comments, this approach may potentially trigger false end result if some values in the array are duplicated (with the last). Correct bullet-proof version should be:
foreach ($rows as $key => $row) {
$end = end($rows) === $row && $key === key($rows) ? 'class="last"' : '';
// ...
foreach ($rows as $row) {
$is_last_row = ++$i == count($rows);
echo "<tr>";
echo "<td>" . $row['field1'] . "</td>";
echo "<td>" . $row['field2'] . "</td>";
echo "<td>" . $row['filed3'] . "</td>";
echo "</tr>";
}
here $i should be an unused variable.
Try This
$numItems = count($rows);
$i = 0;
foreach($rows as $row) {
$trClass = 'firstclass';
if(++$i === $numItems)
{
$trClass = 'lastclass';
}
echo "<tr class='$trclass'>";
echo "<td>" . $row['field1'] . "</td>";
echo "<td>" . $row['field2'] . "</td>";
echo "<td>" . $row['filed3'] . "</td>";
echo "</tr>";
}
// first, let's find out the last key
end($rows);
$last = key($rows);
// then just loop over
foreach ($rows as $key => $row) {
if ($key == $last) {
// last leaf of the summer...
}
echo "<tr>";
echo "<td>" . $row['field1'] . "</td>";
echo "<td>" . $row['field2'] . "</td>";
echo "<td>" . $row['filed3'] . "</td>";
echo "</tr>";
}

Categories