PHP function to loop SQL result and generate HTML tables - php

I want to write an php function that will echo sql query results in a specific manner.
Example I have table 1 which is 10.000 rows * 43 columns:
NO NAME Prof Date of birth
1 John Teacher 1987
2 Nick Engineer 1976
3
4
5
And so on. Based on No which is an integer (1-10.000), I want to generate tables such as:
Name: John
Prof: Teacher
Date of birth: 1987
Name: Nick
Prof: Engineer
Date of birth: 1976
So far my code:
`
$hostname = "";
$username = "";
$password = "";
$dbname = "db1";
//connection to the database
$con = mysqli_connect($hostname, $username, $password, $dbname)
or die("Unable to connect to MySQL");
mysqli_set_charset($con, 'utf8');
/*echo "Connected to db1 database <br>";
else
echo "Could not connect"; */
$query1 = "SELECT * FROM `table 1` WHERE CODE_NO = 1";
$query2 = "SHOW COLUMNS FROM table 1";
$result1 = mysqli_query($con, $query1);
$result2 = mysqli_query($con, $query2);
// Check result
// Useful for debugging.
if (!$result1) {
$message = 'Invalid query: ' . mysqli_error($con) . "\n";
$message .= 'Whole query: ' . $query1;
die($message);
}
echo "<table>"; // table tag in the HTML
while($row = mysqli_fetch_array($result1))
//Creates a loop to loop through results
{
echo
"<tr>
<th>CODE_NO:</th>
<td>" . $row['CODE_NO'] . "</td>
</tr>
<tr>
<th>FIRST_NAME:</th>
<td>" . $row['FIRST_NAME'] . "</td>
</tr>
<tr>
<th>SURNAME:</th>
<td>" . $row['SURNAME'] . "</td>
</tr>
<tr>
<th>Date of birth:</th>
<td>" . $row['DOB'] . "</td>
</tr>
<tr>
<th>Date of death:</th>
<td> " . $row['DOD'] . "</td>
</tr>";
}
echo "</table>"; //Close the table in HTML
?>`
Is it possbile to code the process once, without hard-coding anything, so it could be repeated as many times as needed?
Edit:
$x = 1;
$query = "SELECT * FROMpersonsWHERE CODE_NO = '$x'";
$result = mysqli_query($con, $query);

If I understood you correctly, this would do what you need:
function generateTableFromResult($result) {
$html = "<table>";
while($row = mysqli_fetch_array($result)) {
foreach($row as $column => $value) {
$html.="<tr><th>".$column."</th><td>".$value."</td></tr>";
}
}
$html.="</table>";
return $html;
}
// usage:
// ...
$result1 = mysqli_query($con, $query1);
echo generateTableFromResult($result1);

You can have the excepted result.
You will need to have a variable to be incremented with the values and returned at the end.
See my example:
// Check result
// Useful for debugging.
if (!$result1) {
$message = 'Invalid query: ' . mysqli_error($con) . "\n";
$message .= 'Whole query: ' . $query1;
die($message);
}
$table = "<table>"; // table tag in the HTML
while($row = mysqli_fetch_array($result1)){
//Creates a loop to loop through results
$table .="<tr>";
$table .=" <th>CODE_NO:</th>";
$table .=" <td>" . $row['CODE_NO'] . "</td>";
$table .="</tr>";
$table .="<tr>";
$table .=" <th>FIRST_NAME:</th>";
$table .=" <td>" . $row['FIRST_NAME'] . "</td>";
$table .="</tr>";
$table .="<tr>";
$table .=" <th>SURNAME:</th>";
$table .=" <td>" . $row['SURNAME'] . "</td>";
$table .="</tr>";
$table .="<tr>";
$table .=" <th>Date of birth:</th>";
$table .=" <td>" . $row['DOB'] . "</td>";
$table .="</tr>";
$table .="<tr>";
$table .=" <th>Date of death:</th>";
$table .=" <td> " . $row['DOD'] . "</td>";
$table .="</tr>";
}
$table .= "</table>"; //Close the table in HTML
echo $table;
?>`
This is a possible approach to get the result that you want.
However you sent an array in the json format with the values and in the front end build the table using js.

Revised function generateTableFromResult from above that works correctly
function generateTableFromResult($result) {
$html = "";
$i = 0;
$header = "<tr>";
$body = "";
while($row = mysqli_fetch_assoc($result)) {
$i += 1;
$body .= "<tr>\n";
foreach($row as $column => $value) {
if ($i == 1){
$header .= "<th>$column</th>\n";
}
$body .= "<td>$value</td>\n";
}
$body .= "</tr>\n";
}
$header .= "</tr>\n";
$html .= "<table> $header $body</table>";
return $html;
}

Related

Displaying PHP Many to Many Relationship

Hi everyone im new at php so here is my code i am having trouble displaying php in many to many relationship im doing a student information system
here is my database
student
student_id
name
address
course
subject
subject_id
subject_name
subject_code
student_subject
subject_id
student_id
Here is my query
$sql = "SELECT subject_name
FROM subject
LEFT JOIN student_subject ON (student.student_id = 'student_id')
LEFT JOIN subject ON (subject.subject_id = 'subject_id' )";
$records = mysql_query($sql);
and now this is my code to display it please help me how to display this example i just only want to display the subject name and the subject code
while($student=mysql_fetch_array($records)){
echo $student['subject_name'];
echo $student['subject_code'];
}
this is only sample because this is only what i want to dispaly please help me thanks sorry for my bad english. cant search anything about displaying many to many relationship in google i can see some query but i cant search about the code i tried many but i always failed thank you so much
desired Output:
Subject Name ---|--- Subject CODE
ICT___________||_________IT 101
ALGEBRA_______||_________ MATH101
remove the underscore in your vision cant fix the output new here in stackoverflow
<?php
$con = mysql_connect("localhost", "root", "") or die('There is an error to connect DB' . mysql_error());
mysql_select_db('test') or die ('Unable to select DB' . mysql_error());
$query = 'SELECT ST.student_id, ST.name, ST.address, SB.subject_name, SB.subject_code FROM student ST, subject SB, `student_subject` STSB WHERE STSB.student_id=ST.student_id AND STSB.subject_id=SB.subject_id';
$query = mysql_query($query) or die('Unable to execute query' . mysql_error());
if ($query) {
$str = '';
$header = '<tr><td>Student ID</td><td>Name</td><td>Address</td><td>Subject</td><td>Subject Code</td></tr>';
while ($row = mysql_fetch_array($query)) {
$str .= '<tr>';
$student_id = $row['student_id'];
$name = $row['name'];
$address = $row['address'];
$subject = $row['subject_name'];
$subject_code = $row['subject_code'];
$str .= '<td>' . $student_id . '</td>';
$str .= '<td>' . $name . '</td>';
$str .= '<td>' . $address . '</td>';
$str .= '<td>' . $subject . '</td>';
$str .= '<td>' . $subject_code . '</td>';
$str .= '</tr>';
}
if ($str) {
$table = '<table border="1">' . $header . $str . '</table>';
} else {
$tdata = '<tr><td colspan="5">No data found</td></tr>';
$table = '<table border="1">' . $header . $tdata . '</table>';
}
echo $table;
}
Output will be like this:

Mysqli showing table content in one row and column name not retrieved from db

I was trying to use Mysqli instead of Mysql with php in order to gather contents from my database and the code below (code 1) works fine but i have 2 problems:
1 - The code 1 shows all the rows on the same line instead of one above each other.
2 - I cant get how to get the columns name of the table like when i was doing with mysql method (code 2).
---------------------code 1----------------
<?php
$db = new mysqli('localhost', 'root', '', '...');
if($db->connect_errno > 0){
die('Unable to connect to database [' . $db->connect_error . ']');
}
$sql = <<<SQL SELECT * FROM `...`
SQL;
if(!$result = $db->query($sql)){
die('There was an error running the query [' . $db->error . ']');
}
while($row = $result->fetch_assoc()){
echo "<tr class='info'>
<td>" . $row['...'] . "</td>
<td>" . $row['...'] . "</td>
<td>" . $row['...'] . "</td>
</tr>"; } ?>
---------------- code 2------------
<?php
$connection = mysql_connect('localhost', 'root', '');
mysql_select_db('dhocp');
$query = "SELECT * FROM ...";
$result = mysql_query($query);
echo "<table class='table'>";
echo '<tr>';
for ($i = 0; $i < mysql_num_fields($result); $i++) {
echo "<th>".mysql_field_name($result, $i)."</th>";
}
echo '</tr>';
while($row = mysql_fetch_array($result)){ //Creates a loop to loop through results
echo "<tr class='info'><td>" . $row['...'] . "</td>
<td>" . $row['...'] . "</td>
<td>" . $row['...'] . "</td>
</tr>";
}
echo "</table>";
mysql_close();
?>
------------ fix update ------------------
addedd
echo "<table class='table'>";
in code 1 before the while loop
------------ fix update 2 --------------Show column table----
$db = new mysqli("localhost", "...", "...", "...");
$query = "SELECT * from ...";
if ($result = $db->query($query)) {
/* Get field information for all columns */
while ($finfo = $result->fetch_field()) {
printf("%s\n", $finfo->name);
}
$result->close();
}
You could e.g. print the array keys (=field names) on the first iteration
$header = true;
foreach( $mysqli->query('SELECT id,x,y FROM soFoo') as $row ) {
if ( $header ) {
// on the first iteration print the array-keys <-> field names
$header = false;
echo '<tr><th>', join('</th><th>', array_map('htmlspecialchars', array_keys($row))), '</th></tr>', "\r\n";
}
echo '<tr><td>', join('</td><td>', array_map('htmlspecialchars', $row)), '</th></tr>', "\r\n";
}
or you fetch the metadata as descibed at http://docs.php.net/mysqli.quickstart.metadata
$result = $mysqli->query('SELECT id,x,y FROM soFoo');
$meta = $result->fetch_fields();
echo '<tr><th>', join('</th><th>', array_map( function($e) { return htmlspecialchars($e->name); }, $meta)), '</th></tr>', "\r\n";
foreach( $result as $row ) {
echo '<tr><td>', join('</td><td>', array_map('htmlspecialchars', $row)), '</th></tr>', "\r\n";
}

Fitting table in HTML

I'm trying to design a webpage where it simply shows info from a database using PHP.
I almost solve all of my problem but it's the first time I'm using HTML and I am having trouble finding a solution for my problem.
The code I have so far is:
<?php
$connection = mysql_connect('localhost','XXXX','XXXX');
mysql_select_db('cardata_laptimer');
echo "<table>";
echo "<table border = 1>";
$query = "SELECT * from tempos GROUP BY piloto";
$result = mysql_query($query);
while($row = mysql_fetch_array($result))
{
$query = "SELECT * from tempos WHERE piloto = '" . $row['piloto'] . "' ORDER BY tempo";
$resultado = mysql_query($query);
echo "<td>" . $row['piloto'] . "</td></tr>";
while($rows = mysql_fetch_array($resultado))
{
echo "<td>" . $rows['tempo'] . "</td><td>" . $rows['data'] . "</td></tr>";
}
}
The output I'm getting can be seen in www.cardata.pt
1st problem: How to I make the "piloto" (for example AA) occupy the space of 2 cells?
2nd problem: I want the table to show "pilotos" side by side and the info for each one (tempo and data) down the piloto name.
Thanks in advance
To occupy the space of 2 cells add : colspan="2"
here is my edit of your code :
<?php
$connection = mysql_connect('localhost','XXXX','XXXX');
mysql_select_db('cardata_laptimer');
echo '<table border="0"><tr>';
$query = "SELECT * from tempos GROUP BY piloto";
$result = mysql_query($query);
while($row = mysql_fetch_array($result))
{
echo '<td><table border="1"><tr>';
$query = "SELECT * from tempos WHERE piloto = '" . $row['piloto'] . "' ORDER BY tempo";
$resultado = mysql_query($query);
echo '<td colspan="2">' . $row['piloto'] . "</td></tr><tr>";
while($rows = mysql_fetch_array($resultado))
{
echo "<td>" . $rows['tempo'] . "</td><td>" . $rows['data'] . "</td>";
}
echo '</tr></table></td>';
}
echo '</tr></table>';
?>

PHP MySQL Variable Filter - "AND" Acting Like "OR"

Is there a simpler method to using url variables to filter mysql results? I wrote the following code and it works to a degree and I know there has to be a simpler method, but I'm not sure where to start. I'd rather replace this one since it only half works.
$start=0;
$limit=3;
if(isset($_GET['pg']))
{
$pg=$_GET['pg'];
$start=($pg-1)*$limit;
}
else {
$pg = 1;
}
$sql = mysql_query($query);
if(isset($_GET['signage'])) {
$result = mysqli_query($conn,"SELECT * FROM pilotOperators WHERE signage='1' LIMIT $start, $limit");
}
elseif(isset($_GET['certifications'])) {
$certification = $_GET['certifications'];
$result = mysqli_query($conn,"SELECT * FROM pilotOperators WHERE certifications='$certification' LIMIT $start, $limit");
}
elseif(isset($_GET['state'])) {
$state = $_GET['state'];
$result = mysqli_query($conn,"SELECT * FROM pilotOperators WHERE state='$state' LIMIT $start, $limit");
}
elseif(isset($_GET['certifications'], $_GET['signage'])) {
$certification = $_GET['certifications'];
$signage = $_GET['signage'];
$result = mysqli_query($conn,"SELECT * FROM pilotOperators WHERE signage='$signage' AND certifications='$certification' LIMIT $start, $limit");
}
elseif(isset($_GET['certifications'], $_GET['signage'], $_GET['state'])) {
$certification = $_GET['certifications'];
$signage = $_GET['signage'];
$state = $_GET['state'];
$result = mysqli_query($conn,"SELECT * FROM pilotOperators WHERE signage='$signage' AND certifications='$certification' AND state='$state' LIMIT $start, $limit");
}
else {
$result = mysqli_query($conn,"SELECT * FROM pilotOperators LIMIT $start, $limit");
}
while($row = mysqli_fetch_array($result))
{
echo "\n <table border='0' class='resultTable' width='75%'> \n";
echo "<tr> \n";
echo "<td width='120px'>ID: </td> \n";
echo "<td>" . $row['id'] . "</td> \n";
echo "</tr> \n";
echo "<tr> \n";
echo "<td>Name: </td> \n";
echo "<td>" . $row['name'] . "</td> \n";
echo "</tr> \n";
echo "<tr> \n";
echo "<td>Phone: </td> \n";
echo "<td>" . $row['phone'] . "</td> \n";
echo "</tr> \n";
echo "<tr> \n";
echo "<td>Alt. Phone: </td> \n";
echo "<td>" . $row['alt_phone'] . "</td> \n";
echo "</tr> \n";
echo "<tr> \n";
echo "<td>Fax: </td> \n";
echo "<td>" . $row['fax'] . "</td> \n";
echo "</tr> \n";
echo "<tr> \n";
echo "<td>Email: </td> \n";
echo "<td>" . $row['email'] . "</td> \n";
echo "</tr> \n";
echo "<tr> \n";
echo "<td>Website: </td> \n";
echo "<td><a href='" . $row['website'] . "' target='_blank'>" . $row['website'] . "</a></td> \n";
echo "</tr> \n";
echo "<tr> \n";
echo "<td>City: </td> \n";
echo "<td>" . $row['city'] . "</td> \n";
echo "</tr> \n";
echo "<tr> \n";
echo "<td>State: </td> \n";
echo "<td>" . $row['state'] . "</td> \n";
echo "</tr> \n";
echo "<tr> \n";
echo "<td>Certifications: </td> \n";
echo "<td>" . $row['certifications'] . "</td> \n";
echo "</tr> \n";
echo "<tr> \n";
echo "<td>Top Sign: </td> \n";
echo "<td>";
if($row['signage'] = 1) {
echo "Has Top Sign";
}
else {
echo "Top Sign Not Listed";
}
echo "</td> \n";
echo "</tr> \n";
echo "</table> \n\n";
}
$rows = mysqli_num_rows(mysqli_query($conn, "SELECT * FROM pilotOperators"));
$total=ceil($rows/$limit);
echo "<div id='paginationLinks'> \n";
if($pg>1)
{
echo "<a href='?pg=".($pg-1)."' class='paginationButton'>PREVIOUS</a> \n";
}
if($pg!=$total)
{
echo "<a href='?pg=".($pg+1)."' class='paginationButton'>NEXT</a> \n";
}
echo "<ul class='page'> \n";
for($i=1;$i<=$total;$i++)
{
if($i==$pg) { echo "<li class='current'>".$i."</li> \n"; }
else { echo "<li><a href='?id=".$i."'>".$i."</a></li> \n"; }
}
echo "</ul> \n";
echo "</div> \n";
mysqli_close($con);
When I said that this code kinda works allow me to explain. When I have multiple variables in my url(I.E. ?signage=VALUE&certifications=VALUE) the code acts like it has OR in place of AND.
Like This: $result = mysqli_query($conn,"SELECT * FROM pilotOperators WHERE signage='$signage' OR certifications='$certification' LIMIT $start, $limit");
Instead Of This: $result = mysqli_query($conn,"SELECT * FROM pilotOperators WHERE signage='$signage' AND certifications='$certification' LIMIT $start, $limit");
If my URL contains the following &signage=1&certifications=washington it is not only showing me results that have both of those, but it is showing me results of people with Washington certifications OR where signage=1.
I don't have many variables that will be passed. It should only be 3, but my method just seems complicated.
What can I do to make this simpler and why does my AND act like OR when attempting to filter the results.
Q: What can I do to make this simpler?
A: You could do something like the following, to conditionally append a predicate to the SQL statement, and defer running the statement until it's fully built. It looks like you only need to run one SQL statement, so there only needs to be one call to mysqli_query. Populate a variable to contain populate with the SQL text, and have mysqli_query reference the variable.
NOTE: Any potentially unsafe values must be properly escaped to thwart SQL Injection vulnerabilities. (Note the use of the mysqli_real_escape_string function around every value that's being included in the SQL text.)
For example:
# start of SQL statement
$sql = "SELECT * FROM pilotOperators WHERE 1=1";
# append condition for signage (if required)
if(isset($_GET['signage'])) {
$sql .= " AND signage='1'";
}
# append condition for certifications (if required)
if(isset($_GET['certifications'])) {
$certification = mysqli_real_escape_string($conn,$_GET['certifications']);
$sql .= " AND certifications='$certification'"
}
# append condition for state (if required)
if(isset($_GET['state'])) {
$state = mysqli_real_escape_string($conn,$_GET['state']);
$sql .= " AND state='$state'";
}
# append ORDER BY and LIMIT
$sql .= " ORDER BY 1,2,3";
$sql .= " LIMIT " . mysqli_real_escape_string($conn,$start)
. "," . mysqli_real_escape_string($conn,$limit);
#echo "SQL=" . $sql; // for debugging
$result = mysqli_query($conn,$sql);
I've also added an ORDER BY clause so the rows will be returned in a deterministic sequence; replace the positional references to the columns you want.
The WHERE 1=1 is a dummy placeholder, that will always evaluate to TRUE. The purpose of that is so that any subsequent predicates can be added with an AND and we don't need to muck with figuring out whether this is the first predicate being added, and we need to use WHERE instead of AND.
The leading space in each part that's being appended is important. (I just find it easier to handle that as a leading character, rather than remembering to add it at the end, but you could have the space at the end of each part instead).
Q: Why is my AND acting like OR?
A: It's not, you're never getting to a statement that has an AND in it. If "certifications" is set, you're executing a SQL statement that contains only a predicate on the certifications column. You never reach the elseif for "certifications" and "state" both being set.
FOLLOWUP
There's an error in the code above, a missing semicolon (statement terminator) is missing from one line:
$sql .= " AND certifications='$certification'" ;
^
The .= operator appends the value on the right to the current value of the variable on the left. That is, this statement
$x .= "foo";
does the same thing as this statement.
$x = $x . "foo";
The variables $certification and $state aren't really necessary. You could remove these two lines:
$state = mysqli_real_escape_string($conn,$_GET['state']);
$sql .= " AND state='$state'";
and replace it with this:
$sql .= " AND state='" . mysqli_real_escape_string($conn,$_GET['state']) . "'";
But breaking that into two separate lines does make it easier to debug and spot mistakes, easy to add an echo or var_dump for debugging...
$state = mysqli_real_escape_string($conn,$_GET['state']);
echo "state=" . $state ;
var_dump($state);
$sql .= " AND state='$state'";
That is not best thing you should really do, but just like an idea:
$query = 'SELECT * FROM pilotOperators ';
$filters = array('signage', 'certifications', 'state');
$where = false;
foreach($filters as $filter) {
if (isset($_GET[$filter])) {
$filter_val = mysqli_real_escape_string($_GET[$filter]);
if (! $where ) {
$where = true;
$query .= ' WHERE '.$filter.'= "'.$filter_val.'"';
} else {
$query .= ' AND '.$filter.'= "'.$filter_val.'"';
}
}
}
$query .= " LIMIT $start, $limit";
$result = mysqli_query($conn,$query);
EDIT 1 Ignore some values of filter
$filters = array('signage', 'certifications', 'state');
$filters_ignore_value = array('state'=>'Select State');
$where = false;
foreach($filters as $filter) {
if (isset($_GET[$filter])) {
$filter_val = mysqli_real_escape_string($_GET[$filter]);
if (isset($filters_ignore_value[$filter] && $filters_ignore_value[$filter] == $filter_val) {
continue;
}
if (! $where ) {
$where = true;
$query .= ' WHERE '.$filter.'= "'.$filter_val.'"';
} else {
$query .= ' AND '.$filter.'= "'.$filter_val.'"';
}
}
}
When I have multiple variables in my url(I.E. ?signage=VALUE&certifications=VALUE) the code acts like it has OR in place of AND
Take the example of signage AND certifications being set: the first if clause will evaluate to true, resulting in that query being executed regardless of whether certifications is set. You might consider re-ordering the if/elseif. For instance:
//check for all
if(isset($_GET['certifications'], $_GET['signage'], $_GET['state'])) {
}elseif (isset($_GET['certifications'], $_GET['signage'])){
}elseif (){
}
Alternatively, as suggested in another answer, build your query up by checking each requisite parameter

PHP - trying to print a table from a reference number which has been stored in an array?

Hi I'm wondering if you could help me? I'm trying to get the rows from the the database by using the reference number that I have stored in an array called items, and displaying the rows in a table, but I can only get the references number to show on the page...any help be really appreciated?
</head>
<h1>Shopping Cart</h1>
<body>
<?php $con = pg_connect("blah blah");
if (!$con){
die('Could not connect: ' . pg_error());
}
if (isset($_POST['items'])) {
$n = count($_POST['items']);
for($i=0; $i < $n; $i++)
echo $_POST['items'][$i];
}
if(!$_SESSION["selectingrows"]== 0){
$result = pg_query ($con, "SELECT title, platform, description, price FROM CSGames WHERE 'refnumber' = 'items[]'");
echo "<table>
<tr>
<th>Title</th>
<th>Platform</th>
<th>Description</th>
<th>Price</th>
</tr>";
while($rows = pg_fetch_result($result));{
echo"<tr>"; echo "<td>" . $rows['title'] . "</td>"; echo "<td>" . $rows['platform'] . "</td>"; echo "<td>" . $rows['description'] . "</td>"; echo "<td>" . $rows['price'] . "</td>";
echo"</tr>";
}
echo"</table>";
}
You are blocking your while statement:
while($rows = pg_fetch_result($result));{
and should be:
while($rows = pg_fetch_result($result)){
notice the semicolon is gone.
EDIT: It appears that there are more syntax errors (this is complete):
$con = pg_connect("blah blah");
if (!$con){
die('Could not connect: ' . pg_error());
}
if (isset($_POST['items'])) {
$n = count($_POST['items']);
for($i=0; $i < $n; $i++){
echo $_POST['items'][$i];
}
if(!$_SESSION["selectingrows"]== 0){
$result = pg_query ($con, "SELECT title, platform, description, price FROM CSGames WHERE 'refnumber' = 'items[]'");
echo "<table>
<tr>
<th>Title</th>
<th>Platform</th>
<th>Description</th>
<th>Price</th>
</tr>";
while($rows = pg_fetch_result($result));{
echo"<tr>"; echo "<td>" . $rows['title'] . "</td>"; echo "<td>" . $rows['platform'] . "</td>"; echo "<td>" . $rows['description'] . "</td>"; echo "<td>" . $rows['price'] . "</td>";
echo"</tr>";
}
echo"</table>";
}
}
I imagine your problem is here:
$result = pg_query ($con, "SELECT title, platform, description, price FROM CSGames WHERE 'refnumber' = 'items[]'");
items[] is not any kind of valid variable reference. You are probaly needing to do something like this:
$items = array();
foreach ($_POST['items'] as $item) {
$items[] = pg_escape_string($con, $item);
}
$item_string = "'" . implode("','", $items) . "'";
$result = pg_query ($con, "SELECT title, platform, description, price FROM CSGames WHERE 'refnumber' IN ($item_string)");
Note I have escaped the posted data for use in the query, I have built a string of all teh values, and then used that string in SQL WHERE 'refnumber' IN clause.
</head>
<h1>Shopping Cart</h1>
<body>
<?php $con = pg_connect("blah blah");
if (!$con){
die('Could not connect: ' . pg_error());
}
if (isset($_POST['items'])) {
$n = count($_POST['items']);
$items = array();
for($i=0; $i < $n; $i++)
array_push($items,$_POST['items'][$i]; // stored referrral_no in array
}
$items = implode("','",$items); // implode to query use
if(!$_SESSION["selectingrows"]== 0){
$result = pg_query ($con, "SELECT title, platform, description, price FROM CSGames WHERE 'refnumber' IN ('$items')"); // revise query to IN
echo "<table>
<tr>
<th>Title</th>
<th>Platform</th>
<th>Description</th>
<th>Price</th>
</tr>";
while($rows = pg_fetch_result($result)){
echo"<tr>"; echo "<td>" . $rows['title'] . "</td>"; echo "<td>" . $rows['platform'] . "</td>"; echo "<td>" . $rows['description'] . "</td>"; echo "<td>" . $rows['price'] . "</td>";
echo"</tr>";
}
echo"</table>";
}
try this i first stored again your items in array
then implode it for use in query

Categories