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).
Related
This is for an assignment, so the code is based on how the learning resources are presented. I have a plant database that I have to make changes to, and then update plantID no.2. I have created the form which is then populated with plantID 2 info, but when I click the Update button after making changes, it wipes all the info for that entry in the database. I'm not sure where I have gone wrong. Any help would be awesome.
<?php
// MySQL Database Connect
require_once("connect.php");
// read the values from the form and store in variables
$botanicName = $_POST['bot_name'];
$commonName = $_POST['comm_name'];
$plantDescription = $_POST['pl_desc'];
$commonUse = $_POST['comm_use'];
$maxHeight = $_POST['m_height'];
$maxWidth = $_POST['m_width'];
$popular = $_POST['pop'];
// escape variables for security
$botanicName = mysqli_real_escape_string($conn, $bot_name);
$commonName = mysqli_real_escape_string($conn, $comm_name);
$plantDescription = mysqli_real_escape_string($conn, $pl_desc);
$commonUse = mysqli_real_escape_string($conn, $comm_use);
$maxHeight = mysqli_real_escape_string($conn, $m_height);
$maxWidth = mysqli_real_escape_string($conn, $m_width);
$popular = mysqli_real_escape_string($conn, $pop);
// create the UPDATE query
$query="UPDATE plant SET botanicName='$botanicName', commonName='$commonName', plantDescription='$plantDescription', commonUse='$commonUse', maxHeight='$maxHeight', maxWidth='$maxWidth', popular='$popular' WHERE plantID='2'";
//execute the query
$results = mysqli_query($conn, $query );
// check for errors
if(!$results) {
echo ("Query error: " . mysqli_error($conn));
exit;
}
else {
// Redirect the browser window back to the make_changes page if there are no errors
header("location: ../make_changes.html");
}
?>
<h2>Edit a Plant</h2>
<?php
// run a select query to return the existing data for the record
$query = "SELECT * FROM plant WHERE plantID='2'";
$results = mysqli_query($conn, $query );
// capture any errors
if(!$results) {
echo ("Query error: " . mysqli_error($conn));
}
else {
// fetch and store the results for later use if no errors
while ($row = mysqli_fetch_array($results)) {
$bot_name = $row['botanicName'];
$comm_name = $row['commonName'];
$pl_desc = $row['plantDescription'];
$comm_use = $row['commonUse'];
$m_height = $row['maxHeight'];
$m_width = $row['maxWidth'];
$pop = $row['popular'];
}
}
?>
<form method="post" action="code/update_plant.php">
<p>Botanic Name: <input type="text" name="botanicName" value="<?=$bot_name?>" required></p>
<p>Common Name: <input type="text" name="commonName" value="<?=$comm_name?>"required></p>
<p>Plant Description: <input type="text" name="plantDescription" value="<?=$pl_desc?>" required></p>
<p>Common Use: <input type="text" name="commonUse" value="<?=$m_height?>" required></p>
<p>Max. Height (m): <input type="text" name="maxHeight" value="<?=$m_height?>" required></p>
<p>Max. Width (m): <input type="text" name="maxWidth" value="<?=$m_width?>" required></p>
<p>Popular? (Y/N): <input type="text" name="popular" value="<?=$pop?>"required></p>
<input type="submit" name="submit" value= "Update">
</form>
The parameters sent to $_POST have the name key in your input so your $_POST['bot_name'] for example is empty, the correct way to get that name is $_POST['botanicName'].
This will be your post parameters:
$botanicName = $_POST['botanicName'];
$commonName = $_POST['commonName'];
$plantDescription = $_POST['plantDescription'];
$commonUse = $_POST['commonUse'];
$maxHeight = $_POST['maxHeight'];
$maxWidth = $_POST['maxWidth'];
$popular = $_POST['popular'];
The names you use in the form have to exactly match the indexes you use in $_POST. You are using variables that are not defined.
// read the values from the form and store in variables
$botanicName = $_POST['botanicName'];
$commonName = $_POST['commonName'];
$plantDescription = $_POST['plantDescription'];
$commonUse = $_POST['commonUse'];
$maxHeight = $_POST['maxHeight'];
$maxWidth = $_POST['maxWidth'];
$popular = $_POST['popular'];
Fix the mysqli escape function calls:
// variable $bot_name does not exist therefore it results in a null value
$botanicName = mysqli_real_escape_string($conn, $bot_name); // bad
// Fixed
$botanicName = mysqli_real_escape_string($conn, $botanicName); // good
Make the form input names the same as $_POST
<form method="post" action="code/update_plant.php">
<p>Botanic Name: <input type="text" name="botanicName" value="<?=$botanicName?>" required></p>
<p>Common Name: <input type="text" name="commonName" value="<?=$botanicName?>"required></p>
<p>Plant Description: <input type="text" name="plantDescription" value="<?=$plantDescription?>" required></p>
<p>Common Use: <input type="text" name="commonUse" value="<?=$maxHeight?>" required></p>
<p>Max. Height (m): <input type="text" name="maxHeight" value="<?=$m_height?>" required></p>
<p>Max. Width (m): <input type="text" name="maxWidth" value="<?=$maxWidth?>" required></p>
<p>Popular? (Y/N): <input type="text" name="popular" value="<?=$popular?>"required></p>
<input type="submit" name="submit" value= "Update">
</form>
I needed to change the indexes in the $_POST (I was using undefined variables) and change them also in the mysqli escape functions.
I'm having trouble with posting values typed into textarea. everything else works well, any idea how to make it work?
HTML:
<form id="formData2" action="artistuploader.php" method="post"
enctype="multipart/form-data">
<input type="hidden" name="size" value="1000000"></input>
<br/>
<input id="inputField" type="text" name="actname" placeholder="Act Name" >
<br>
<input id="inputField" type="text" name="fullname" placeholder="Full Name" >
<br>
<input id="inputField" type="text" name="genre" placeholder="Genre" >
<br>
<textarea id="inputField" name="biography" form="formData2" placeholder="Biography"<?php echo $biography; ?>></textarea>
<br>
<input id="inputField" type="file" name="artistImage" placeholder="Artwork" >
<br>
<input id="inputField" type="text" name="imagepath" placeholder="Image path URL" >
<br>
<input id="submitButton" type="submit" name="uploadArtist" value="Register Artist">
</form>
PHP
<?php
$msg = "";
//if Upload button is pressed
if (isset($_POST['uploadArtist'])){
$target = "uploads/artistPics".basename($_FILES['artistImage']['name']);
//connecting to our database
$db = mysqli_connect("127.0.0.1", "user", "pass", "tablename");
$tmp_name = $_FILES['artistImage']['tmp_name'];
$name = $_FILES['artistImage']['name'];
//getting the submitted form data
$ActName = $_POST['actname'];
$FullName = $_POST['fullname'];
$Genre = $_POST['genre'];
$ArtistPhoto = $_FILES['artistImage']['name'];
$imageURLpath = $_POST['imagepath'];
$Biography = $_POST['biography'];//having problem with this line here
//saving submitted data into database table songsDB
$sql = "INSERT INTO artistsdb (ActName,FullName,Genre,ArtistPhoto,Biography,imageURLpath) VALUES ('$ActName','$FullName','$Genre','$ArtistPhoto','$Biography','$imageURLpath')";
mysqli_query($db, $sql); //stores the submitted data into table
//now moving the uploaded image to uploads folder
if(move_uploaded_file($_FILES['artistImage']['tmp_name'], $target)){
$msg = "Uploaded Successful";
}else{
$msg = "There was a problem uploading Data";
}
}
//header("refresh:1; url=index.php"); ?>
Replace your textarea with
<textarea id="inputField" name="biography" form="formData2" placeholder="Biography"><?php echo $biography; ?></textarea>
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>
';
}
My site has a simplistic login that when you go to an adminSLP page it redirects to the admin login page if the user isnt logged in. Problem is that when you are logged in to the page and try say inserting a record with the form i posted below it redirects you back to the login page. I cant see where I am going wrong.
ADMIN SLP
session_start();
// Call this function so your page
// can access session variables
if ($_SESSION['adminloggedin'] != 1) {
// If the 'loggedin' session variable
// is not equal to 1, then you must
// not let the user see the page.
// So, we'll redirect them to the
// login page (login.php).
header("Location: adminLogin.php");
exit;
}
ADMIN LOGIN
session_start();
if ($_GET['login']) {
// Only load the
code below if the GET
// variable 'login' is set. You will
// set this when you submit the form
if ($_POST['adminusername'] == '******'
&& $_POST['adminpassword'] == '*******') {
// Load code below if both username
// and password submitted are correct
$_SESSION['adminloggedin'] = 1;
// Set session variable
header("Location: adminSLP.php");
exit;
// Redirect to a protected page
} else echo '<style>#falseLogin{display: block!important;}</style>';
// Otherwise, echo the error message
}
LOGIN FORM
<form method="POST" action="adminLogin.php?login=true" id="adminlogin" style="padding:0">
<label for="adminusername">Username:</label>
<input type="text" name="adminusername" autocomplete="off"><br/>
<label for="adminpassword">Password:</label>
<input type="password" name="adminpassword" autocomplete="off" /><br/>
<input type="submit" value="Login">
</form>
FORM MADE FOR INSERTING RECORDS TO A DB
<form id="trainingForm" method="post" action="" style="display:block;">
<div>
<h2 id="title" style="color:#c89d64;font-size:36px;font-family: 'RokkittRegular'; margin:0 0 15px; padding:30px 0 30px 0;font-weight:normal;">Add New SLP</h2>
<label for="first_name">First Name</label><input id="first_name" name="first_name" data-required="false" data-validation="length" data-validation-length="min4" type="text">
<label for="last_name">Last Name</label><input id="last_name" name="last_name" data-required="false" data-validation="length" data-validation-length="min4" type="text">
<label for="title">Title</label><input id="title" name="title" data-required="false" data-validation="length" data-validation-length="min4" type="text">
<label for="user_phone">Phone*</label><input id="user_phone" name="user_phone" type="tel" value="(123) 456-7890" data-required="true" onFocus="if(this.value == '(123) 456-7890') this.value='';">
<label for="user_email">Email*</label><input id="user_email" name="user_email" type="email" value="name#something.com" data-required="true" data-validation="email" onFocus="if(this.value == 'name#something.com') this.value='';">
<label for="state_name">License Held In:</label><select name='state_name[]' id="state_name" multiple>
<?php
$result = mysqli_query($con,'SELECT * FROM license_state');
$count = 1;
while($row = mysqli_fetch_array($result))
{
echo '<option value=' . $row['state_name'] . '>' . $row['state_name'] . '</option>';
}
?>
</select>
<span><label for="isChecked">May we post your information on our site?:</label>
<input type="radio" name="isChecked" value="1" checked="checked"><p>Yes</p>
<input type="radio" name="isChecked" value="0"><p>No</p></span>
<label for="asha_number">Asha# (Will Not Be Published)*</label><input id="asha_number" name="asha_number" data-required="true" data-validation="length" data-validation-length="min4" type="text">
<label for="practice_name">Practice Name*</label><input id="practice_name" name="practice_name" data-required="true" data-validation="length" data-validation-length="min4" type="text">
<label for="practice_location">Practice Location*</label><input id="practice_location" name="practice_location" data-required="true" data-validation="length" data-validation-length="min4" type="text">
<span><label for="telepracticeProvider">Are you a telepractice provider?:</label>
<input type="radio" name="telepracticeProvider" id="yes" value="Yes" ><p>Yes</p>
<input type="radio" name="telepracticeProvider" id="no" value="No" checked="checked"><p>No</p></span><br/>
<input type="hidden" id='user_id' name='user_id'/>
<br/><button name="submit" id="submit" type="submit">Submit</button>
</div>
</form>
insert to db
if(isset($_POST['submit']))
{// Create connection
$con=mysqli_connect("Speechvive.db.11357591.hostedresource.com","****","*****!","Speechvive");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$title = $_POST['title'];
$state_name = $_POST['state_name'];
$asha_number = $_POST['asha_number'];
$practice_name = $_POST['practice_name'];
$practice_location = $_POST['practice_location'];
$user_phone = $_POST['user_phone'];
$user_email = $_POST['user_email'];
$isChecked = $_POST['isChecked'];
$telepracticeProvider = $_POST['telepracticeProvider'];
$implodeStates = implode(', ',$state_name);
$insert = "INSERT INTO users ".
"(first_name,last_name, title, state_name, asha_number, practice_name, practice_location, user_phone, user_email, isChecked, telepracticeProvider) ".
"VALUES('$first_name','$last_name', '$title', '$implodeStates', $asha_number, '$practice_name', '$practice_location', '$user_phone', '$user_email', '$isChecked', '$telepracticeProvider')";
$insertData = mysqli_query( $con,$insert );
if(! $insertData )
{
die('Could not enter data: ' . mysql_error());
}
mysqli_close($con);?>
<script>window.location = "http://www.speechvive.com/adminSLP.php";//RELOAD THE CURRENT PAGE</script><?php
} else if(isset($_POST['save'])){
// Create connection
$con=mysqli_connect("Speechvive.db.11357591.hostedresource.com","Speechvive","Slp2014!","Speechvive");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$user_id = $_POST['user_id'];
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$title = $_POST['title'];
$state_name = $_POST['state_name'];
$asha_number = $_POST['asha_number'];
$practice_name = $_POST['practice_name'];
$practice_location = $_POST['practice_location'];
$user_phone = $_POST['user_phone'];
$user_email = $_POST['user_email'];
$isChecked = $_POST['isChecked'];
$telepracticeProvider = $_POST['telepracticeProvider'];
$implodeStates = implode(', ',$state_name);
$update = ("UPDATE users SET first_name='$first_name',last_name='$last_name', title='$title', state_name='$implodeStates', asha_number='$asha_number', practice_name='$practice_name', practice_location='$practice_location', user_phone='$user_phone', user_email='$user_email', isChecked='$isChecked', telepracticeProvider='$telepracticeProvider' WHERE user_id = $user_id");
$updateData = mysqli_query( $con,$update );
if(! $updateData )
{
die('Could not enter data: ' . mysqli_error($con));
}
mysqli_close($con);?>
<script>window.location = "http://www.speechvive.com/adminSLP.php";</script><?php
}
window.location = "http://www.speechvive.com/adminSLP.php";
why did you wrote this in insert to db part.. I think this is creating the problem
I have the following code, whenever I try to insert the data, the $content is not being inserted, where might the problem be? I am using the function test input for security related issues.
<?php
// define variables and set to empty values
$title = $content = $path = $file_type ="";
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$title = test_input($_POST["title"]);
$content = test_input($_POST["content"]);
$path = test_input($_POST["path"]);
$file_type = test_input($_POST["file_type"]);
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$con=mysqli_connect("localhost","---","---","---");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO articles (ArtID,Title,Content,Image_VideoLink_Path,file_type)
VALUES
('','$title','$content','$path',' $file_type')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "<h2 >Article Published</h2>";
echo"<a href='../mag/index.php'> View it Now </a>";
mysqli_close($con);
?>
here is the code for the form:
<form method="POST" action="artPro.php">
<fieldset>
<legend>Create New Article</legend>
<br/>
Article Title:
<input type="text" placeholder="enter title here" class="span3" name="title" required>
Image/Video Path :
<input type="text" placeholder="enter image name e.g k.jpg or k.mp4 for video" name="path" class="span3" required/>
File Type :
<input type="text" name="file_type" class="span3" required placeholder="e.g: image or video"/>
<br/>
<label>Article Content:</label>
<textarea name="content" rows="20" class="jqte-test span12" required id="txtmsg"></textarea>
<br><button type="submit" class="btn btn-primary btn-large pull-right">Publish</button>
</fieldset>
</form>
Try this query:
$sql="INSERT INTO articles
(Title,Content,Image_VideoLink_Path,file_type) VALUES
('$title','$content','$path',' $file_type')";
$content was not being inserted because you are giving Article ID. And I am sure that Article ID will your primary key and this will auto incremented. So, you did not need to mention Article id in sql query (statement).