display multiple rows from oracle database with php - php

I am trying to display multiple rows from Oracle table with php.
Below is my code:
<?php
include("dbconnect.php");
$personcon=$conn;
$surname = $_POST['Surname'];
$suburb = $_POST['Suburb'];
$state = $_POST['State'];
$discipline = $_POST['Discipline'];
$companyname = $_POST['CompanyName'];
$rank = $_POST['Rank'];
$role = $_POST['Role'];
$yearsexperience = $_POST['YearsExperience'];
$recentproject = $_POST['RecentProject'];
$sellrate = $_POST['SellRate'];
$projectnumber = $_POST['ProjectNumber'];
$tendernumber = $_POST['TenderNumber'];
$query = "SELECT CP.ROLE AS CURRENT_ROLE , CP.SURNAME, CP.FIRSTNAME, CP.COMPANY,CC.COMPANYNAME AS CONSULTANT_COMPANY, CP.YEARSEXPERIENCE AS EXPERIENCE_IN_YEAR, CP.QUALIFICATION, D.PRINCIPLEDISCIPLINE, D.SUBDISCIPLINE1, D.SUBDISCIPLINE2, D.SUBDISCIPLINE3, D.SUBDISCIPLINE4, D.SUBDISCIPLINE5, D.SUBDISCIPLINE6, D.SUBDISCIPLINE7, D.SUBDISCIPLINE8, L.SUBURB, L.STATE, L.COUNTRY FROM CONSULTANTPERSONNEL CP, LOCATION L, ONSULTANTPERSONNEL_DISCIPLINE N, DISCIPLINE D, CONSULTANTCOMPANY CC, CONTRACTS C, PROJECTS P, TENDERS T, FEEBASIS F WHERE CP.LOCATIONID = L.LOCATIONID AND CP.CONSULTANTPERSONALID = N.CONSULTANTPERSONALID AND N.DISCIPLINID = D.DISCIPLINID AND CP.CONSULTANTCOMPANYID = CC.CONSULTANTCOMPANYID AND CP.CONTRACTID = C.CONTRACTID AND C.FEECODE = F.FEECODES AND C.PROJECTNUMBER = P.PROJECTNUMBER AND C.TENDERNUMBER = T.TENDERNUMBER AND LOWER(CP.SURNAME) LIKE LOWER('%".$surname."%') AND LOWER(L.SUBURB) LIKE LOWER('%".$suburb."%') AND LOWER(L.STATE) LIKE LOWER('%".$state."%') AND LOWER(D.PRINCIPLEDISCIPLINE) LIKE LOWER('%".$discipline."%') AND LOWER(CC.COMPANYNAME) LIKE LOWER('%".$companyname."%') AND LOWER(CP.RANK) LIKE LOWER('%".$rank."%') AND LOWER(CP.ROLE) LIKE LOWER('%".$role."%') AND LOWER(P.PROJECTNAME) LIKE LOWER('%".$recentproject."%') AND LOWER(P.PROJECTNUMBER) LIKE LOWER('%".$projectnumber."%') AND LOWER(T.TENDERNUMBER) LIKE LOWER('%".$tendernumber."%')";
$SQL = oci_parse($personcon, $query);
oci_execute($SQL);
$results = array();
$numRows = oci_fetch_all($SQL, $results, null, null, OCI_FETCHSTATEMENT_BY_ROW);
if($numRows > 0){
echo "<p> <table border=1>\n";
//Print the headings
echo "<tr>\n";
foreach($results[0] as $index=>$value)
echo "<th>$index</th>\n";
echo "</tr>\n";
echo "<tr>\n";
foreach($results as $row)
foreach($row as $index=>$value)
echo "<td>$value</td>\n";
echo "</tr>\n";
echo "</table>\n </p>";
oci_close($personcon);
} else {
echo "<tr> The search you enter is not in the database.";
}
?>
I can retrieve the data I wish but instead of displaying row by row, it displays all the data in one row.
Any Idea how to fix that ? Thanks

You got simple and common (for me at least) mistake in Your loops, that creates only one row and puts every column inside. Try changing:
echo "<tr>\n";
foreach($results as $row)
foreach($row as $index=>$value)
echo "<td>$value</td>\n";
echo "</tr>\n";
to something like this:
foreach($results as $row)
{
echo "<tr>\n";
foreach($row as $index=>$value)
{
echo "<td>$value</td>\n";
}
echo "</tr>\n";
}
The brackets will help You see the scopes. Its not python, You know. ;)

Related

How to integrate array_column() and array_filter() into dynamic table generation of sql results

I want to read out data from an sql-database an show them in a table. This works well. Now, I would like to show only those columns with at least one value in it and not the empty ones (containing NULL, 0, empty string). This works with the following example:
enter code here
<TABLE width="500" border="1" cellpadding="1" cellspacing="1">
<?php
$query = mysql_query("SELECT * FROM guestbook", $db);
$results = array();
while($line = mysql_fetch_assoc($query)){
$results[] = $line;
$Name = array_column($results, 'Name');
$Home = array_column($results, 'Home');
$Date = array_column($results, 'Date');
$Emptycolumn = array_column($results, 'Emptycolumn');
$Comment = array_column($results, 'Comment');
$City = array_column($results, 'City');
}
echo "<TR>";
if(array_filter($Name)) {echo "<TH>Name</TH>";}
if(array_filter($Home)){echo "<TH>Home</TH>";}
if(array_filter($Date)){echo "<TH>Date</TH>";}
if(array_filter($Emptycolumn)){echo "<TH>Emptycolumn</TH>";}
if(array_filter($Comment)){echo "<TH>Comment</TH>";}
if(array_filter($City)){echo "<TH>City</TH>";}
echo "</TR>";
$query = mysql_query("SELECT * FROM guestbook", $db);
while($line = mysql_fetch_assoc($query)){
echo "<TR>";
if(array_filter($Name)) {echo "<TD>".$line['Name']."</TD>";}
if(array_filter($Home)) {echo "<TD>".$line['Home']."</TD>";}
if(array_filter($Date)) {echo "<TD>".$line['Date']."</TD>";}
if(array_filter($Emptycolumn)) {echo "<TD>".$line['Emptycolumn']."</TD>";}
if(array_filter($Comment)) {echo "<TD>".$line['Comment']."</TD>";}
if(array_filter($City)) {echo "<TD>".$line['City']."</TD>";}
echo "</TR>";
}
?>
</TABLE>
Since the column-names of my table are highly variable (depending on the query), the table is generated by looping through the result-array, first the column-names, then the values in the rows:
enter code here
$sql = "SELECT DISTINCT $selection FROM $tabelle WHERE
$whereclause"; //will be changed to PDO
$result = mysqli_query($db, $sql) or die("<b>No result</b>"); //Running
the query and storing it in result
$numrows = mysqli_num_rows($result); // gets number of rows in result
table
$numcols = mysqli_num_fields($result); // gets number of columns in
result table
$field = mysqli_fetch_fields($result); // gets the column names from the
result table
if ($numrows > 0) {
echo "<table id='myTable' >";
echo "<thead>";
echo "<tr>";
echo "<th>" . 'Nr' . "</th>";
for($x=0;$x<$numcols;$x++){
$key = array_search($field[$x]->name, $custom_column_arr);
if($key !== false){
echo "<th>" . $key . "</th>";
}else{
echo "<th>" . $field[$x]->name . "</th>";
}
}
echo "</tr></thead>";
echo "<tbody>";
$nr = 1;
while ($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $nr . "</td>";
for ($k=0; $k<$numcols; $k++) { // goes around until there are no
columns left
echo "<td>" . $row[$field[$k]->name] . "</td>"; //Prints the data
}
echo "</tr>";
$nr = $nr + 1;
} // End of while-loop
echo "</tbody></table>";
}
}
mysqli_close($db);
Now, I tried to integrate the array_column() and array_filter()-blocks of the example above into the loops, but unfortunately, it didn´t work. I´m sure, this is easy for a professional and I would be very grateful, if someone could help me with this problem!
Thank you very much in advance!!

Writing the attributes of a database in PHP

I am writing an application in which user can enter a database name and I should write all of its contents in table with using PHP.I can do it when I know the name of database with the following code.
$result = mysqli_query($con,"SELECT * FROM course");
echo "<table border='1'>
<tr>
<th>blablabla</th>
<th>blabla</th>
<th>blablabla</th>
<th>bla</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['blablabla'] . "</td>";
echo "<td>" . $row['blabla'] . "</td>";
echo "<td>" . $row['blablabla'] . "</td>";
echo "<td>" . $row['bla'] . "</td>";
echo "</tr>";
}
echo "</table>";
In this example I can show it since I know the name of table is course and it has 4 attributes.But I want to be able to show the result regardless of the name the user entered.So if user wants to view the contents of instructors there should be two columns instead of 4.How can I accomplish this.I get the table name with html.
Table:<input type="text" name="table">
Edit:Denis's answer and GrumpyCroutons' answer are both correct.You can also ask me if you didnt understand something in their solution.
Quickly wrote this up, commented it (This way you can easily learn what's going on, you see), and tested it for you.
<form method="GET">
<input type="text" name="table">
</form>
<?php
//can be done elsewhere, I used this for testing. vv
$config = array(
'SQL-Host' => '',
'SQL-User' => '',
'SQL-Pass' => '',
'SQL-Database' => ''
);
$con = mysqli_connect($config['SQL-Host'], $config['SQL-User'], $config['SQL-Pass'], $config['SQL-Database']) or die("Error " . mysqli_error($con));
//can be done elsewhere, I used this for testing. ^^
if(!isSet($_GET['table'])) { //check if table choser form was submitted.
//In my case, do nothing, but you could display a message saying something like no db chosen etc.
} else {
$table = mysqli_real_escape_string($con, $_GET['table']); //escape it because it's an input, helps prevent sqlinjection.
$sql = "SELECT * FROM " . $table; // SELECT * returns a list of ALL column data
$sql2 = "SHOW COLUMNS FROM " . $table; // SHOW COLUMNS FROM returns a list of columns
$result = mysqli_query($con, $sql);
$Headers = mysqli_query($con, $sql2);
//you could do more checks here to see if anything was returned, and display an error if not or whatever.
echo "<table border='1'>";
echo "<tr>"; //all in one row
$headersList = array(); //create an empty array
while($row = mysqli_fetch_array($Headers)) { //loop through table columns
echo "<td>" . $row['Field'] . "</td>"; // list columns in TD's or TH's.
array_push($headersList, $row['Field']); //Fill array with fields
} //$row = mysqli_fetch_array($Headers)
echo "</tr>";
$amt = count($headersList); // How many headers are there?
while($row = mysqli_fetch_array($result)) {
echo "<tr>"; //each row gets its own tr
for($x = 1; $x <= $amt; $x++) { //nested for loop, based on the $amt variable above, so you don't leave any columns out - should have been <= and not <, my bad
echo "<td>" . $row[$headersList[$x]] . "</td>"; //Fill td's or th's with column data
} //$x = 1; $x < $amt; $x++
echo "</tr>";
} //$row = mysqli_fetch_array($result)
echo "</table>";
}
?>
$tablename = $_POST['table'];
$result = mysqli_query($con,"SELECT * FROM $tablename");
$first = true;
while($row = mysqli_fetch_assoc($result))
{
if ($first)
{
$columns = array_keys($row);
echo "<table border='1'>
<tr>";
foreach ($columns as $c)
{
echo "<th>$c</th>";
}
echo "</tr>";
$first = false;
}
echo "<tr>";
foreach ($row as $v)
{
echo "<td>$v</td>";
}
echo "</tr>";
}
echo "</table>";
<?php
$table_name = do_not_inject($_REQUEST['table_name']);
$result = mysqli_query($con,'SELECT COLUMN_NAME FROM information_schema.COLUMNS WHERE TABLE_NAME='. $table_name);
?>
<table>
<?php
$columns = array();
while ($row = mysql_fetch_assoc($result)){
$columns[]=$row['COLUMN_NAME'];
?>
<tr><th><?php echo $row['COLUMN_NAME']; ?></th></tr>
<?php
}
$result = mysqli_query($con,'SELECT * FROM course'. $table_name);
while($row = mysqli_fetch_assoc($result)){
echo '<tr>';
foreach ($columns as $column){
?>
<td><?php echo $row[$column]; ?></td>
<?php
}
echo '</tr>';
}
?>
</table>

Failed to iterate over selected rows

The code is supposed to get a row at each loop and build td elements for each data piece. However, it only gets some rows while missing others even though all rows were selected:
$query = "select * from category";
$ret = mysql_query($query, $conn);
while ($rows = mysql_fetch_assoc($ret)) {
echo "<tr>";
foreach ($rows as $val) {
echo "<td>{$val}</td>";
}
}
mysql_fetch_assoc returns an associative array. To display each returned row, do something like this (taken directly from the php.net page for mysql_fetch_assoc
while ($row = mysql_fetch_assoc($result)) {
echo $row["userid"];
echo $row["fullname"];
echo $row["userstatus"];
}
Try removing the curly braces like this:
echo "<td>$val</td>";
Beside you didn't close the <tr> tag. So you should do this:
$query = "select * from category";
$ret = mysql_query($query, $conn);
while ($rows = mysql_fetch_assoc($ret)) {
echo "<tr>";
foreach ($rows as $val) {
echo "<td>$val</td>";
}
echo"</tr>";
}
Now like Jack Albright said you should consider various columns of your table to display specific data. Upon that the while() is already a look, I think you don't need to add any foreach() inside. SO your final code should look like this:
$query = "select * from category";
$ret = mysql_query($query, $conn);
while ($rows = mysql_fetch_assoc($ret)) {
echo "<tr>";
echo "<td>$rows['columnName']</td>";
echo "</tr>";
}

Displaying data horizontally using php and mysql

Hi I'm attempting to display data retrieved from a mysql table horizontally in an html table using php. The code below works well except for the fact that it leaves out the first record (starts at the second record) in my database. I'm sure it has something to do with the counter but I can't seem to figure out how to get it to stop doing this. If anyone can point out my error I'd really appreciate it!
$items = 5;
$query = "SELECT * FROM members ";
$result = mysql_query($query)
or die(mysql_error());
$row = mysql_fetch_array($result);
if (mysql_num_rows($result) > 0) {
echo '<table border="1">';
$i = 0;
while($row = mysql_fetch_array($result)){
$first_name = $row['first_name'];
if ($i==0) {
echo "<tr>\n";
}
echo "\t<td align=\center\">$first_name</td>\n";
$i++;
if ($i == $items) {
echo "</tr>\n";
$i = 0;
}
}//end while loop
if ($i > 0) {
for (;$i < $items; $i++) {
echo "<td> </td>\n";
}
echo '</tr>';
}//end ($i>0) if
echo '</table>';
}else {
echo 'no records found';
}
try and remove the 1st
$row = mysql_fetch_array($result);
you are calling it twice, that's why it skips 1 row in your while loop
try this simpler.
$items = 5;
$query = "SELECT * FROM members ";
$result = mysql_query($query) or die(mysql_error());
if (mysql_num_rows($result) > 0) {
echo '<table border="1">';
while($row = mysql_fetch_array($result)){
$first_name = $row['first_name'];
echo "<tr>";
for ($i=0 ; $i <= $items ;$i++) {
echo "<td align='center'>".$first_name."</td>";
}
}//end while loop
echo "</tr>";
echo '</table>';
}else{ echo 'no records found'; }
I have run into this issue before. Try the do while loop instead. Example
do {
// code
} while($row = mysql_fetch_array($result)); //end while loop
$row = mysql_fetch_array($result);
1) remove this line of code from ur scripts
2) only use while loop code instead.

Joining two different tables containing csv and display them on a webpage

I have been stuck with a problem and I am newbie in mysql and php, Here is the code first , so that I can explain in detail:
$metros = array(1,263);
foreach($metros as $metro_id) {
$sql = "SELECT cuisine_id, cuisine_name_en FROM poi_restaurant_cuisines";
$result = mysql_query($sql);
$cuisine_id = array();
$cusine_name = array();
while($row = mysql_fetch_assoc($result)) {
$cuisine_id[] = $row['cuisine_id'];
$cuisine_name[] = $row['cuisine_name_en'];
}
foreach ($cuisine_id as $cuisine) {
$sql = "
SELECT COUNT(*)
FROM poi AS p
LEFT JOIN poi_restaurant AS pr USING (poi_id)
WHERE p.poi_address_prefecture_id = '$metro_id'
AND pr.poi_restaurant_cuisine_id_array
AND find_in_set('$cuisine', poi_restaurant_cuisine_id_array)
AND p.poi_status = 1";
$result = mysql_query($sql);
$count_cuisine = array();
while($row = mysql_fetch_array($result)) {
$count_cuisine[$metro_id][$cuisine] = $row['COUNT(*)'];
}
echo "<table border = 1 cellpadding= 5 cellspacing= 5 width= 100>";
echo "<tr><th>CuisineID</th><th>Count</th></tr>";
echo "<tr><td>";
echo $cuisine;
echo "</td><td>";
echo $count_cuisine[$metro_id][$cuisine];
echo "</td><td>";
echo "</tr>";
echo "</table>";
}
}
The poi_restaurant_cuisine_id_array contains csv values. I am able to produce the count and the cuisine ID on the web page. I want to replace the cuisine ID with the name of the cuisine. I am not very good at sql or either PHP as I am a beginner. I hope I am being clear enough. Any help is highly appreciated ...Thank you.
Try this:
echo '<table border="1" cellpadding="5" cellspacing="5" width="100">';
echo "<tr><th>Cuisine</th><th>Count</th></tr>";
$metros = array(1,263);
foreach($metros as $metro_id) {
$sql = "SELECT cuisine_id, cuisine_name_en FROM poi_restaurant_cuisines";
$result = mysql_query($sql);
$cuisines = array();
while($row = mysql_fetch_assoc($result)) {
$cuisines[] = array(
'id' => $row['cuisine_id'],
'name' => $row['cuisine_name_en'],
);
}
foreach ($cuisines as $cuisine) {
$sql = "
SELECT COUNT(*)
FROM poi AS p
LEFT JOIN poi_restaurant AS pr USING (poi_id)
WHERE p.poi_address_prefecture_id = '$metro_id'
AND pr.poi_restaurant_cuisine_id_array
AND find_in_set('{$cuisine['id']}', poi_restaurant_cuisine_id_array)
AND p.poi_status = 1";
$result = mysql_query($sql);
$count_cuisine = array();
while($row = mysql_fetch_array($result)) {
$count_cuisine[$metro_id][$cuisine['id']] = $row['COUNT(*)'];
}
echo "<tr>
<td>{$cuisine['name']}</td>
<td>{$count_cuisine[$metro_id][$cuisine['id']]}</td>";
</tr>";
}
}
echo "</table>";
Assuming cuisine_id is a unique identifier, then just use it as the array index....
while($row = mysql_fetch_assoc($result)) {
$cuisines[$row['cuisine_id']] = $row['cuisine_name_en'];
}
....
foreach ($cuisines as $cuisine_id=>$cuisine_name_en) {
However storing multiple values in a single column is a very bad idea.
Generating and running queries in a loop is another very bad idea.
It is possible to reduce this to a single query, declared and invloked outside the inner loop but because your data is not mormalized, this is rather complex.

Categories