PHP - editing data in db issue - php

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>
';
}

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).

My search form does not seem to work

I want my search form to display users(username,firstname or lastname) from my database and display them as the user is typing like how facebook and twitter do but when i click search,nothing happens.Here are 2 parts of my header inc that deal with the search form,1st part:
<?php
include( "Connect.php" );
ob_start(); session_start();
if (isset($_SESSION['user_login'])) {
$user = $_SESSION["user_login"];
}
else {
$username = "";
}
$output = "";
//Collect
if(isset($_POST['search'])) {
$searchq = $_POST['search'];
$searchq = preg_replace("#[^0-9a-z]#i","",$searchq);
$query = $mysqli->query("SELECT * FROM users WHERE first_name LIKE '%$searchq%' OR last_name LIKE '%$searchq%'") or die("could not search!");
$count = mysqli_num_rows($query);
if($count == 0) {
$output = 'There was no search results!';
} else {
while($row = mysqli_fetch_array($query)) {
$fname = $row['first_name'];
$lname = $row['last_name'];
$id = $row['id'];
$output .= '<div> '.$fname.' '.$lname. '</div>';
}
}
}
?>
2nd part:
<form id="searchForm">
<fieldset>
<div class="input">
<p>
<form action="header inc.php" method="post">
<input type="text" class="Search" id="search" size="35" placeholder="Search username,fullname or topic"/>
<label for="Submit"></label>
<input type="submit" name="search" value="Go" id="search" />
</p>
</div>
</form>
<?php print ("$output"); ?>
invalid action name
action="header inc.php"
you cannot use space in .php files
Edit the filename as headerInc.php and pass it in the form as:
action="headerInc.php"
I have changed your html code , just use it and it will start working. In your html there is hierarchy of form tag , I have added method post to first form and I have replaced the name of the text field by submit button name. In each post your data value was "go".
I hope it will resolve your problem :
<form id="searchForm" method="post">
<fieldset>
<div class="input">
<p>
<form action="header inc.php" method="post">
<input type="text" class="Search" name="search" id="search" size="35" placeholder="Search username,fullname or topic"/>
<label for="Submit"></label>
<input type="submit" value="Go" id="search_button" />
</p>
</div>
</form>
<?php echo $output; ?>

How to perform same event on two different buttons?

I have this piece of code below, supposing it will display no request when no data in database and it will display the request with an accept and reject button when they is data in database. How should i write my code in order to make the accept and reject button perform some action?
<?php
$travelRequest = $user->userTravelRequest($userid);
if(!$travelRequest){
echo '<div class="requestbox">
<p> You have no request from others at the moment. </p>
</div>';
}
else {
foreach($travelRequest as $request){
echo '<div class= "requestbox">
<p>'. $request->trip_name.'</p>
<p>Organised by '.$request->username.'</p>';
?>
<form method="POST">
<div class = "AR-btn">
<input type="button" name="accept" value="Accept"/>
<input type="button" name="reject" value="Reject"/>
<p></p>
</div>
</form>
</div>
<?php
}
}
?>
Use type="submit" instead of type="button", and give them the same name. Then they'll submit the form, and the script can test which button was used from the value of that parameter.
<input type="submit" name="action" value="Accept"/>
<input type="submit" name="action" value="Reject"/>
You then test this with:
if (isset($_POST['action'])) {
if ($_POST['action'] == 'Accept') {
// Add to database
} elseif ($_POST['action'] == 'Reject') {
// Delete from database
}
}
Try this code :-
<?php
if (isset($_POST['accept']) && $_POST['accept'] == 'Accept' ) {
// do what you want
die("Accept is clicked");
} else if (isset($_POST['reject']) && $_POST['reject'] == 'Reject' ) {
// do what you want
die("Reject is clicked");
}
?>
<?php
$travelRequest = $user->userTravelRequest($userid);
if(!$travelRequest){
echo '<div class="requestbox">
<p> You have no request from others at the moment. </p>
</div>';
} else {
foreach($travelRequest as $request){
echo '<div class= "requestbox">
<p>'. $request->trip_name.'</p>
<p>Organised by '.$request->username.'</p>';
?>
<form method="POST">
<div class = "AR-btn">
<input type="submit" name="accept" value="Accept"/>
<input type="submit" name="reject" value="Reject"/>
<p></p>
</div>
</form>
</div>
<?php
}
}
?>
Just try this logic..may help you
$query = "select data from database";
.
.
.
$data = $row['data'];
if($data){ // reject button when they is data in database
echo '<input type="submit" name="action" value="Reject"/>';
}
else{ // viceversa
echo '<input type="submit" name="action" value="Accept"/>';
}

could not inserting data to mysql table using php

I have following form in html
<form method="post" enctype="multipart/form-data" />
<fieldset>
<legend>Activate Scheme</legend>
<p>Date Of Draw</p>
<p><input type="text" name="dateOfDraw" class="textBox" style="width:150px" /></p>
<p>Time Of Draw</p>
<p><input type="text" class="textBox" name="timeOfDraw" style="width:150px" /></p>
<p>Enter scheme name</p>
<p><input type="text" class="textBox" name="schemeName" style="width:150px" />
</p>
<p>Upload Image</p>
<p><input type="file" name="image" id="image" /></p>
<p><input name="scheme_button" type="submit" class="button1" value="Submit"></p>
</fieldset>
</form>
Problem is that their is no error when I execute the following query
<?php
if(isset($_POST['submit_button']) && count($_POST)>0) {
print_r($_POST);
$dateOfDraw = $_POST['dateOfDraw'];
$timeOfDraw = $_POST['timeOfDraw'];
$schemeName = $_POST['schemeName'];
$imageName = $_FILES['image']['name'];
$destination = '../images/'.$imageName;
$source = $_FILES['image']['tmp_name'];
if(move_uploaded_file($source, $destination)) {
echo 'file uploaded';
} else {
echo ' file not uploaded';
}
$sSQL = "INSERT INTO landing_page(dateOfDraw, timeOfDraw, schemeName, image) VALUES('$dateOfDraw','$timeOfDraw','$schemeName','$imageName')";
echo $sSQL;
if(!$sSQL){
die(mysqli_query($con));
}
mysqli_query($con,$sSQL);
//header("location: list_products.php");
}
?>
but when I check my data in a mysql database the rows are still empty. Please check it am I missing something or the php code is wrong.
Note: I am using php version 5.5.16
The name of your submit button is scheme_button and that's exactly the thing that you need to $_POST.
if(isset($_POST['scheme_button']) && count($_POST) > 0)
You form doesn't have an action and it doesn't know where to go. So add one.
<form method="post" action="index.php" enctype="multipart/form-data" />
firstly you have to name of submit button
if(isset($_POST['scheme_button']) && count($_POST) > 0)
secondly if insert code in same page then
if insert code in another page then
action = "filename"

PHP Chatbox : Cannot Send to MySQL Database

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.

Categories