PHP Chatbox : Cannot Send to MySQL Database - php

Code :
$user = $_POST["user"];
$message = $_POST["message"];
$message = htmlspecialchars($message);
$db=mysqli_connect("host","username","pwd","db");
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysql_connect_error();
}
#Connected
if(isset($message) == true && $message != "" && $message != " "){
if(isset($user) == false){
$user = "visitor";
}
$sql="
INSERT INTO ChatBox (DateTime, User, Content)
VALUES
(now(),'$_POST[User]','$_POST[Content]')
";
if (!mysqli_query($db,$sql))
{
die('Error: ' . mysqli_error($db));
}
}
mysqli_close($db);
This is my code in a chatbox.
However, I use the line if(isset($message) == true && $message != "" && $message != " "){ to find out whether $_POST['message'] is null or not.
Finally, I cannot insert anything in my chat box.
This is my chatbox link : http://jamie-is-cool.comeze.com/chat.php
The problem is that : After clicking Send! nothing happened. It just reload and didn't send.
What should I do?
A complete list of code is available here.

Insert code block will on fire if the statement if( isset( message) ... returns a true.
But in your HTML form, there is no such element with name message but a user and content.
<form action="chat.php" style="margin:0px;padding:1px;" method="POST">
User: <input type="text" style="width:15%;" name="User" /> |
<input type="text" style="width:65%;" name="Content" />
<input type="submit" value="Send!" style="width:10%;" />
</form>
Add an input type element named message to the form with some value and then submit to get succeed.
<form action="chat.php" style="margin:0px;padding:1px;" method="POST">
User: <input type="text" style="width:15%;" name="User" /> |
<input type="text" style="width:65%;" name="Content" />
<input type="text" style="width:65%;" name="message" />
<input type="submit" value="Send!" style="width:10%;" />
</form>
For better display, adjust the form table display width accordingly.

Related

How to retrieve and confirm form inputs on another php file

I have The following form inputs I am trying to send these input data to "placebet.php" then retrieve the data and add a confirm or cancel button, then It can add to the database
<form action="placebet.php" method="post">
<div id="box" class="boxlit">
<div class="box" data-id="0">Myanmar - Vietnam<br>Home [1]<div class="crtTotal">4.30</div>
<input type="hidden" name="kickoff[]" value="7/17/2022 10:00">
<input type="hidden" name="match[]" value="Myanmar - Vietnam">
<input type="hidden" name="result[]" value="Home [1]" readonly="">
<input type="hidden" name="value[]" value="4.30"></div>
<div class="box" data-id="4">Thailand - Philippines<br>Draw [2]<div class="crtTotal">3.20</div>
<input type="hidden" name="kickoff[]" value="7/17/2022 13:30">
<input type="hidden" name="match[]" value="Thailand - Philippines">
<input type="hidden" name="result[]" value="Draw [2]" readonly="">
<input type="hidden" name="value[]" value="3.20"></div>
<div class="box" data-id="11">Botswana - Cameroon<br>Away [3]<div class="crtTotal">1.35</div>
<input type="hidden" name="kickoff[]" value="7/17/2022 22:00">
<input type="hidden" name="match[]" value="Botswana - Cameroon">
<input type="hidden" name="result[]" value="Away [3]" readonly="">
<input type="hidden" name="value[]" value="1.35"></div></div><br>
<input type="hidden" name="account[]" value="0818054386" readonly="">
<input type="hidden" name="balance[]" value="20" readonly="">
<input type="hidden" id="todds" name="todds[]" value="18.58" readonly="">
<input type="hidden" id="inp" name="payout[]" value="92.90" readonly="">
<div>Total Odds: <b id="ct1">18.58</b></div><br>
<div>(N$)Stake: <input id="stake" type="number" name="stake[]" value="5"> NAD</div><br>
<div>Payout: N$ <b id="payout">92.90</b></div>
<input class="bet1" type="submit" name="submit" value="Bet">
</form>
Php code in "placebet.php"
I'm not sure if the code below is correct but I need it to show the input data from the form and give me a option to confirm the data(button) and then it can finally add to the database
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "", "forms");
$dba = mysqli_connect("localhost","root","","login");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$error = false; //set the error status value
$error_msg = "";
$back = mysqli_real_escape_string($link, $_REQUEST['kickoff'][0]);
$total = count($back); // get the length of the match
for($i=0;$i<$total;$i++){
// Escape user inputs for security
$kickoff = mysqli_real_escape_string($link, $_REQUEST['kickoff'][$i]);
$match = mysqli_real_escape_string($link, $_REQUEST['match'][$i]);
$selection = mysqli_real_escape_string($link, $_REQUEST['result'][$i]);
$odd = mysqli_real_escape_string($link, $_REQUEST['value'][$i]);
$account = mysqli_real_escape_string($link, $_REQUEST['account'][0]);
$stake = mysqli_real_escape_string($link, $_REQUEST['stake'][0]);
$payout = mysqli_real_escape_string($link, $_REQUEST['payout'][0]);
$todds = mysqli_real_escape_string($link, $_REQUEST['todds'][0]);
$accabal = mysqli_real_escape_string($link, $_REQUEST['balance'][0]);
//run sql query for every iteration
$charge = mysqli_query($dba, "UPDATE users SET balance = $accabal- $stake WHERE username='".$_SESSION['username']."'") ;
$_SESSION["balance"] = $accabal- $stake ;
$date = date ('Ymd');
$create = mysqli_query($link,"CREATE TABLE R$date LIKE receipts") ;
$insert = mysqli_query($link,"INSERT INTO `R$date`(`Match`, `Selection`, `Odd`,`Account`,`Stake Amount`,`Payout`,`Total Odds`) VALUES ('$match','$selection','$odd','$account','$stake','$payout','$todds')");
if(!$insert)
{
$error = true;
$error_msg = $error_msg.mysqli_error($link);
}
//check your error status variable and show your output msg accordingly.
if($error){
echo "Error :".$error_msg;
}else{
header("location: index.php");
exit;
}
}
mysqli_close($db);
?>
What you want to do isn't redirect to index.php, cause with this you start a new request and cant point on the request data of placebet.php anymore.
You want either to send your form via javascript ajax request and then react to the response of placebet.php (https://www.w3schools.com/js/js_ajax_intro.asp) or generating your own new output at placebet.php which then can be a confirm page or something similar.
e.g.
if($error){
echo "Error :".$error_msg;
}else{
echo "Data has been stored!";
}
You also could put your html at the end of the php file after closing the php part with ?> like mentioned here https://www.thoughtco.com/php-with-html-2693952#:~:text=As%20you%20can%20see%2C%20you,re%20inside%20the%20PHP%20tags).

After I hit Submit on my PHP page nothing happens. The data should import into my php database

I created this signup page. The problem is when I click submit after I enter the information nothing happens. It just refreshes the same page. The info I enter should import into my database after I hit submit and display a thank you for signing up message after the submission. Please help. I'm trying to keep everything to single page by implementing the html and php code all on one page instead of 2 separate files.
<html>
<body>
<?php
$output_form = true; //declare a FLAG we can use to test whether or not to show form
$first_name = NULL;
$last_name = NULL;
$email = NULL;
if (isset($_POST['submit']) ) { //conditional processing based on whether or not the user has submitted.
$dbc = mysqli_connect('localhost', 'name', 'pswd', 'database')
or die('Error connecting to MySQL server.');
$first_name = mysqli_real_escape_string($dbc, trim($_POST['firstname']));
$last_name = mysqli_real_escape_string($dbc, trim($_POST['lastname']));
$email = mysqli_real_escape_string($dbc, trim($_POST['email']));
$output_form = false; // will only change to TRUE based on validation
//Validate all form fields
if (empty($first_name)) {
echo "WAIT - The First Name field is blank <br />";
$output_form = true; // will print form.
}
if (empty($last_name)) {
echo "WAIT - The Last Name field is blank <br />";
$output_form = true; // will print form.
}
if (empty($email)) {
echo "WAIT - The Email field is blank <br />";
$output_form = true; // will print form.
}
if ((!empty($first_name)) && (!empty($last_name)) && (!empty($email))) {
//End of form validation
//This section establishes a connection to the mysqli database, and if it fails display error message
$query = "INSERT INTO quotes (first_name, last_name, email, " .
"VALUES ('$first_name', '$last_name', '$email')";
$result = mysqli_query($dbc, $query)
or die('Error querying database.');
mysqli_close($dbc);
$to = 'email#email.com';
$subject = 'New Customer';
$msg = "$first_name $last_name\n" .
"Email: $email\n";
$mail = mail($to, $subject, $msg, 'From:' . $email);
if($mail){
header("Location: https://www.locate.com/blue.php".$first_name);
exit();
}
//Display the user input in an confirmation page
echo "<body style='margin-top: 100px; background-color: #f2f0e6;'><p style = 'color: #000000; text-align: center;font-size:300%; font-family:Arial, Helvetica, sans-serif;'><strong>Thanks for signing up!</strong></p><center><p style = 'color: #000000; text-align: center;font-size:200%; font-family:Arial, Helvetica, sans-serif;'>Contact us for any questions
</p>
</center>
</body>";
}//end of validated data and adding recored to databse. Closes the code to send the form.
} //end of isset condition. This closes the isset and tells us if the form was submitted.
else { //if the form has never been submitted, then show it anyway
$output_form = true;
}
if ( $output_form ) { //we will only show the form if the user has error OR not submitted.
?>
<div id="box">
<center><img src="../../images/duck.jpg" class="sign-up" alt="Sign Up"></center>
<br>
<p>Sign Up to get Discount Code</p><br>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?> ">
<div>
<label for="firstname">First name:</label>
<input type="text" id="firstname" name="firstname" size="37" maxlength="37" value=" <?php echo $first_name; ?>" />
</div>
<div>
<label for="lastname">Last name:</label>
<input type="text" id="lastname" name="lastname" size="37" maxlength="37" value="<?php echo $last_name; ?>" />
</div>
<div>
<label for="email">Email:</label>
<input type="text" id="email" name="email" size="37" maxlength="37" value="<?php echo $email; ?>" />
</div>
<div id="submit">
<input type="submit" name="Submit" value="Submit" />
</div>
</center>
</form>
</div>
<?php
}
?>
</body>
You are asking for $_POST['submit'] instead of $_POST['Submit']

PHP - editing data in db issue

I'm going to keep it short and simple. I'm writing a really basic code in php which adds content to mysql db and I've run into an issue with editing. This is my form:
if($idExists)
{
Print '
<form action="editIt.php" method="POST">
<div name="id"> '. $id . '</div>
Enter new detail: <input type="text" name="details"/><br/>
public post? <input type="checkbox" name="public[]" value="yes"/><br/>
<input type="submit" value="Update List"/>
</form>
';
}
And this is my editIt.php
//session start and stuff
if(filter_input(INPUT_SERVER, 'REQUEST_METHOD', FILTER_SANITIZE_STRING) == "POST")
{
echo "<script type='text/javascript'>alert('EDITIT!');</script>";
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("WebSiteDB") or die ("Cannot connect to database");
$id = $_POST['id'];
$details = mysql_real_escape_string($_POST['details']);
$time = strftime("%X");
$date = strftime("%B %d, %Y");
$isPublic = 'no';
foreach($_POST['public'] as $eachCheck)
{
if($eachCheck != NULL)
$isPublic = "yes";
}
mysql_query("UPDATE list SET details='$details', dateEdited='$date', timeEdited= '$time', public='$isPublic' WHERE id='$id'");
header("location: home.php");
}
I can't really find an issue with this code (which is not really strange, I'm a newbie at web stuff) and yet it just goes to home.php and does not change data in DB. Please, help me jump this ledge, so I can go on with my life.
I think, the problem is in this line $id = $_POST['id'];. On form submit, the input field value will only be submitted, not the DIV value.
So, please change from :
if($idExists)
{
Print '
<form action="editIt.php" method="POST">
<div name="id"> '. $id . '</div>
Enter new detail: <input type="text" name="details"/><br/>
public post? <input type="checkbox" name="public[]" value="yes"/><br/>
<input type="submit" value="Update List"/>
</form>
';
}
To :
if($idExists)
{
Print '
<form action="editIt.php" method="POST">
<input type="hidden" name="id" value="' . $id . '">
Enter new detail: <input type="text" name="details"/><br/>
public post? <input type="checkbox" name="public[]" value="yes"/><br/>
<input type="submit" value="Update List"/>
</form>
';
}

Why isn't my php form passing the data

here is my code. I am not sure why after i input the first and last name the second page does not show the proper text.. The form is suppose to take in first name and last name into a text box.. Then on the next page when person submits it should validate that the proper type of data was input, and then print out text if it was not, or print out text if it was successful.
<body>
<h2 style="text-align:center">Scholarship Form</h2>
<form name="scholarship" action="process_Scholarship.php" method="post">
<p>First Name:
<input type="text" name="fName" />
</p>
<p>Last Name:
<input type="text" name="lName" />
</p>
<p>
<input type="reset" value="Clear Form" />
<input type="submit" name="Submit" value="Send Form" />
</form>
my second form
<body>
<?php
$firstName = validateInput($_POST['fName'],"First name");
$lastName = validateInput($_POST['lName'],"Last name");
if ($errorCount>0)
echo <br>"Please use the \"Back\" button to re-enter the data.<br />\n";
else
echo "Thank you for fi lling out the scholarship form, " . $firstName . " " . $lastName . ".";
function displayRequired($fieldName)
{
echo "The field \"$fieldName\" is required.<br />n";
}
function validateInput($data, $fieldName)
{
global $errorCount;
if (empty($data))
{
displayRequired($fieldName);
++$errorCount;
$retval = "";
}
else
{
$retval = trim($data);
$retval = stripslashes($retval);
}
return($retval);
}
$errorCount = 0;
?>
</body>

How to validate form [duplicate]

This question already has an answer here:
How to validate form in php
(1 answer)
Closed 8 years ago.
Anyone please help me on how to validate a form? I have the code, it is working ok..but I found that after I hit the submit button & php shows the errors, there is an input field, asking the user to answer the math Ques..when I enter the answer, then hit submit button again, it just says mail successfully sent, but other fields are still empty. Any ideas how to fix it. Also, the php value in the answerbox input tags, is not saving the text in box, it disappears. by the way, I got some help from other users, i'm a noob in php, so if you don't mind please explain.
Thanks for your time!
<form name="contact" action="formtest.php" method="post">
<label for="YourName">Your Name:</label>
<input type="text" name="name" class="required" value="<?= isset($_POST['name']) ? $_POST['name'] : '' ?>" />
<label for="YourEmail">Your Email:</label>
<input type="text" name="email" class="required" value="<?= isset($_POST['email']) ? $_POST['email'] : '' ?>"/>
<label for="Subject">Subject:</label>
<input type="text" name="subject" class="required" value="<?= isset($_POST['subject']) ? $_POST['subject'] : '' ?>" />
<label for="YourMessage">Your Message:</label>
<textarea name="message" class="required"><?= isset($_POST['message']) ? $_POST['message'] : '' ?></textarea>
<p class="c3">10 + 5 =<input type="text" name="answerbox" id="answerbox" "<?= isset($_POST['answerbox']) ? $_POST['answerbox'] : '' ?>"/></p>
<fieldset>
<input type="submit" name="submit" id="submit" value="Send" class="required"/>
<input type="reset" id="reset" value="Reset"/>
</fieldset>
<?php
if(isset($_POST['submit'])){
$name = trim($_POST["name"]);
$email = trim($_POST["email"]);
$subject = trim($_POST["subject"]);
$message = trim($_POST["message"]);
$answerbox = trim($_POST["answerbox"]);
if(empty($_POST['name'])){
print "<div class='formerrors'><li>Please type your name.</li></div>";
}
else {
if (ctype_alpha($name) === false) {
print "<div class='formerrors'><li>Your name only should be in letters!</li></div>";
}
}
if(empty($_POST['email'])){
print "<div class='formerrors'><li>You've forgot to type your email address.</li></div>";
} else{
if(filter_var($email, FILTER_VALIDATE_EMAIL) === false){
print "<div class='formerrors'><li>Your email is not valid, please check.</li></div>";
}
}
if(empty($_POST['subject'])){
print "<div class='formerrors'><li>Please type a subject.</li></div>";
}
if(empty($_POST['message'])){
print "<div class='formerrors'><li>You've forgot to type your message.</li></div>";
}
if(empty($_POST['answerbox'])){
print "<div class='formerrors'><li>Please answer the math question.</li></div>";
}
else {
if($answerbox != 15){
print"<div class='formerrors'><li>Answer is not correct.</li></div>";
}
else{
$headers = 'From: '.$email. "\r\n" .
'Reply-To: '.$email . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail('me#mymail.me',$subject,$message,$headers);
print "<div class='formerrors'><li>mail succesuffully sent</li></div>";
}
}
}
?>
</form>
Try placing your php code above the html as it is php setting the values of the variables, and you are calling them before they are set.
It is best practice to have php code at the top of the file, and then html below it, or even have the php on a separate file, but include it at the top.
Also I find it better to create an array of errors, and then if the array count is 0, then perform the action (send email) else call the error of arrays within the html, not the php. Then you can choose where to display it on the page, and style it accordingly.
Change your form action to
<?php $PHP_SELF; ?>
So it has to be
<form name="contact" action="<?php $PHP_SELF; ?>" method="post">
For the other issue you must place your code above the form.

Categories