Get data of multiple columns from SQL Server using PHP - php

I am trying to select the data from SQL Server but only the columns stored in the variable SelectedColumns. This variable store the columns' names separated by comma from a drop Down list. For example : echo $SelectedColumns will display Country,Product,Date
I could create the header of the table by exploding the variable and use foreach. Now I want to get the data of these columns display it in the <tbody> </tbody>
Here is my php page :
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$ser="********";
$db="********";
$user="********";
$pass="********";
$query = 'SELECT '.$_POST['selectedColumns'].' FROM ********';
$dbDB = new PDO("odbc:Driver=ODBC Driver 13 for SQL Server;Server=********,1456;Database=********;Port=1456", $user, $pass);
?>
<!DOCTYPE html>
<html>
<head>
<title>table</title>
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.15/css/jquery.dataTables.min.css" />
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>
</head>
<body>
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<?php
$row = $_POST["selectedColumns"];
$rows = explode(",",$row);
echo "<tr>";
foreach ($rows as $r ) {
echo "<td>";
echo $r;
echo "<td>";
}
echo "</tr>";
?>
</thead>
<tbody>
</tbody>
</table>
</body>
</html>
<script>
$(document).ready(function() {
$('#example').DataTable();
} );
</script>
I was trying this solution to use foreach twice
<?php
$row = $_POST["selectedColumns"];
$rows = explode(",",$row);
foreach ($dbDB->query($query) as $dataRow) {
echo "<tr>";
foreach ($rows as $r ) {
echo "<td>" . $dataRow[$r] . "</td>"; }
echo "</tr>";
}
?>
But it's not working. Any suggestions please ? Thank you very much.

Related

PHP How to use for loop's variable with mysql_fetch_array to indicate row to get data?

I have trouble to use for loop's variable $counter with
$HA_Row = mysql_fetch_array($HA_Res);
to indicate which row's data I am going to get. Basically, I have no idea to use $counter and $HA_Res together.
I want to it can display different rows' data of my database.
For example, like
echo "$HA_Row[Check_In_Date]"
I have tried
echo "$HA_Row[$counter][Check_In_Date]"
and
echo "$HA_Row[Check_In_Date][$counter]", echo "[$counter]$HA_Row[Check_In_Date]"
but none of them works.
Thank you so much! Appreciate your time.
<?php
session_start();
include_once 'dbconnect.php';
if(!isset($_SESSION['Hotel_User_ID']))
{
header("Location: index.php");
}
$res = mysql_query("SELECT * FROM Hotel_Info WHERE Hotel_ID =".$_SESSION['Hotel_User_ID']);
$userRow = mysql_fetch_array($res);
$HA_Res = mysql_query("SELECT * FROM Hotel_Account WHERE Hotel_ID =".$_SESSION['Hotel_User_ID']);
$HA_Row = mysql_fetch_array($HA_Res);
$HA_Count = mysql_num_rows($HA_Res);
// echo "$HA_Count". "<br>";
// echo "$HA_Row[Check_In_Date]";
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Hello - <?php echo $userRow['Hotel_Email']; ?></title>
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<div id="header">
<div id="left">
<label>Welcome <?php echo $userRow['Hotel_Uname']; ?> </label>
</div>
<div id="right">
<div id="content">
Sign Out
</div>
</div>
</div>
<div id="menu">
Manage <br>
Update
</div>
<div id="body">
<center>
<div id="Hotel-InfoForm">
<form method="post" enctype="multipart/form-data">
<!-- <table.ver2 align="center" width="60%" border="0"> -->
<table align="center" width="85%" border = "1">
<tr>
<th>Check In Data</th>
<th>Check Out Data</th>
<th>Theme</th>
<th>Bed Size</th>
<th>First Name</th>
<th>Last Name</th>
<th>Gender</th>
<th>Age</th>
<th>Phone Number</th>
<th>Email</th>
</tr>
<?php
for($counter = 0; $counter < $HA_Count; $counter = $counter + 1)
{
// using $counter for $HA_Row[....]
echo "<tr>";
echo "<td>";
echo "$HA_Row[Check_In_Date]";
echo "</td>";
echo "<td>";
echo "$HA_Row[Check_Out_Date]";
echo "</td>";
$Theme_Res = mysql_query("SELECT * FROM Theme WHERE Theme_ID = ".$HA_Row[Theme_ID]);
$Theme_Row = mysql_fetch_array($Theme_Res);
echo "<td>";
echo "$Theme_Row[Theme_Name]";
echo "</td>";
echo "<td>";
echo "$Theme_Row[Bed_Size]";
echo "</td>";
$Guest_Res = mysql_query("SELECT * FROM Guest_Info WHERE Guest_ID = ".$HA_Row[Guest_ID]);
$Guest_Row = mysql_fetch_array($Guest_Res);
echo "<td>";
echo "$Guest_Row[First_Name]";
echo "</td>";
echo "<td>";
echo "$Guest_Row[Last_Name]";
echo "</td>";
echo "<td>";
echo "$Guest_Row[Gender]";
echo "</td>";
function ageCalculator($dob)
{
if(!empty($dob))
{
$birthdate = new DateTime($dob);
$today = new DateTime('today');
$age = $birthdate->diff($today)->y;
return $age;
}
else
{
return 0;
}
}
echo "<td>";
echo ageCalculator($Guest_Row[Birth_Day]);
echo "</td>";
echo "<td>";
echo "$Guest_Row[Phone_Num]";
echo "</td>";
echo "<td>";
echo "$Guest_Row[Email]";
echo "</td>";
echo "</tr>\n";
}
?>
</table>
</form>
</div>
</center>
</div>
</body>
</html>
You could use mysql_fetch_assoc and while looping, like this:
while($HA_Row = mysql_fetch_assoc($HA_Res)){
echo $HA_Row[Check_In_Date]."<br>";
};
This while will loop in each instance!
You don't normally use a counter to control fetch, especially if you just want to process the records in sequence. Each call to fetch will return the next row in the result set without further action on your part.
First, replace all your mysql_* calls with their mysqli_* counterparts. Then replace your line
for($counter = 0; $counter < $HA_Count; $counter = $counter + 1)
with
while ($HA_Row = mysqli_fetch_array($HA_Res))
On each loop, mysqli_fetch_array returns the next row, and after reading the last row the next call returns false, which exits the loop.
Switching to mysqli_* or PDO will also gain you prepared statements, which help to protect against SQL injection, among numerous other benefits.

I am trying to add a dropdown menu box within a table with data fetched from mysql

I am using notepad, xampp and mysql and phpMyadmin to create a football prediction website. On the prediction page I have a page showing the fixture in a table. I want the use to be able to post a Home_Sore and Away_Score for each corresponding fixture using a series of dropdown menus with numbers 1-20.
For example:
Fixture_ID|Home_Team|Home_Score|Away_Score|Away_Team|
1 Man United <Dropdown> <Dropdown> Spurs
Is this possible? I am new to php coding and would appreciate any help i get!:)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<?php
$connection = mysql_connect('localhost', 'root', 'password'); //The Blank string is the password
mysql_select_db('mls');
$query = "SELECT * FROM fixtures"; //You don't need a ; like you do in SQL
$result = mysql_query($query);
$columns = array();
$resultset = array();
# Set columns and results array
while ($row = mysql_fetch_assoc($result)) {
if (empty($columns)) {
$columns = array_keys($row);
}
$resultset[] = $row;
}
# If records found
if( count($resultset > 0 )) {
?>
<table class="table table-bordered" >
<thead>
<tr class='info';>
<?php foreach ($columns as $k => $column_name ) : ?>
<th> <?php echo $column_name;?> </th>
<?php endforeach; ?>
</tr>
</thead>
<tbody>
<?php
// output data of each row
foreach($resultset as $index => $row) {
$column_counter =0;
?>
<tr class='success';>
<?php for ($i=0; $i < count($columns); $i++):?>
<td> <?php echo $row[$columns[$column_counter++]]; ?> </td>
<?php endfor;?>
</tr>
<?php } ?>
</tbody>
</table>
<?php }else{
?>
<h4> echo Information Not Available </h4>
<?php }
?>
</body>
</html>
You can do this by including something like this in td tag
<select name="mySelect">
<?php $result= mysql_query('SELECT * FROM fixtures'); ?>
<?php while($row= mysql_fetch_assoc($result)) { ?>
<option value="<?php echo $row['your_column_name'];?>">
<?php echo $row['your_column_name']; ?>
</option>
<?php } ?>
</select>

add/remove data from table from previous page

I have an HTML table being displayed from php data and I'm trying to move data from one table to another based on what is clicked. I cannot get it to move from table to another but I"m not getting any code error.
<html>
<head>
<title>View Requests</title>
</head>
<body>
<div class="breadcrumbs">
<center>
Home · Requests
</center>
</div>
<?php
require_once '../../scripts/app_config.php';
require_once '../../scripts/database_connection.php';
// get results from database
$result = mysql_query("SELECT * FROM temp")
or die(mysql_error());
echo "<table border='1' cellpadding='10'>";
echo "<tr> <th>ID</th> <th>First Name</th> <th>Last Name</th> <th>Username</th> <th></th> <th></th></tr>";
// loop through results of database query, displaying them in the table
while($row = mysql_fetch_array( $result )) {
// echo out the contents of each row into a table
echo "<tr>";
echo '<td>' . $row['User_id'] . '</td>';
echo '<td>' . $row['First_name'] . '</td>';
echo '<td>' . $row['Last_name'] . '</td>';
echo '<td>' . $row['Username'] . '</td>';
echo '<td>Approve</td>';
echo '<td>Delete</td>';
echo "</tr>";
}
// close table>
echo "</table>";
?>
</body>
</html>
PHP EDIT SCRIPT:
<html>
<head>
<title>View Requests</title>
</head>
<body>
<div class="breadcrumbs">
<center>
Home · Requests · All Users
</center>
<?php
require_once '../../scripts/app_config.php';
require_once '../../scripts/database_connection.php';
$id = $_GET['id'];
$sql = ("INSERT INTO users
SELECT * FROM temp WHERE User_id = $id ");
mysql_query($sql)
or die(mysql_error());
?>
</body>
</html>
I needed to use
$id = $_get['id];
and in the insert statement i had to replace id with User_id
<html>
<head>
<title>View Requests</title>
</head>
<body>
<div class="breadcrumbs">
<center>
Home · Requests · All Users
</center>
<?php
require_once '../../scripts/app_config.php';
require_once '../../scripts/database_connection.php';
$id = $_GET['id'];
$sql = ("INSERT INTO users
SELECT * FROM temp WHERE User_id = $id ");
mysql_query($sql)
or die(mysql_error());
?>
</body>
</html>

hyperlink trouble in php echo'd table

I"m having trouble with my code hopefully someone can help.
I'm trying to call information using "php echo" to display information in table form and it works except for the links which doesn't recognize the $id. If I don't put it in the table form it works fine but it is not aesthetically appealing.
Any suggestions would be greatly appreciated!
<?php
session_start();
if(!isset($_SESSION['name'])){
header("location: ../index.php");
exit();
}
// Script Error Reporting
error_reporting(E_ALL);
ini_set('display_errors', '1');
include_once("../scripts/connect.php");
// Delete Item Question to Admin, and Delete Product if they choose
if (isset($_GET['deleteid'])) {
echo 'Do you really want to delete messages with ID of ' . $_GET['deleteid'] .'? Yes | No';
exit();
}
if (isset($_GET['yesdelete'])) {
// delete from database
$id_to_delete = $_GET['yesdelete'];
$sql = mysql_query("DELETE FROM `mystore`.`messages` WHERE `messages`.`id` = '$id_to_delete' LIMIT 1") or die (mysql_error());
}
$messages = "";
$sql = mysql_query("SELECT * FROM messages ORDER BY msg_date DESC LIMIT 20");
$count = mysql_num_rows($sql);
if($count > 0){
while($row = mysql_fetch_array($sql)){
echo '<tr>';
echo '<td>'.$row['msg_name'].'</td>';
echo '<td>'.$row['msg_email'].'</td>';
echo '<td>'.$row['msg_subject'].'</td>';
echo '<td>'.$row['msg_date'].'</td>';
echo '<td>Reply</td>';
echo '<td>Delete</td>';
echo '</tr>';
}
}else{
$messages = "<b>There are no messages in the database at this moment</b>";
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Admin Messages</title>
<meta charset="utf-8" />
<link rel="stylesheet" href="style/forms.css" media="screen">
<link rel="stylesheet" href="style/main.css" media="screen">
</head>
<body>
<div id="main_wrapper">
<?php include_once("templates/tmp_header.php"); ?>
<?php include_once("templates/tmp_nav.php"); ?>
<section id="main_content">
<h2 class="page_title">Messages</h2>
<br/>
<table width="730" cellspacing="0" cellpadding="3" border="1">
<tr>
<td align="center" width="100">From</td>
<td align="center" width="300">Email</td>
<td align="center" width="300">Subject</td>
<td align="center" width="100">Date</td>
<td align="center" width="100">Actions</td
></tr>
<?php echo $messages; ?>
</table>
</section>
<?php include_once("templates/tmp_aside.php"); ?>
<?php include_once("templates/tmp_footer.php"); ?>
</div>
Please change
echo '<td>Delete</td>';
to
echo "<td><a href='admin_messages.php?deleteid=$id'>Delete</a></td>";
when trying to print out a variable the main string has to be wrapped in double quotes.
If you want to interpolate variables in PHP, you need to use double quotes. echo '$id' will literally print $id, whereas echo "$id" will print the value of the variable. However, I would recommend an alternative approach. Don't use PHP where it isn't needed. There's no need to use echo so much.
I would change the contents of your loop to this:
?>
<tr>
<td><?=$row['msg_name']?></td>
<td><?=$row['msg_email']?></td>
<td><?=$row['msg_subject']?></td>
<td><?=$row['msg_date']?></td>
<td>Reply</td>
<td>Delete</td>
</tr>
<?php
The <?=$id?> is shorthand for <?php echo $id?> and is supported by default in PHP versions >=5.4.0. You can also use it in previous versions if you enable short_open_tags.
As stated in the comments, you should really be using mysqli functions, as mysql functions are deprecated.

Put MySQL request result in table

<?PHP
?>
<html>
<head>
<title></title>
<link rel="stylesheet" href="one.css" type="text/css">
</head>
<?
include_once "db.php";
$result = mysql_query("SELECT * FROM products WHERE product_type='weddingdressaline' ORDER BY user_id");
{
echo "<table width='100%' border='5' bordercolor='#860071' cellspacing='5' cellpadding='5'>";
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_array($result))
{
echo "<tr>";
$i = 0;
while ($i < 3)
{
echo '<td><table width="100%" border="0" cellspacing="0" cellpadding="0" BGCOLOR="#AA99C5"><TR><TD><div class="container"><img src="showimage.php?user_id=' . $row["user_id"] . '" ALIGN="CENTER" /></div></td><tr><td><CENTER><STRONG>' . $row['price'] . '</STRONG></td></TABLE>';
$i++;
}
echo "</tr>";
}
} else {
echo "<tr><td colspan='" . ($i + 1) . "'>No Results found!</td></tr>";
}
echo "</table>";
}
?>
The code is suppose to put one item into one column. Unfortunately its placing one result for the entire row. If anyone has any ideas how to fix this please help.
You have some access brackets in your code:
$result = mysql_query("SELECT * FROM products WHERE product_type='weddingdressaline' ORDER BY user_id");
{ <===
echo "<table width='100%' border='5' bordercolor='#860071' cellspacing='5' cellpadding='5'>";
[....]
echo "</table>";
} <===
First of all please learn some clean coding standards for everyones sake:
http://drupal.org/coding-standards
The second problem is that your are outputting this in the wrong. Trying to use tables for one (use divs) is just poor markup these days. All your styles should be in your CSS, not embedded on the page.
Here is your greatly improved markup. You use CSS to change how it is displayed on the page, not a table structure.
<html>
<head>
<title></title>
<link rel="stylesheet" href="one.css" type="text/css">
</head>
<body>
<?php
include_once "db.php";
$result = mysql_query("SELECT * FROM products WHERE product_type = 'weddingdressaline' ORDER BY user_id");
echo '<div class="productTable">';
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_object($result)) {
echo '
<div class="container">
<div class="productImage">
<a href="viewproduct.php?user_id=' . $row->user_id . '">
<img src="showimage.php?user_id=' . $row->user_id . '" align="center" />
</a>
</div>
<div class="price">' . $row->price . '</div>
</div>';
}
}
else {
echo '<div class="container"><div class="noResults">No Results found!</div></div>';
}
echo "</div>";
?>
</body>
</html>

Categories