Happy new yar. I am still new to php so I need your great help. I am designing a post page where visitors can post anything. I am almost through but when I post something to the page, the new post over ride the old one, I am certain I need to use foreach loop but my problem I can't define the $posting variable.
My bad, but I really need you guys to help me. here is my coding:
<?php
include 'connect.php';
?>
<?php
if (isset($_POST['submit'])) {
$title = $_POST['title'];
$post = $_POST['post'];
$name = $_POST['name'];
if (empty($title) or empty($post) or empty($name)) {
$message = "Please fill in all fields";
} else {
mysql_query("INSERT INTO prayer VALUES('', '" . $title . "', '" . $post . "', '" . $name . "')");
$message = "PRAYER REQUEST SUBMITTED!!!";
}
echo"$message";
}
?>
<form method="post" action="prayerpage.php">
<table width="80%">
<tr>
<td><b>Name:</b><input type="text" name="name" />
<b>Title:</b><input type="text" name="title" /></td>
</tr>
<tr>
<td><b>Prayer<br>Request:</b></td>
<td><textarea name='post' rows='10' cols='40'></textarea></td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="submit" value="SUMIT"/></td>
</tr>
</table>
</form>
<hr width="70%">
<?php
function postid($id) {
$array = array();
$q = mysql_query("SLECT * FROM prayer WHERE id='.$id.'");
while ($r = mysql_fetch_assoc($q)) {
$array['id'] = $r['id'];
$array['title'] = $r['title'];
$array['name'] = $r['name'];
$array['post'] = $r['post'];
}
return $array;
}
foreach ($posting as $posting) {
?>
<table width="60%">
<tr>
<td><font color="blue"><?php echo $title; ?></font></td>
</tr>
<tr>
<td><?php echo $post; ?> - <font color="blue"><?php echo $name; ?></font> </td>
</tr>
</table>
<hr noshade width="50%">
<?php
}
?>
And please i also need the code to make the post a link to its page
check your id is auto increment or not if not then make it autoincrement
then try to change this code in your page :
mysql_query("INSERT INTO prayer VALUES('', '".$title."', '".$post."', '".$name."')");
to
mysql_query("INSERT INTO prayer VALUES('".$title."', '".$post."', '".$name."')");
There are a couple problems with your code. The first is that you mysql_query when you should be using mysqli_query, same mysql_fetch_assoc, should be mysqli_fetch_assoc -- please replace all references of mysql_* with mysqli_*. The second is you are running a query inside of a function. The third problem is your query is wrong. And... you do not need a foreach in the way you are using it.
function postid($id) {
global $db;
$array = array();
$id = (int)$id; // cast as int to prevent SQL injection
$q = mysqli_query($db, "SELECT * FROM prayer WHERE id=$id");
while ($r = mysqli_fetch_assoc($q)) {
$array['id'] = $r['id'];
$array['title'] = $r['title'];
$array['name'] = $r['name'];
$array['post'] = $r['post'];
}
return $array;
}
You had a typo, it should be SELECT not SLECT. You do need to concatenate variables when you are inside of a double quoted string. I would link to the PHP documentation about it but is not super clear. Basically the following lines all result in the same output:
$amazing = "neato!";
$example1 = "This is my variable: $amazing"; // Output: This is my variable: neato!
$example2 = 'This is my variable: ' . $amazing; // Output: This is my variable: neato!
$example3 = "This is my variable: " . $amazing; // Output: This is my variable: neato!
Notice how you can put a variable inside of a string with double quotes. But you cannot do this:
$doesNotWork = 'This is my variable: $amazing'; // Output: This is my variable: $amazing
$doesNotWork = "This is my variable: '.$amazing.'"; // Output: This is my variable: '.$amazing.'
The reason you should use mysqli_query is because mysql_query is no longer supported. Inside of your function you will need to use the special keyword global to get the variable of your database connection (I set it to $db in the example but you might have it called something else).
Basically, global is a PHP keyword that will allow you to access variables that have been defined in the global scope. Read about in the documentation by clicking here
[..] within user-defined functions a local function scope is introduced. Any variable used inside a function is by default limited to the local function scope.
Lastly.. you do not have the variable $posting defined correctly.
You can fix this by getting rid of your call to foreach, replace this line:
foreach ($posting as $posting) {
With these 2 lines:
$q = mysqli_query($db, "SELECT * FROM prayer");
while ($posting = mysqli_fetch_assoc($q)) {
Your $posting variable is undefined, when it looks like you actually just want to query the database and get all the rows from the prayer table.
This query will give you warnings in MYSQL but execute due to PK auto increment:
mysql_query("INSERT INTO prayer
VALUES('', '" . $title . "', '" . $post . "', '" . $name . "')");
Solution is that define column names in this query and if your id is PK than not use because its auto increment:
mysql_query("INSERT INTO prayer (title,post,name)
VALUES('".$title."','".$post."','".$name."')");
Related
I get an error like this;
Notice: Undefined offset: 0 on line 93
My php code is look like this below code..
$i=0;
while ($ww=mysqli_fetch_array($query))
{
if ($i%2==0)
$class="evenRow";
else
$class="oddRow";
$id=$ww[0];
$studentid=$ww[1];
$name=$ww[2];
$kelompok=$ww[8];
$block=$ww[9];
$level=$ww[10];
$house=$ww[11];
$status=$ww[14];
echo "<tr>
<input type=hidden name=applyid[] value=".$id."/>
<td>$studentid</td>
<td>$name</td>
<td>$kelompok</td>
<td>$block</a></td>
<td>$level</td>
<td>$house</td>
<td>
<input type=checkbox name=status approved checked> APPROVED <br>
</td>
</tr>";
}
$i++;
echo "</table>";
This is the error on line 93: $checkbox[] .= $_POST['applyid'][$i];}
And the SQL Query to update the status is look like this...
<?php
include("connection.php");
$checkbox = array();
if(isset($_POST['applyid']))
{
$check = count($_POST['applyid']);
for($i=0;$i<$check;$i++){
$checkbox[] .= $_POST['applyid'][$i];}
$check = "('" . implode( "','", $checkbox ) . "');" ;
$sql="UPDATE application SET apply_status = 'APPROVED' WHERE apply_id IN $check" ;
$result = mysqli_query($con, $sql) or die(mysqli_error($con));
}
?>
I want to update multiple row selected by checkbox. This is the table output
Click Here
..............................................................................
VIEW THE PENDING STATUS:
This is my code if only the apply_status = 'PENDING' will only view.
I add the if else statement... but is not working. if there is several apply_status = approved. It will not showed the pending one. But if there is no apply_status = aprroved. It will view all the application.
<?php
include("connection.php");
$sql="SELECT * FROM application";
$record = mysqli_query($con, $sql) or die ("error".mysqli_error($con));
$apply = mysqli_fetch_assoc($record);
$status1 = $apply["apply_status"];
if ($status1 == "APPROVED") {
echo "<br>";
echo "No application from student yet.<br>";
echo "<br>";
} else {
echo "<table border='1'><tr>
<td><strong>Student ID</strong></td>
<td><strong>Student Name</strong></td>
<td><strong>Kelompok</strong></td>
<td><strong>Block</strong></td>
<td><strong>Level</strong></td>
<td><strong>House</strong></td>
<td><strong>Status</strong></td>
</tr>";
$i=0;
while ($ww=mysqli_fetch_array($query))
{
if ($i%2==0)
$class="evenRow";
else
$class="oddRow";
$id=$ww[0];
$studentid=$ww[1];
$name=$ww[2];
$kelompok=$ww[8];
$block=$ww[9];
$level=$ww[10];
$house=$ww[11];
$status=$ww[14];
echo '<tr>
<input type="hidden" name="applyid['.$i.']" value="'.$id.'"/>
<td>'.$studentid.'</td>
<td>'.$name.'</td>
<td>'.$kelompok.'</td>
<td>'.$block.'</a></td>
<td>'.$level.'</td>
<td>'.$house.'</td>
<td>
<input type="checkbox" name="status['.$i.']" value="approved" checked> APPROVED <br>
</td>
</tr>';
$i++;
}
echo '</table>';
}
?>
Try changing :
$check = count($_POST['applyid']);
for($i=0;$i<$check;$i++){
$checkbox[] .= $_POST['applyid'][$i];
}
TO
foreach($_POST['applyid'] as $index=>$idValue){
$checkbox[] .= $idValue;
}
EDIT :
use the index of the loop to index the input's so that you can associate them with each other in the receiving page :
$i = 0; // $i used to determain if it is odd or even, also used as the index in the html inputs
// comments are your friend
while ($ww=mysqli_fetch_array($query))
{
if ($i%2==0){ // best practice for readable code is to use the braces
$class="evenRow";
}
else{
$class="oddRow";
}
// easier to read when spaced equally
$id = $ww[0];
$studentid = $ww[1];
$name = $ww[2];
$kelompok = $ww[8];
$block = $ww[9];
$level = $ww[10];
$house = $ww[11];
$status = $ww[14];
// single quotes are faster to proccess in PHP
// use $i to force the array index
// place quotation marks arrount html attribute values
echo '<tr>
<input type="hidden" name="applyid['.$i.']" value="'.$id.'"/>
<td>'.$studentid.'</td>
<td>'.$name.'</td>
<td>'.$kelompok.'</td>
<td>'.$block.'</td> <!-- removed a closing "a" tag, as it wasn\'t closeing anything -->
<td>'.$level.'</td>
<td>'.$house.'</td>
<td>
<input type="checkbox" name="status['.$i.']" value="approved" checked> APPROVED <br>
</td>
</tr>';
$i++; // increment $i inside the loop, else it will never change until the loop is completed
}
// single quotes are faster to proccess in PHP
echo '</table>';
On the recieving page, use this,
include("connection.php");
if(isset($_POST['applyid']))
{
$allIDs = ''; // using this in the single SQL query, remove it if you not going to use it
$approvedIds = ''; // we will add all the approved Ids here for using in the SQL query
$unapprovedIds = ''; // we will add all the un-approved Ids here for using in the SQL query
// if the single SQL query works, remove the $unapprovedIds
foreach($_POST['applyid'] as $index=>$idValue){
if(isset($_POST['status'][$index])){ // if the status for this ID was posted, it was selected ( ony selected checkboxes get posted )
$approvedIds .= ($approvedIds === '' ? '' : ', ').$idValue; // we add it to the string that will be used in the "IN"
// if $approvedIds is not blank, add a comma to format corrctly for SQL
}else{ // if the single SQL query works, remove this entire else
$unapprovedIds .= ($unapprovedIds === '' ? '' : ', ').$idValue; // we add it to the string that will be used in the "IN"
// if $unapprovedIds is not blank, add a comma to format corrctly for SQL
}
$allIDs .= ($allIDs === '' ? '' : ', ').$idValue; // using this in the single SQL query, remove it if you not going to use it
}
// update all the approved ones
// single quotes
// format you SQL in a easy to read way
$sql = 'UPDATE application
SET apply_status = \'APPROVED\'
WHERE apply_id IN ('.$approvedIds.')' ;
$result = mysqli_query($con, $sql) or die(mysqli_error($con));
// update all the unaproved ones
// format you SQL in a easy to read way
$sql = 'UPDATE application
SET apply_status = \'UNAPROVED\'
WHERE apply_id IN ('.$unapprovedIds.')' ;
$result = mysqli_query($con, $sql) or die(mysqli_error($con));
/////////////////
//
// worth a try as a single query UNTESTED :
//
//////////////////////////////////////////////
$sql='UPDATE application
SET apply_status =
CASE WHEN apply_id IN ('.$approvedIds.') THEN \'APPROVED\'
ELSE \'UNAPPROVED\'
END
WHERE apply_id IN ('.$allIDs.')';
}
I have added some basic guidelines for you so that you can apply them going forward
Here is some of my code for my checkout page. I am new to php, this is my first semester, and I am still struggling. This page collects orders added to the cart and displays and totals the orders perfectly. Here is my problem.
Sometimes there will be OrderIn products and there can be none or more than one of these, and there can also be OrderOut products, or none. complicated, I know. I may be trying to do too much. When I press the pay this invoice button, I want to collect the Order ID's, no matter how many or what kind, (out or in) and set the order ID Paid to yes, and insert the OrderId's into the appropriate invoice, invoice_in or invoice_out, and set shipped to NO.
Is this possible, it is changing the OrderId_in, first product only to yes, and now I am getting a MySQL error of "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '75.18', 'No')' at line 2". I could use some direction here please.
<div class="tablecheckOut">
<form action='checkout.php' method='post'>
<p><strong>Purchases this invoice: </strong><br><br>
<?php
echo "<table class='middlecheckOut'>
<tr>
<td class='td2'><b>Order ID: </b></td>
<td class='td2'><b>Product Name: </b></td>
<td class='td2'><b>Quantity: </b></td>
<td class='td2'><b>Price: </b></td>
</tr>";
if (isset($_GET['user_id'])) {
$user_id = $_GET['user_id'];
} elseif (isset($_POST['user_id'])) {
$user_id = $_POST['user_id'];
}
$display="SELECT *
FROM order_instate JOIN in_Product ON
order_instate.ip_id = in_product.ip_id
WHERE user_id = '$user_id'; " ;
$displayResult = #mysqli_query($dbhandle, $display)
or die(mysqli_error($dbhandle));
$priceIn = 0;
while($row = mysqli_fetch_array($displayResult, MYSQLI_ASSOC)) {
if($row['orderIn_paid'] == "No") {
echo "<tr>
<input type='hidden' name='ip_id' value='" . $row['ip_id'] . "' />
<td class='td2'>" . $row['orderIn_id'] . "   </td>
<td class='td2'>" . $row['ip_name'] . "   </td>
<td class='td2'>" . $row['orderIn_quantity'] . "   </td>
<td class='td2'>$" . $row['orderIn_total'] . "   </td>
</tr>";
$priceIn += $row['orderIn_total'];
$orderIn_id = $row['orderIn_id'];
$_SESSION['orderIn'] = $orderIn_id;
}
}
if (isset($_GET['user_id'])) {
$user_id = $_GET['user_id'];
} elseif (isset($_POST['user_id'])) {
$user_id = $_POST['user_id'];
}
$display2="SELECT *
FROM order_outstate JOIN op_Product ON
order_outstate.op_id = op_product.op_id
WHERE user_id = '$user_id'; " ;
$displayResult2 = #mysqli_query($dbhandle, $display2)
or die(mysqli_error($dbhandle));
$priceOut = 0;
while($row2 = mysqli_fetch_array($displayResult2, MYSQLI_ASSOC)) {
if($row2['orderOut_paid'] == "No") {
echo "<tr>
<input type='hidden' name='op_id' value='" . $row2['op_id'] . "' />
<td class='td2'>" . $row2['orderOut_id'] . "   </td>
<td class='td2'>" . $row2['op_name'] . "   </td>
<td class='td2'>" . $row2['orderOut_quantity'] . "   </td>
<td class='td2'>$" . $row2['orderOut_total'] . "   </td>
</tr>";
$priceOut += $row2['orderOut_total'];
$orderOut_id = $row['orderOut_id'];
$_SESSION['orderOut'] = $orderOut_id;
}
}
echo "</table>";
$subtotal = 0;
$tax = 0;
$gtotal = 0;
$subtotal = number_format($priceIn + $priceOut, 2);
$tax = number_format($subtotal * .074, 2);
$gtotal = number_format($subtotal + $tax, 2);
?>
</p>
<p><strong>Total Amount of Purchase(s): <?php echo "$" . " $subtotal " ?></strong></p>
<p><strong>Tax this invoice (7.4%): <?php echo "$" . " $tax " ?> </strong></p>
<p><strong>Grand Total of Invoice: <?php echo "$" . " $gtotal " ?> </strong></p>
<p>
<input type="submit" name="submit" value="Pay This Invoice" style="width: 162px; height: 37px" >
<input type="button" name="print" value="Print This Invoice" style="width:162px; height: 37px" onclick="window.print()">
</p>
</form>
</div>
</body>
</html>
<?php
if($_SERVER['METHOD'] == 'POST') {
if(isset($_SESSION['orderIn'])) {
$orderIn_id = $_SESSION['orderIn'];
$orderIn_paid = "Yes";
$changeVal="UPDATE order_instate
SET orderIn_paid = '$orderIn_paid'
WHERE orderIn_id = '$orderIn_id'; " ;
$changeCheck=mysqli_query($dbhandle, $changeVal)
or die(mysqli_error($dbhandle));
}
if(isset($_SESSION['orderOut'])) {
$orderOut_id = $_SESSION['orderOut'];
$orderOut_paid = "Yes";
$changeVal2="UPDATE order_outstate
SET orderOut_paid = '$orderOut_paid'
WHERE orderOut_id = '$orderOut_id'; " ;
$changeCheck2=mysqli_query($dbhandle, $changeVal2)
or die(mysqli_error($dbhandle));
}
$invoiceIn_total = 0;
$invoiceIn_total = $gtotal;
$invoiceIn_shipped = "No";
$add ="INSERT INTO invoice_in(user_id, orderIn_id, invoiceIn_total, invoiceIn_shipped)
VALUES ('$user_id', '$orderIn_id '$invoiceIn_total', '$invoiceIn_shipped')";
$addCheck=mysqli_query($dbhandle, $add)
or die(mysqli_error($dbhandle));
$invoiceOut_total = 0;
$invoiceOut_total = $gtotal;
$invoiceOut_shipped = "No";
$add2 ="INSERT INTO invoice_out(user_id, orderOut_id, invoiceOut_total, invoiceOut_shipped)
VALUES ('$user_id', '$orderOut_total '$invoiceOut_total', '$invoiceOut_shipped')";
$addCheck2=mysqli_query($dbhandle, $add2)
or die(mysqli_error($dbhandle));
header("location: userOrders.php");
}
?>
There are a few things wrong with your code.
There's
VALUES ('$user_id', '$orderIn_id '$invoiceIn_total',
^^
is missing a quote and a comma
do
VALUES ('$user_id', '$orderIn_id', '$invoiceIn_total',
same thing for
VALUES ('$user_id', '$orderOut_total '$invoiceOut_total',
^^
do
VALUES ('$user_id', '$orderOut_total', '$invoiceOut_total',
which are where the SQL errors come from.
$orderOut_total is undefined in your posted code.
Plus, from a comment you made:
"Fred, I found why my OrderOut_id was not getting populated, I found a syntax error, I was creating and defining the variable without using the correct $row2 to grab it. It now works for both OrderIn and OrderOut, although I have not tested for multiple orders. But I am getting it working, thanks to you Fred, that worked in finding my exact syntax error."
Which came to be the final solution to the problem.
I must note that your present code is open to SQL injection. Use prepared statements, or PDO with prepared statements, they're much safer.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Error reporting should only be done in staging, and never production.
I'm using a rather long HTML form to update lots of details relating to a product - for brevity I won't share the form in its entirety. However, for illustrative purposes here's a snippet :
HTML FORM
<form name="form1" method="post" action="update_ac.php">
<table width="100%" cellpadding="0" cellspacing="0">
<tr>
<td>
<input name="season" type="text" class="button_select" id="season" value="<?=$rows['season']; ?>" size="10" />
<input name="restock" type="checkbox" id="restock" value="on" <?php if($rows['restock']=='on') { echo 'checked="checked"'; } ?>/>
// other fields
</td>
</tr>
</table>
</form>
My question is when posting the form to update_ac.php - how can I dynamically generate a MYSQL update statement based on the fields that are completed?
Here's an example of my form action page:
PHP FORM Action
<?php
foreach ($_POST as $key => $value) {
$$key = $value;
}
$sql= mysql_query ("
UPDATE product SET
title='".$title."',
rating='".$rating."',
season='".$season."',
brand_id='".$brand_id."',
category='".$category."',
... etc ");
?>
I don't want to have to declare every single field that could possibly need updating in the UPDATE statement. I would like the UPDATE statement to only address the fields concerned given the presence of defined PHP variables posted from the form.
At the moment, I'm getting lots of NOTICE: Undefined variable x where there have been empty fields when posting the form.
I hope this makes sense - little long winded.
Any advice? Thanks
UPDATE
Following on from #Styphon's answer - I amended it slightly to include the WHERE condition at the end of the query.
$query = "UPDATE product SET";
$comma = " ";
foreach($_POST as $key => $val) {
if( ! empty($val)) {
$query .= $comma . $key . " = '" . mysql_real_escape_string(trim($val)) . "'";
$comma = ", ";
}
}
$product_id = $_POST['product_id'];
$query = $query . "WHERE product_id = '".$product_id."' ";
Assuming that all the field names in the table are the same as the names of your form inputs this is straight forward. You can use this:
$query = "UPDATE product SET";
$comma = " ";
foreach($_POST as $key => $val) {
if( ! empty($val)) {
$query .= $comma . $key . " = '" . mysql_real_escape_string(trim($val)) . "'";
$comma = ", ";
}
}
$sql = mysql_query($query);
To be more secure you should create a whitelist of accepted parameters, i.e. the columns in your table like this:
$query = "UPDATE product SET";
$comma = " ";
$whitelist = array(
'title',
'rating',
'season',
'brand_id',
'cateogry',
// ...etc
);
foreach($_POST as $key => $val) {
if( ! empty($val) && in_array($key, $whitelist)) {
$query .= $comma . $key . " = '" . mysql_real_escape_string(trim($val)) . "'";
$comma = ", ";
}
}
$sql = mysql_query($query);
That way your query can only contain parameters you set, and if anyone manages to inject extras (by changing the names of your form inputs for example) it wont be passed to your database.
I'd also recommend you stop using Mysql_*, it's deprecated. You should look at MySQLi or PDO as alternatives.
I'm developing a comments system. Right now it is very simple. But I am a bit stuck.
I have a set off rooms that you can book. And for each of the rooms, you can submit comments to them.
When I click my to acess the comments of a room, I sent the room id with the URL, as you can see by the following code:
if (isset ( $_GET ['id'] )) {
$room_id = $_GET ['id'];
}
$user_id = $_SESSION ['id'];
if ($_POST){
extract($_POST);
$register = $comment->createComment($room_id, $user_id, $comments);
}
?>
<div id="comments">
<?php echo $comment->getComments($room_id); ?>
</div>
<div id="comment-form">
<h3>New Comment</h3>
<form action="" method="post">
<table>
<tr>
<td><textarea name="comments" cols="40" rows="8"></textarea></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="submit" value="Submit Comment" /></td>
</tr>
</table>
</form>
</div>
To get my comments I call my function getComments($room_id)
public function getComments($room_id) {
$str = "SELECT * FROM comments WHERE room_id = $room_id";
$result = $this->db->mysqli->query ($str);
if ($result->num_rows > 0) {
$string = "<table><thead><tr><th>#ID</th><th>Room id</th><th>user id</th><th>comments</th><th>Timestamp</th></tr></thead><tbody>";
while ( $row = $result->fetch_assoc () ) {
$string .= "<tr><td>" . $row ['id'] .
"</td><td>" . $row ['room_id'] .
"</td><td>" . $row ['user_id'] .
"</td><td>" . $row ['comments'] .
"</td><td>" . $row ['timestamp'] .
"</td><td>[<a href='deleteComment.php?id=" . $row ['id'] . "'>Delete</a>]</td> ";
}
$string .= "</tbody></table>";
return $string;
}
}
As you can see I create a link that goes to deleteComment.php and sent the link of the comment that I want to delete with it.
On that page I call a new function:
if ($comment->deleteComment($_GET['id']))
{
echo "comment deleted"
}
else
{
echo "Something went wrong.s";
}
And finally, my delete comment function:
public function deleteComment($id)
{
$sql = "DELETE FROM comments WHERE id = ?";
if (!$result = $this->db->mysqli->prepare($sql))
{
return false;
}
if (!$result->bind_param('i', $id))
{
return false;
}
return $result->execute();
}
All of this is working. But my question is: How can I delete the comments and still stay on the original page that displays the comments, and not go to the deleteComments.php page? I'm not looking for an AJAX solution. It would be nice if I could just stick to PHP.
As Rakesh suggested, you can use the header() function in your deleteComment function or you can just link to the same page but with comment id to be deleted
instead of:
href='deleteComment.php?id=" . $row ['id'] . "'>
do:
href='?id=" . $row ['delete_comment_id'] . "'>
and delete the comment before creating the list of comments
Just link the delete "button" to the normal comments page with a seperate delete GET or POST value (instead of id), then at the beginning of your comments page if it is set.
Eg: yourpage.com/comments.php?delete=14
if (isset($_GET['delete']))
{
$comment->deleteComment($_GET['delete']);
}
BUT(!) really be aware, the way you are doing it, allows for any user to delete any comment by entering its id, this is not safe!
I would like to have the freedom to place a row entry from my database wherever i' prefer in the page. Right now, the php code that I use is as follows (it is clean working code):
<html><head></head>
<body>
<?php
$db = mysql_connect("xxx","xxx","xxx") or die("Database Error");
mysql_select_db("caisafety",$db);
$id = $_GET['id'];
$id = mysql_real_escape_string($id);
$query = "SELECT * FROM `cert_rr` WHERE `id`='" . $id . "'";
$result = mysql_query($query);
echo $row['id']; while($row = mysql_fetch_array( $result )) {
echo "<br><br>";
echo $row['basic3'];
echo $row['basic2'];
echo $row['basic1'];
}
?>
</body>
</html>
I call id through the browser Eg. http://site.com/getid.php?id=10 . But I do not have the freedom to place my row entry within my html. For eg. like this:
<table><tr>
<td align="center">BASIC INFO 1: <?php echo $row['basic1']; ?></td>
<td align="center">BASIC INFO 2: <?php echo $row['basic2']; ?></td>
</tr></table>
I can place html within echo PHP tags but then I have to clean up my html and thats a lot of work. Retaining HTML formatting would be preferred. Any help or guidelines on this would be much appreciated.
<?php
$db = mysql_connect("xxx","xxx","xxx") or die("Database Error");
mysql_select_db("caisafety",$db);
$id = $_GET['id'];
$id = mysql_real_escape_string($id);
$query = "SELECT * FROM `cert_rr` WHERE `id`='" . $id . "'";
$result = mysql_query($query);
//you need to retrieve every row and save to an array for later access
for($rows = array(); $tmp = mysql_fetch_array($result);)
{
$rows[] = $tmp;
}
//now you can use the $rows array where every you want e.g. with the code from Zhube
?>
....
<table><?php foreach($rows as $r):
<td><?php echo $r['id'] ?></td><?php endforeach ?>
</table>
By
while($row = mysql_fetch_array( $result )) {
echo "<br><br>";
echo $row['basic3'];
echo $row['basic2'];
echo $row['basic1'];
}
you save only the last row
Instead of having your HTML tags as part of the PHP variable, do something like this instead:
<table><?php foreach($row as $r):?>
<td><?php echo $r['id'] ?></td><?php endforeach ?>
</table>