This is the first time I'm using this website, I have recently started working on a project where the webpage will display two table, one of the table will gather all the information from a SQL Database and place them in the table along with a button next to each rows allowing you to insert that record to another to the other table, so far, this is the code I have written:
//Include the Following Files
include 'connect.php';
//Select All Price Plans
$query = "SELECT * FROM pricing";
$result = mysql_query($query);
//Print all Plans in Table
while ($pricing = mysql_fetch_array($result))
{
echo "<table border=1>";
echo "<tr>";
echo "<td>" .$pricing['planID']. "</td>";
echo "<td>" .$pricing['planTitle']. "</td>";
echo "<td>" .$pricing['planDescription']. "</td>";
echo "<td>" .$pricing['planPricing']. "</td>";
echo "<td>" . **BUTTON HERE** . "</td>";
echo "</tr>";
echo "<table>";
}
//Assign $link to Case
$link = '?run=planA';
//Pre-defined Functions
function planA()
{
$query = "INSERT into restaurant_plan (`planID`, `planTitle`, `planDescription`, `planPricing`) SELECT * FROM pricing WHERE planID='2' ";
$result = mysql_query($query);
}
//Setting Case to Run Each Functions
if (isset($_GET['run'])) $linkchoice=$_GET['run'];
else $linkchoice='';
switch($linkchoice)
{
case 'planA':
planA();
break;
case 'planB':
planB();
break;
}
Could anyone suggest any guide or possibly an example how I could assign a function to each rows? Thanks a lot!
your code prints one table for each record in table "pricing", use this code instead :
//Select All Price Plans
$mysqli = new mysqli("hostname", "username", "pass", "dbname");
$query = "SELECT * FROM pricing";
$result = $mysqli->query($query);
//Print all Plans in Table
echo "Available Price Plans";
echo "<table border=1>";
while ( $pricing = $result->fetch_assoc() ) {
echo "<tr>";
echo "<td>" .$pricing['planID']. "</td>";
echo "<td>" .$pricing['planTitle']. "</td>";
echo "<td>" .$pricing['planDescription']. "</td>";
echo "<td>" .$pricing['planPricing']. "</td>";
echo "<td>" .'<img style="border:none;" src="'. $icon .'" />'. "</td>";
//print a button as you mentioned
echo "<td>"."<form action='#' method='get'><input type='hidden' name='id' value='".$pricing['planID']."'/><input type='submit' value='copy'/></form></td>";
echo "</tr>";
}
echo "</table>";
and your function :
function planA()
{
// get selected plan info
$query = "SELECT * FROM pricing";
$result = $mysqli->query($query);
$row = $res->fetch_assoc();
//copy info to table 'restaurant_plan'
$query = "INSERT into restaurant_plan (".$_GET["id"].", ".$row["planTitle"].", ".$row["planDescription"].", ".$row["planPricing"].")";
$result = $mysqli->query($query);
}
Not an answer, but if you want your code to be cleaner & more readable/maintainable, you should use HTML with PHP inserted, rather than echoing HTML via PHP:
<?php
//Select All Price Plans
$query = "SELECT * FROM pricing";
$result = mysql_query($query);
//Print all Plans in Table
?>
Available Price Plans
<?php while ($pricing = mysql_fetch_array($result)) : ?>
<table border=1>
<tr>
<td><?= $pricing['planID'] ?></td>
<td><?= $pricing['planTitle'] ?></td>
<td><?= $pricing['planDescription'] ?></td>
<td><?= $pricing['planPricing'] ?></td>
<td><img style="border:none;" src="<?= $icon ?>" /></td>
</tr>
<table>
<?php endforeach; ?>
Also, as I mentioned in the comments above, you should stop using mysql_* functions. They're being deprecated. Instead use PDO (supported as of PHP 5.1) or mysqli (supported as of PHP 4.1). If you're not sure which one to use, read this article.
Change your table output to the following:
<table border="1">
<?php
while ($pricing = mysql_fetch_array($result)) {
?>
<tr>
<td><?php echo $pricing['planID']; ?></td>
<td><?php echo $pricing['planTitle']; ?></td>
<td><?php echo $pricing['planDescription']; ?></td>
<td><?php echo $pricing['planPricing']; ?></td>
<td><a href='<?php echo $link; ?>'><img style="border:none;" src='<?php echo $icon; ?>' /></a></td>
</tr>
<?php
}
?>
<table>
Double check you database connection as well to ensure data can be retrieved.
Related
I need help, I cannot figure out, I cannot find why I am having errors and I am not able to achieve something freaking simple.
Long story short, I have a website to manage projects, so when I run the search function it throws a table with some records from the database, there is a button called "see details" which is assigned to a project id with database i.e. 21, 1, 48 etc, the problem is that when I click "see details" it throws everything from the table proposals instead of 1 project, no matter which button I click on, if its id 1, 21, 48, it prints everything.
details page
details.php:
<?php
include '../includes/config.php';
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Attempt select query execution
$sql = "SELECT * FROM proposals_table WHERE id LIKE '_%'";
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
echo "<table class='table table-bordered'>";
echo "<tr>";
echo "<th>Organisation</th>";
echo "<th>Project</th>";
echo "<th>Proposal Date</th>";
echo "<th>Date Received</th>";
echo "<th>Notes</th>";
echo "</tr>";
while($row = mysqli_fetch_array($result)){
echo "<tr>";
echo "<td>" . $row['company'] . "</td>";
echo "<td>" . $row['project'] . "</td>";
echo "<td>" . $row['proposal_date'] . "</td>";
echo "<td>" . $row['date_received'] . "</td>";
echo "<td>" . $row['notes'] . "</td>";
echo "</tr>";
}
echo "</table>";
// Free result set
mysqli_free_result($result);
} else{
echo "No records matching your query were found.";
}
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
?>
search/result page
proposals.php
<?php
include '../includes/config.php';
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Attempt select query execution
$sql = "SELECT * FROM proposals_table";
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
echo "<table class='table table-bordered'>";
echo "<tr>";
echo "<th>Organisation</th>";
echo "<th>Project</th>";
echo "<th>Proposal Date</th>";
echo "<th>Date Received</th>";
echo "<th>Options</th>";
echo "</tr>";
while($row = mysqli_fetch_array($result)){
echo "<tr>";
echo "<td>" . $row['company'] . "</td>";
echo "<td>" . $row['project'] . "</td>";
echo "<td>" . $row['proposal_date'] . "</td>";
echo "<td>" . $row['date_received'] . "</td>";
echo "<td> <a class='btn btn-primary' href='details.php?id={$row['id']}'>See details</a></td>";
echo "</tr>";
}
echo "</table>";
// Free result set
mysqli_free_result($result);
} else{
echo "No records matching your query were found.";
}
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
?>
If you want to show only the selected element on your details page then you need to fetch only that selected item from the database.
First of all you should separate HTML from PHP. The best would be to have them in separate files. In PHP you prepare the data to be displayed and then in HTML you fill in the blanks with PHP values.
To select a value from MySQL using a given ID you must use prepared statements with parameter binding. So if you create your link in this way:
echo "<td> <a class='btn btn-primary' href='details.php?id=".urlencode($row['id'])."'>See details</a></td>";
You can receive this ID in your details page using $_GET['id']. You can bind that value to your WHERE clause in SQL.
<?php
include '../includes/config.php';
// Attempt select query execution
$stmt = $link->prepare("SELECT * FROM proposals_table WHERE id=?");
$stmt->bind_param('s', $_GET['id']);
$stmt->execute();
$proposals = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
if($proposals) {
?>
<table class='table table-bordered'>
<tr>
<th>Organisation</th>
<th>Project</th>
<th>Proposal Date</th>
<th>Date Received</th>
<th>Notes</th>
</tr>
<?php foreach($proposals as $row): ?>
<tr>
<td><?=$row['company'] ?></td>
<td><?=$row['project'] ?></td>
<td><?=$row['proposal_date'] ?></td>
<td><?=$row['date_received'] ?></td>
<td><?=$row['notes'] ?></td>
</tr>
<?php endforeach; ?>
</table>
<?php
} else {
echo 'No records matching your query were found.';
}
And of course your config.php page should look like this:
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = new mysqli('localhost', 'user', 'pass', 'db');
$link->set_charset('utf8mb4'); // always set the charset
*Below is my code
When I click search, it only display one result from my database.
Is there other method to solve this problem?
Or how to save multiple variables in the session and then display it?
<?php
session_start();
?>
<?php
include("htmltable.php");
?>
<table align="center">
<table class="data-table">
<caption class="title">Donor Lists</caption>
<thead>
<tr>
<th>DonorID</th>
<th>Donor</th>
<th>gender</th>
<th>bloodgroup</th>
<th>State</th>
</tr>
</thead>
<tbody>
<td><?php echo("{$_SESSION['DonorID']}"."<br />");?></td>
<td><?php echo("{$_SESSION['FullName']}"."<br />");?></td>
<td><?php echo("{$_SESSION['gender']}"."<br />");?></td>
<td><?php echo("{$_SESSION['bloodgroup']}"."<br />");?></td>
<td><?php echo("{$_SESSION['State']}"."<br />");?></td>
</tbody>
</table>
</table>
This is the process, when user search, it will select from the database and then display it at the search donor page.
<?php
session_start();
include "dbh.inc.php";
if (isset($_POST['submit']))
{
$sql="SELECT * FROM donorregistration WHERE (bloodgroup='{$_POST["bloodgroup"]}' AND State='{$_POST["State"]}')";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_assoc($result))
{
$_SESSION['DonorID'] = $row['DonorID'];
$_SESSION['FullName'] = $row['FullName'];
$_SESSION['gender'] = $row['gender'];
$_SESSION['bloodgroup'] = $row['bloodgroup'];
$_SESSION['State'] = $row['State'];
header("Location: ../assignbloodbank/Searchdonor.php?search=success");
exit();
}
}
else
{
echo "<div class='alert alert-danger'><i class='fa fa-users'></i> No Donors Found</div>";
}
}
?>
When you use header("Location") inside of a while loop only the first redirect will work. And when you use exit() no further code will execute. Also, there's no need to set $_SESSION for every row (as that will overwrite the variable too, unless you use an array for each session value with $_SESSION['key'][]).
The easiest approach would be to simply craft your <table> inside of your if statement, and craft your table rows inside of your while loop:
<?php
if (mysqli_num_rows($result) > 0)
{
?>
<table>
<thead>
<tr>
<th>DonorID</th>
<th>Donor</th>
<th>gender</th>
<th>bloodgroup</th>
<th>State</th>
</tr>
</thead>
<tbody>
<?php
while($row = mysqli_fetch_assoc($result))
{
echo "<td>" . $row['DonorID'] . "</td>";
echo "<td>" . $row['FullName'] . "</td>";
echo "<td>" . $row['gender'] . "</td>";
echo "<td>" . $row['bloodgroup'] . "</td>";
echo "<td>" . $row['State'] . "</td>";
}
?>
</tbody>
</table>
<?php
}
?>
This way, the table itself only gets generated if there are rows returned from the database, meaning you'll never end up with a table with nothing in it.
You need to add new array in existing $_SESSION element rather than override the previous $_SESSION. Add this code in you while loop. if you want to print multiple records then you have to use foreach loop
$_SESSION['DonorID'][] = $row['DonorID'];
$_SESSION['FullName'][] = $row['FullName'];
$_SESSION['gender'][] = $row['gender'];
$_SESSION['bloodgroup'][] = $row['bloodgroup'];
$_SESSION['State'][] = $row['State'];
For printing multiple records use foreach loop
foreach ( $_SESSION as $row ) {
echo "<td>" . $row['DonorID'] . "</td>";
echo "<td>" . $row['FullName'] . "</td>";
echo "<td>" . $row['gender'] . "</td>";
echo "<td>" . $row['bloodgroup'] . "</td>";
echo "<td>" . $row['State'] . "</td>";
}
EDIT: The problem is due to you never place the session variable with array, hence your output from sql actually kept repeating overwrite inside the variable, that the reason why you able to acquire one result only.
What you can do is declare your session as array before store the data.
$_SESSION['DonorID'] = array();
$_SESSION['FullName'] = array();
$_SESSION['gender'] = array();
$_SESSION['bloodgroup'] = array();
$_SESSION['State'] = array();
Then retrieve your data using index. Make sure add your for new rows.
$counter=0;
$loopcounter=count($_SESSION['DonorID']);
while($counter < $loopcounter)
{
<tr><td><?php echo("{$_SESSION['DonorID'][$counter]}"."<br />");?></td>
.....</td></tr>
$counter++;
}
Reference: store mutiple values in php session
I'm trying to display the values from two different rows into two columns in a single row but I can't figure out how to retrieve the data.
This is what I tried:
SELECT wp_posts.*, wp_postmeta.*
FROM wp_posts
LEFT JOIN wp_postmeta
ON wp_posts.ID = wp_postmeta.post_id
WHERE wp_posts.post_type='product' AND wp_postmeta.meta_key='_sale_price'
OR wp_postmeta.meta_key='_stock'
ORDER BY wp_posts.ID
I display the data like this:
foreach($sth as $row)
{
?>
<tr>
<td><?php echo $row["ID"]; ?></td>
<td><?php echo $row["post_title"]; ?></td>
<td><?php echo $row["meta_value"]; ?></td>
<td><?php echo $row["meta_value"]; ?></td>
</tr>
I'm getting this:
While I'd like to get this:
I'm not sure whether I should post this in the PHP, WP or SQL category.
use this code:
only replace your tables with this example
$sql = "SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
LEFT JOIN Orders
ON Customers.CustomerID=Orders.CustomerID
ORDER BY Customers.CustomerName";
$result = mysqli_query($con, $sql);
while ($row = mysqli_fetch_assoc($result)) {
<tr>
<td><?php echo $row["ID"]; ?></td>
<td><?php echo $row["post_title"]; ?></td>
<td><?php echo $row["meta_value"]; ?></td>
<td><?php echo $row["meta_value"]; ?></td>
</tr>
///your code here
}
It seems that your fetch results are coupled, so I'd suggest that you print the fetch results in the rule below:
/* Print this when $row is in odd number */
<tr>
<td><?php echo $row["ID"]; ?></td>
<td><?php echo $row["post_title"]; ?></td>
<td><?php echo $row["meta_value"]; ?></td>
/* Print this when $row is in even number */
<td><?php echo $row["meta_value"]; ?></td>
</tr>
In the end, according to the sample data you provide above, you will find that the 1st foreach it prints
"#" = '285'
"Nom" = 'Bouquet Opalin'
"Prix HT" = '25'
2nd foreach it prints:
"Stock" = '9'
I did the example for you, click the link below.
For your reference
/* added at 2018-04-26 */
<?php
/* include your dbconfig */
include_once('../sit/dbConfig.php');
$dbConfig = new dbConfig();
$query = array();
$query[0] = "SELECT * FROM wp_posts WHERE 1;";
$column = " ID, post_title, meta_value ";
$table = " wp_posts ";
$arr = array();
$arr = $dbConfig->sqlSelect1($column, $table);
echo "<pre>";
echo "1) Print raw array data which get from DB" . "<br><br>";
print_r( $arr );
echo "</pre>";
echo "<br><br>";
?>
<?php
echo "<pre>";
echo "2) Print in table format" . "<br><br>";
echo "<table border='1' width=device-width >";
echo "<tr>";
echo "<td>#</td>";
echo "<td>Nom</td>";
echo "<td>Prix HT</td>";
echo "<td>Stock</td>";
echo "</tr>";
/* Print this when $row is in even number */
foreach ($arr as $row => $key) {
if ($row % 2 == 0) {
echo "<tr> <td>";
echo $key["ID"];
echo "</td> <td>";
echo $key["post_title"];
echo "</td> <td>";
echo $key["meta_value"];
echo "</td>";
}
/* Print this when $row is in odd number */
if ($row % 2 == 1) {
echo "<td>";
echo $key["meta_value"];
echo "</td> <tr>";
}
}
echo "</table>";
echo "</pre>";
?>
I have tried the same code below on my c# app and it works fine, but when i tried the same code on php with the tweak of instead of column number on c# i replaced it with column name but the result is different.
$sql ="SELECT
`adexposure`.`symbol`,
`adexposure`.`netvolume`,
`fxexposure`.`netvolume`,
`adexposure`.`lastupdate`
FROM `adexposure`
LEFT JOIN `fxexposure` ON `adexposure`.`symbol` = `fxexposure`.`symbol`";
$result = $conn->query($sql);
if($result->num_rows>0)
{
echo "<table>";
echo "<tr>";
echo "<th>Symbol</th>";
echo "<th>Net Volume A</th>";
echo "<th>Net Volume B</th>";
echo "<th>Last Update</th>";
echo "</tr>";
while($row = $result->fetch_assoc())
{
echo "<tr>";
echo "<td>" .$row["symbol"]."</td>";
echo "<td>" .$row["netvolume"]."</td>";
echo "<td>" .$row["netvolume"]."</td>";
echo "<td>" .$row["lastupdate"]."</td>";
echo "</tr>";
}
echo "</table>";
}
else
{
echo "0 results";
}
Result should be:
<table border=1>
<tr>
<th>Symbol</th>
<th>Net Volume A</th>
<th>Net Volume B</th>
<th>Last Update</th>
</th>
</tr>
<tr>
<td>BITCOIN</td>
<td>2.5</td>
<td>3.5</td>
<td>2018.02.05 10:44</td>
</tr>
<tr>
<td>LITECOIN</td>
<td>1.5</td>
<td>5.5</td>
<td>2018.02.05 10:44</td>
</tr>
<tr>
<td>HASHCOIN</td>
<td>0.5</td>
<td>0.5</td>
<td>2018.02.05 10:44</td>
</tr>
</table>
but thats not the case.
The result shows both net volume of fxexposure.netvolume.
I hope you can help me with this.
Thanks...
just a suggestion you have two time netvolumn so you should use alias
sql ="SELECT
`adexposure`.`symbol`,
`adexposure`.`netvolume`,
`fxexposure`.`netvolume` as netvolume2,
`adexposure`.`lastupdate`
FROM `adexposure`
LEFT JOIN `fxexposure` ON `adexposure`.`symbol` = `fxexposure`.`symbol`";
while($row = $result->fetch_assoc())
{
echo "<tr>";
echo "<td>" .$row["symbol"]."</td>";
echo "<td>" .$row["netvolume"]."</td>";
echo "<td>" .$row["netvolume2"]."</td>";
echo "<td>" .$row["lastupdate"]."</td>";
echo "</tr>";
}
If you assign an alias to the returned colums you can address them correctly in the php
$sql ="SELECT
`adexposure`.`symbol`,
`adexposure`.`netvolume` as `netvolume_A`, /* ALIAS */
`fxexposure`.`netvolume` as `netvolume_B`,
`adexposure`.`lastupdate`
FROM `adexposure`
LEFT JOIN `fxexposure` ON `adexposure`.`symbol` = `fxexposure`.`symbol`";
$result = $conn->query($sql);
if($result->num_rows>0)
{
echo "<table>";
echo "<tr>";
echo "<th>Symbol</th>";
echo "<th>Net Volume A</th>";
echo "<th>Net Volume B</th>";
echo "<th>Last Update</th>";
echo "</tr>";
while($row = $result->fetch_assoc())
{
echo "<tr>";
echo "<td>" .$row["symbol"]."</td>";
echo "<td>" .$row["netvolume_A"]."</td>";<!-- /* ALIAS */ -->
echo "<td>" .$row["netvolume_B"]."</td>";
echo "<td>" .$row["lastupdate"]."</td>";
echo "</tr>";
}
echo "</table>";
}
else
{
echo "0 results";
}
Read these two lines carefully:
echo "<td>" .$row["netvolume"]."</td>";
echo "<td>" .$row["netvolume"]."</td>";
You are using the same name to mean two different things, so there is no way for PHP to give a different result on those lines.
The solution is to give the values unique column aliases in your SQL:
`adexposure`.`netvolume` as netvolume_as,
`fxexposure`.`netvolume` as netvolume_fx,
And then those are the names in your PHP:
echo "<td>" .$row["netvolume_as"]."</td>";
echo "<td>" .$row["netvolume_fx"]."</td>";
Here is my code. I am fairly new to PHP and mySQL. I'm having a hard time figuring out why my fetch is returning the string "Array". Also, is there a better way to write all of the echo statements? What's proper php coding rules?
while($row = mysql_fetch_array($question))
{
$answerID = $row['intQAID'];
$getAnswer = mysql_query("SELECT cBody FROM tblQA WHERE intResponseID = $answerID AND intPosterID = '17'");
$answerBody = mysql_fetch_array($getAnswer);
echo "<tr class='forum'>";
echo "<td class='forum'>" . $row['intQAID'] . "</td>";
echo "<td class='forum'>" . substr($row['cBody'], 0, 150) . "</td>";
echo "<td class='forum'>" . $row['cCategory'] . "</td>";
echo "<td class='forum'>" . $row['username'] . "</td>";
echo "<td class='forum'>" . $row['post_time'] . "</td>";
echo "</tr>";
echo "<tr class='forum'>";
echo "<td class='forum'></td>";
echo "<td class='forum'>$answerBody</td>";
echo "<td class='forum'></td>";
echo "<td class='forum'></td>";
echo "<td class='forum'></td>";
}
echo "</table></div></div>";
It is returning Array because mysql_fetch_array is supposed to return an array. This is specified in the documentation and the name of the function!
Because it returns an array, it will still return one even if that array only has one item in it.
Your syntax is wrong. The mysql_fetch_array returns an array by default. If you try echo an array PHP outputs "Array". There are a lot of good examples in the PHP manual on the command.
The heredoc format is great for echoing large blocks. Alternatively you could end your php block and just start it again when needed (which is probably what I would do in this situation).
<?php
// lots of PHP statements
?>
<table>
....
<td><?php echo $variable; ?></td>
....
<?php
// resume php
?>
Some people use short tags in their code for echo. I personally don't although it's a matter of personal preference. The new versions of PHP have them enabled by default but older server installations may not support them.
Try this
<?php
$query = mysql_query("SELECT cBody FROM tblQA WHERE intResponseID = $answerID AND intPosterID = '17'");
while($row = mysql_fetch_assoc($query)):
?>
<tr>
<td><?php echo $row['field_name']; ?></td>
<td><?php echo $row['field_name']; ?></td>
<td><?php echo $row['field_name']; ?></td>
<td><?php echo $row['field_name']; ?></td>
<!-- and so on -->
</tr>
<?php endwhile; ?>