As stated here, the required attribute in HTML5 doesn't work in Safari. I have PHP that checks if the required fields are filled out. When the user submits the form (a contact-us type form), the action="" is set to the same page, so that the PHP runs. It sends the email with the information and redirects to the home page (which I tell users at the bottom of the page).
However, I heard about people being able to change the HTML of the page and not require fields. While the form is just a contact form and there's no reason for anyone to go through the trouble of modifying the code, I'm relatively new to web development and programming, and I'd like to know how to prevent this kind of stuff if I was to work on projects in the future where I'd need this much security.
So, anyway, the PHP successfully does not send the email if the required information isn't filled out, but if it isn't filled out, it redirects to the home page anyway. How would I use PHP to stay on the same page after the required information isn't there? I know I can use JavaScript, and I probably will in addition to PHP, but since they can have that turned off, it's not totally secure. Again, I know that my situation doesn't require this much security, but it's good practice for a beginner in my opinion. Here's what I have so far:
<?php
if (isset($_POST['email']) && isset($_POST['address']) && isset($_POST['floors'])) {
$name = $_POST['name'];
$lotSize = $_POST['lotSize'];
$lotSize2 = $_POST['lotSize2'];
$age = $_POST['age'];
$taxes = $_POST['taxes'];
$notes = $_POST['notes'];
$email = $_POST['email'];
$address = $_POST['address'];
$floors = $_POST['floors'];
$bedrooms = $_POST['bedrooms'];
$bathroomsFull = $_POST['bathroomsFull'];
$bathroomsHalf = $_POST['bathroomsHalf'];
if (isset($_POST['basement'])) {
$basement = "Yes";
} else {
$basement = "No";
}
if (!(empty($email) && empty($address) && empty($floors) && is_numeric($floors))) {
if ((strlen($name) < 101) && (strlen($email) < 255) && (strlen($address) < 51) && (strlen($lotSize) < 8) && (strlen($floors) < 4) && (strlen($age) < 4) && (strlen($taxes) < 8) && (strlen($notes) < 481)) {
$message = "You have received information about a listing!<hr/><br/>
<table style='border:1px solid black;padding:3px'>
<tr style='padding:5px'><td><strong>Name:</strong></td><td>" . $name . "</td></tr>
<tr style='padding:5px'><td><strong>Email:</strong></td><td>" . $email . "</td></tr>
<tr style='padding:5px'><td><strong>Address:</strong></td><td>" . $address . "</td></tr>
<tr style='padding:5px'><td><strong>Lot size:</strong></td><td>" . $lotSize . " × " . $lotSize2 . " sq. ft. (" . ($lotSize*$lotSize2) . " sq. ft.)</td></tr>
<tr style='padding:5px'><td><strong>Floors:</strong></td><td>" . $floors . "</td></tr>
<tr style='padding:5px'><td><strong>Bedrooms:</strong></td><td>" . $bedrooms . "</td></tr>
<tr style='padding:5px'><td><strong>Full Baths:</strong></td><td>" . $bathroomsFull . "</td></tr>
<tr style='padding:5px'><td><strong>Half Baths:</strong></td><td>" . $bathroomsHalf . "</td></tr>
<tr style='padding:5px'><td><strong>House Age:</strong></td><td>" . $age . " years</td></tr>
<tr style='padding:5px'><td><strong>Taxes:</strong></td><td>$" . $taxes . " / Yr.</td></tr>
<tr style='padding:5px'><td><strong>Basement:</strong></td><td>" . $basement . "</td></tr>
<tr style='padding:5px'><td><strong>Notes:</strong></td><td>" . $notes . "</td></tr>";
mail("****#****", "Listing Inquiry", $message, "Content-Type: text/html; charset=ISO-8859-1\r\n");
header('Location: sellRedirect.php');
}
}
}
?>
Thanks!
To check if the field has been sent, you should use isset() function.
For example:
if(isset($_POST['name'])) {
// The field has been sent
} else {
die('Something is wrong!');
}
Related
I've set up JavaScript and AJAX that's supposed to fetch data from a database subject to a set of filters, and return a table of results that match those filters. I thought I had the code set up correctly, but when I submit the search filter form, the page reloads and nothing else happens. I can't work out where I'm going wrong!
connection.php is just a file containing my database details/username/password, and I know that's working correctly. I've scoured through for syntax errors and can't find any, so it must be something to do with the way I've written my code. However, I'm very new to all this so am really struggling to see what exactly I've done wrong. Any help would be hugely appreciated!
my javascript:
function showStock(search, genre, publisher, minyear, maxyear) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("results").innerHTML = this.responseText;
}
xmlhttp.open("GET", "stock.php?search=" + search + "&genre=" + genre + "&publisher=" + publisher +
"&min-year=" + min - year + "&max-year=" + max - year, true);
xmlhttp.send();
}
}
my filter form:
<form id="filters">
<label> Search by Title:</label><br>
<input type="search" name="search">
<label>Genre:</label><br>
<select name='genre'>
<option value='All'> All </option>
<?php
function dropdownOptions($category) {
require('connection.php');
$sql = "SELECT DISTINCT ".$category." FROM stock";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
echo "<option value='" . $row[$category] . "'>" . $row[$category] . "</option>";
}
}
dropdownOptions("genre");
?>
</select>
<label>Publisher:</label><br>
<select name="publisher">
<option value="all"> All</option>
<?php
dropdownOptions("publisher");
?>
</select>
<div class="year">
<label>Release Year:</label><br>
<input type="number" name="min-year" min="1970" max="2018">
<label> to </label>
<input type="number" name="max-year" min="1970" max="2018">
</div>
<div class="buttons">
<button type="submit" onclick="showStock(search, genre, publisher, min-year, max-year)">SEARCH</button>
<button type="reset">CLEAR</button>
</div>
</form>
my stock.php code:
<?php
require('connection.php');
$search = $_GET['search'];
$publisher = $_GET['publisher'];
$genre = $_GET['genre'];
$minyear = intval($_GET['min-year']);
$maxyear = intval($_GET['max-year']);
if ($search == "") {
$searchQ = "";
} else {
$searchQ = "AND CONTAINS(title, $title) ";
}
if ($genre == "all") {
$genreQ = "";
} else {
$genreQ = "AND genre = $genre ";
}
if ($publisher == "all") {
$publisherQ = "";
} else {
$publisherQ = "AND publisher = $publisher ";
}
if ($minyear == "" && $maxyear == "") {
$yearQ = "";
} else if ($minyear == "" && $maxyear != "") {
$yearQ = "AND release_date <= $maxyear ";
} else if($minyear != "" && $maxyear == "") {
$yearQ = "AND release_date >= $minyear ";
} else if ($minyear != "" && $maxyear != ""){
$yearQ = "AND release_date BETWEEN $minyear AND $maxyear ";
}
$sql = "SELECT * FROM stock WHERE id > 0".$searchQ.$genreQ.$publisherQ.$yearQ.";";
$result = $conn->query($sql);
echo "<table>
<tr>
<th>ID</th>
<th>Title</th>
<th>Publisher</th>
<th>Genre</th>
<th>Price</th>
<th>Release Year</th>
<th>Stock Units</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['title'] . "</td>";
echo "<td>" . $row['publisher'] . "</td>";
echo "<td>" . $row['Hometown'] . "</td>";
echo "<td>" . $row['genre'] . "</td>";
echo "<td>" . $row['price'] . "</td>";
echo "<td>" . $row['release_date'] . "</td>";
echo "<td>" . $row['stock_units'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
I expected a table of relevant results to load on my webpage (hosted on my uni server here: https://students.emps.ex.ac.uk/admt201/webdev/stock-lookup.php), but instead all that happens is that my search parameters are added to the url of the original webpage and nothing new loads.
This is not an answer, but a long comment with multiple suggestions.
A problem of this nature is best attacked by breaking it down and confirming each part. Since PHP is notoriously difficult to troubleshoot (since if there is an error it doesn't generate any helpful message it just abends) I suggest you tackle the PHP side first.
So, make a copy of your stock.php file and replace the $_GET[] variable assignments with some hard-coded data. Then, make sure it outputs success messages (to ensure you are receiving the data you expected) and run that modified stock.php file as a stand-alone. You first need to confirm that the PHP is working, because if it isn't you can troubleshoot the javascript side till the cows come home and true happiness will continue to elude you.
Another troubleshooting methodology that is useful when troubleshooting PHP is to simply add a number of file writes throughout the file, like this:
$hF = fopen("__debug.log", "a");
//run a couple lines of code
fwrite($hF, "Got to here 01");
//run a few more lines of code
fwrite($hF, "Got to here 02");
//repeat...
Then, check the created __debug.log file and see if you got all of the expected file writes, or if the code died somewhere along the way. Otherwise, how would you know?
Note that there is an extension for Chrome called PHPConsole that allows you to output console messages to the browser, but it can be a bit tricky to get working off the start -- whereas the above fwrite() method is rock-solid-reliable and easily implemented.
Similarly, on the javascript side, salt your code with a bunch of console.log() statements to identify where the problems are manifesting.
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 have been designing a website and everything has been working perfectly, until I started adding in little extras so it would work EXACTLY how I wanted it to work.
This is the script for a website that uploads a title, description, name of a person, image, email address and password for the advert that they are putting online. However it no longer wants to correctly name the image and it sends out an email twice, once in the instance that there may be an image and it instantly does it in the instance where someone may not upload an image, but it is reading it as if it is doing both because there is an error with the file upload.
Btw this is the first PHP script I have ever created so it may seem mashy as I have been kind of mixing it up from different things that I have found online :)
p.s the page where the magic happens is www.afterswap.com/give.php
p.p.s I have a global config file that sets all of the DB connection info etc, hence it being non-existent here.
<?PHP
include("inc/header.php");
foreach ($_POST as $key => $val)
$_POST[$key] = mysqli_real_escape_string($con, $val);
$back = "<a href='give.php'>Click Here To Go Back And Try Again</a>";
if (isset($_POST['upload']) && $_FILES['userfile']['size'] > 0) {
$title = mysqli_real_escape_string($title123);
$title123 = mysqli_real_escape_string($_POST['title']);
$description = mysqli_real_escape_string($description123);
$description123 = mysqli_real_escape_string($_POST['description']);
$Sell_by = $_POST['Sell_by'];
$name = mysqli_real_escape_string($name123);
$name123 = mysqli_real_escape_string($_POST['name']);
$email = $_POST['email'];
$password = $_POST['password'];
$imagename = basename($_FILES['userfile']['name']);
$uploadedfile = $_FILES['userfile']['tmp_name'];
if (empty($imagename)) {
$error = 1;
echo "<h2 class='error'>The name of the image was not found.</h2>" . $back;
}
if ($error != 1 && $noimg != 1) {
$filename = stripslashes($_FILES['userfile']['name']);
$extension = substr(strrchr($filename, '.'), 1);
$extension = strtolower($extension);
}
if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) {
echo '<h2 class="error">Error. Images Must Be Jpg, Gif, or Png Format! Please Go Back And Try Another Image.</h2>' . $back . '';
$errors = 1;
} else {
$time = time();
$newimage = "/photos/" . $time . $imagename;
$result = move_uploaded_file($_FILES['userfile']['tmp_name'], $newimage);
if (empty($result)) {
$error = 1;
echo "<h2 class='error'>There was an error uploading your image.</h2><br/>" . $back . "";
}
$date = date("Y/m/d H:i:s");
$query = "INSERT INTO classifieds (adid, title, description, Sell_by, name, email, password, picture, date, views, authorized ) VALUES ('', '$title123', '$description123', '$Sell_by', '$name123', '$email', '$password', '$newimage', '$date', '0', '0')";
mysqli_query($query) or die(mysqli_error());
$pullback = "SELECT * FROM classifieds WHERE title = '$title123' AND email ='$email' limit 1";
$query2 = mysqli_query($pullback) or die(mysqli_error());
while ($row = mysqli_fetch_array($query2, MYSQL_ASSOC)) {
$newid = $row['adid'];
$pass = $row['pass'];
}
$url = "http://";
$url .= getenv("HTTP_HOST");
$Name = "AfterSwap";
$emailf = "noreply#afterswap.com";
$recipient = $email;
$mail_body = "Thank you for posting a new listing!<br /><br />You May Now Manage Your Ad by selecting one of the following options:<br /><br />Approve your listing: <a href='" . $url . "/approve.php?id=" . $newid . "&pass=" . $password . "'>Click Here</a><br/>Edit your listing: <a href='$url/edit.php?id=" . $newid . "&pass=" . $password . "'>Click Here</a><br/>Remove your listing: <a href='" . $url . "/remove.php?id=" . $newid . "&pass=" . $password . "'>Click Here</a><br /><br />Regards,<br /><br />The AfterSwap Team";
$subject = "AfterSwap Ad Details";
$headers = "From: " . $Name . " <" . $emailf . ">\r\n";
$headers .= "Content-type: text/html\r\n";
mail($recipient, $subject, $mail_body, $headers);
echo "<div align='justify'><div class='success'>Your listing '" . $name123 . "' Has Been Submitted Successfully! <br/><br/>Please take note: Your listing will not show on the website until you verify it via the email sent to you. This email also allows you to edit and remove your listing as well.</div></div>";
}
} elseif (isset($_POST['upload'])) {
$title = mysqli_real_escape_string($title123);
$title123 = mysqli_real_escape_string($_POST['title']);
$description = mysqli_real_escape_string($description123);
$description123 = mysqli_real_escape_string($_POST['description']);
$Sell_by = $_POST['Sell_by'];
$name = mysqli_real_escape_string($name123);
$name123 = mysqli_real_escape_string($_POST['name']);
$email = $_POST['email'];
$password = $_POST['password'];
$date = date("Y/m/d H:i:s");
$query = "INSERT INTO classifieds (adid, title, description, cat, Sell_by, name, email, password, picture, date, views, authorized ) VALUES ('', '$title123', '$description123', '$category', '$Sell_by', '$name123', '$email', '$password', 'images/noimage.jpg', '$date', '0', '0')";
mysqli_query($query) or die(mysqli_error());
$pullback = "SELECT * FROM classifieds WHERE title = '$title123' AND email ='$email' limit 1";
$query2 = mysqli_query($pullback) or die(mysqli_error());
while ($row = mysqli_fetch_array($query2, MYSQL_ASSOC)) {
$newid = $row['adid'];
$pass = $row['pass'];
}
$url = "http://";
$url .= getenv("HTTP_HOST");
$Name = "AfterSwap";
$emailf = "noreply#afterswap.com";
$recipient = $email;
$mail_body = "Thank you for posting a new listing!<br /><br />You May Now Manage Your Ad by selecting one of the following options:<br /><br />Approve your listing: <a href='" . $url . "/approve.php?id=" . $newid . "&pass=" . $password . "'>Click Here</a><br/>Edit your listing: <a href='$url/edit.php?id=" . $newid . "&pass=" . $password . "'>Click Here</a><br/>Remove your listing: <a href='" . $url . "/remove.php?id=" . $newid . "&pass=" . $password . "'>Click Here</a><br /><br />Regards,<br /><br />The AfterSwap Team";
$subject = "AfterSwap Ad Details";
$headers = "From: " . $Name . " <" . $emailf . ">\r\n";
$headers .= "Content-type: text/html\r\n";
mail($recipient, $subject, $mail_body, $headers);
echo "<div align='justify'><div class='success'>Thank you " . $name123 . ", your listing has been submitted successfully! <br/><br/>Please take note: Your isting will not show on the website until you verify it via the email sent to you. This email also allows you to edit and remove your listing as well.</div></div>";
} else {
?>
/* HTML Form here */
<?PHP } ?>
Try this
Change this line
} elseif (isset($_POST['upload'])) {
to
} elseif (isset ( $_POST ['upload'] ) && empty($_FILES)) {
The only thing I can think of would be a if, elseif, or else being passed twice because the condition is being met twice. You may want to revise the code with better indentation, and checking when the elseif, if, and else blocks are passed. Also, it would be a really good idea to take the advice from the two people that commented on your post, MYSQLI is a great way to go! One more thing: You should never pass $_POST unsanitized!! Here is a short easy sanitization script!
MYSQLI:
foreach($_POST as $key=>$val)
$_POST[$key] = mysqli_real_escape_string($con, $val);
MYSQL:
foreach($_POST as $key=>$val)
$_POST[$key] = mysql_real_escape_string($con, $val);
I've created a personal messaging system using PHP and MySQL. Part of the system allows for the sending of group e-mails to people who fit within certain groups.
The code for sending the e-mail is:
session_start();
include_once('../../dbconnect.php');
$email=$_SESSION['email'];
$to = $_POST ['touser'];
$toemail = $_POST['touseremail'];
$from = $_SESSION['name'];
$message = $_POST['message'];
$subject = $_POST['subject'];
$time = time();
if ($to == 'Level 4'){
$usersquery = "SELECT email FROM users WHERE account = 'Level4'";
$getusers = $conn -> query($usersquery);
while ($row = $getusers->fetch_assoc()){
foreach ($row as $value){
$query ="INSERT INTO messages (to_user, to_email, subject, message, from_user, from_email, daterecord) VALUES ('" . $to . "', '" . $value . "', '" . mysqli_real_escape_string($conn, $subject) . "', '" . mysqli_real_escape_string($conn, $message) . "', '$from', '$email', '$time')";
$send = $conn -> query($query);
}
}
}
This works fine, but the problem is when I open the sentbox, each individual message is displayed - when a large group has been messaged, this clogs up the sentbox and is very annoying! The code for the sentbox is:
$emailquery = "SELECT * FROM messages WHERE from_email = '$email' AND sent_deleted = 'no' ORDER BY daterecord DESC";
$sentemails = $conn->query($emailquery);
$emailcount = $sentemails ->num_rows;
if ($emailcount == 0){
echo '<div>No messages sent</div>';
}
else{
?>
<table class="udtable">
<tr>
<th class="reqhead">To</th>
<th class="reqhead">Subject</th>
<th class="reqhead"></th>
</tr>
<?
$i=1;
while ($sent = $sentemails->fetch_assoc()){
if ($i%2 != 0){
$rowclass = 'reqodd';
}
else {
$rowclass = 'reqeven';
}
echo ' <tr class = "' . $rowclass . '">
<td class="reqfrom">' . $sent['to_user'] . '</td>
<td class="reqsubj">' . $sent['subject'] . '</td>
<td class="req"><a id="link' . $sent['id'] . '" href="#" class="sentopen">Open</a></td>
<td class="reqmessage"><pre class=sentboxmessage>' . $sent['message'] . '</pre></td>
<td class="reqid">' . $sent['id'] . '</td>
</tr>';
$i++;
}
?>
</table>
<?
}
?>
The sentbox looks like this:
I'd like to consolidate all of those messages into a single line.
Any ideas?
Thanks!
You need to use grouping in your mysql select statement in your sentbox code snippet
SELECT * FROM messages WHERE from_email = '$email' AND sent_deleted = 'no' GROUP BY subject, daterecord ORDER BY daterecord DESC
This will work and will group your messages by the subject and by the daterecord. So any messages that are sent all at the same time with the same subject will be grouped together. You might need to add in more grouping options to refine if multiple people could send messages with the same subject at the same time.
I have a while loop printing multiple checkboxes..I changed them to checkboxes instead of radio buttons.. now all I want to do is pass the names of all those checkboxes to my vote.php file. If I give my checkbox in my loop a simple name and carry that over to my vote.php which handles all my POST data, it only carries over my last selection.. I want all of my selections. I cleaned my code up for you guys a little bit.
Tell me where I am going wrong here.. here is my initial code printing the buttons..
while($row_nominee=mysql_fetch_array($result_nominee)){
$id = $row_nominee[0];
//print "$level";
$prefix = $row_nominee[1];
$fname = $row_nominee[2];
$lname = $row_nominee[3];
$suffix = $row_nominee[4];
$city = $row_nominee[5];
$state = $row_nominee[6];
$zip = $row_nominee[7];
$bio = $row_nominee[8];
$level = $row_nominee[10];
$name = $prefix . " " . $fname . " " . $lname;
$address = $city . " " . $state . " " . $zip;
//print "$voted";
print "<tr>";
print "<td width=\"4\" valign=\"top\"><input type=\"checkbox\" name=\"candidateOne\" id=\"candidate\" value=$id></td>";
print "<td valign=\"top\"><FONT face=Tahoma,Arial,Helv size=-1><b>Name:</b> <font color=\"#ff0000\">$name</font><br><b>Hometown:</b> $address<br><b>Bio:<br /></b> $bio</font></td>";
print "</tr>";
}
?>
//now here is my vote.php file which handles the checkboxes.
//get the contents from the vote ballot Form
$voter_id = safeEscapeString(qsrequest(voter));
$candidate_id = safeEscapeString(qsrequest(candidateOne));
//print "$voter_id and $candidate_id";
include '../../sql/usagym_connection.php';
if(qsrequest(correct))
{
$voter_id1= safeEscapeString(qsrequest(voter1));
$candidate_id1= safeEscapeString(qsrequest(candidate1));
$votes1= safeEscapeString(qsrequest(votes1));
$votes1 += 1;
$sql_voter = "update stateChair_voters set voted='Y' where (usagnum='$voter_id1')";
//print "$sql_voter<br>";
$result_voter = mysql_query($sql_voter, $link) or die("Invalid query2");
$update_candidate = "update stateChair_nominees set votes=$votes1 where (id=$candidate_id1)";
//print "$update_candidate<br>";
$result_update = mysql_query($update_candidate, $link) or die("Invalid query3");
//print "Total votes is $votes1.";
header( "Location: vote_thanks.html");
exit;
}
else
{
//connect the database
$sql_candidate = "select id, prefix, fname, lname, suffix, city, state, zip, bio, votes from stateChair_nominees where id=$candidate_id";
$result_candidate = mysql_query($sql_candidate, $link) or die("Invalid query1". mysql_error());
while($row_candidate=mysql_fetch_array($result_candidate)){
$id = $row_candidate[0];
$prefix = $row_candidate[1];
$fname = $row_candidate[2];
$lname = $row_candidate[3];
$suffix = $row_candidate[4];
$city = $row_candidate[5];
$state = $row_candidate[6];
$zip = $row_candidate[7];
$bio = $row_candidate[8];
$votes = $row_candidate[9];
$name = $prefix . " " . $fname . " " . $lname;
$address = $city . " " . $state . " " . $zip;
}
?>
All I really want to do is submit multiple people to a vote and not just one person. Thoughts? Thanks guys!
Here is my code for my checkboxes..
print "<td width=\"4\" valign=\"top\"><input type=\"checkbox\" name=\"candidateOne\" id=\"candidate\" value=$id></td>";
Now here is the code that handles these checkboxes.. I didn't write this code and I am having to debug it, so any help is appreciated.
$candidate_id = safeEscapeString(qsrequest(candidateOne));
This code right now handles a string, not a variable. What's the process in having a variable represent multiple checkboxes on the other file while recording them on here?
print "<td width=\"4\" valign=\"top\"><input type=\"radio\" name=\"candidateOne\" id=\"candidate\" value=$id></td>";
You must change the 'name' as you have changed the 'value' in the loop by a variable.