If input exists from one table update it on another one - php

Im trying to make like a refill code that will refill my table.
I have one table that have my refill code in it and other table that stores the balance of the account.
table1: card_credit (table that stores the balance of the account)
table2:card_refill (table that have me refill code)
I have created this code with session and PHP. Now I'm stuck and dont know how to move forward.
I want to make when i write in the refill code from table card_refill that its take the amount of credit into value in table card_refill
refill.php
<strong>Refill</strong>
<form action="refill.php" method"post">
<input type="text" name="refillcode"/>
<br>
<input type="submit" name="Submit" value="Refill" />
</form>
<?php
// starting the session
session_start();
if (isset($_POST['Submit'])) {
$_SESSION['refillcode'] = $_POST['refillcode'];
}
?>

Here is a possible solution, I am just don't know, where the card_id comes from.
This is inserting a new record into your card_credit table.
// starting the session before any output
session_start();
//include here the database connection file!
//for example:
//include('db_connection.php');
if (isset($_POST['Submit'])) {
//First do a validation here, is the refillcode number, exists, etc...
//Insert it into the table
$sql = "INSERT INTO card_credit (card_id, value) VALUES ('[YOUR_CARD_ID_HERE]', " . intval($_POST['refillcode']) . ")";
//Link is the resource variable when you created the mysqli_connect
mysqli_query($link, $sql);
//Redirect here if you want
}
?>
<!-- HTML CODE STARTS HERE -->
<strong>Refill</strong>
<form action="refill.php" method="post">
<input type="text" name="refillcode"/>
<br>
<input type="submit" name="Submit" value="Refill" />
</form>

Related

Database isn't receiving values from form using php

Im trying to send form data to my sql database but the database isn't receiving any of my values. The name of my database is taxibooking and table name is bookings.
I tried separating the php code in another file and using action on form to access the php code. on clicking submit I was redirected to a blank page with my php file name.
<form method="POST" action="">
Name of customer:<input type="text" name="fname"><br><br>
Enter pickup address:<textarea name="padd" rows="5" cols="10"></textarea><br><br>
Enter destination address:<textarea name="dadd" rows="5" cols="10"></textarea><br><br>
Select Taxi type:<select name="taxi"><option value="Viennese Fiaker">The Viennese Fiaker</option><option value="Indian Auto Rickshaw">Indian Auto Rickshaw</option><option value="Little Yellow">Little Yellow</option><option value="Mumbai Taxi Fiat">Mumbai Taxi Fiat</option><option value="Tricycles">Tricycles</option><option value="Water Taxi">Water Taxi</option><option value="Impeccable Taxi">Impeccable Taxi</option><option value="Red Taxi">Red Taxi</option></select><br><br>
<input type="submit" value="submit" name="sub">
</form>
<?php
$con=mysqli_connect("localhost","root","","taxibooking");
if(isset($_POST['sub']))
{
$n=$_POST['fname'];
$p=$_POST['padd'];
$d=$_POST['dadd'];
$type=$_POST['taxi'];
$sql="insert into bookings(name,pickup,destination,type) values ('$n','$p','$d','$type')";
mysqli_query($con,$sql);
}
?>
Try to debug and put query on if condition
if(mysqli_query($con,$sql)){
echo'done';
}else{
echo "error".$sql."</br>" . mysqli_error($con);
}
Here's how to add parameters on your insert script.
$sql="insert into bookings(name,pickup,destination,type) values ('".$n."','".$p."','".$d."','".$type."')";
I made a new database with a different name with the same table name and properties and now it sort of mysteriously works now. No changes done to the code.

PHP update form that updates database information only if there is an input in that particular field using PDO

I am currently working on a form that uses PHP and SQL to update information in a database. It is functioning properly and updating the information but the issue is... is that it updates everything, including fields that I didn't even put any input in which means it will only update a particular row in the database and leave the others blanks... I need it to just change information from a field with an actual input and leave it if there is no input.
Here is the PHP and SQL code:
try {
$deleteRecId = $_GET['id'];
$update_event_name = $_POST['updateName'];
$update_event_location = $_POST['updateLocation'];
$update_event_date = $_POST['updateDate'];
include 'connect.php';
if(isset($_POST["submit"])) {
// new data
$sql = "UPDATE events SET event_name='$update_event_name',
event_location='$update_event_location', event_date='$update_event_date'
WHERE event_id=$deleteRecId";
// Prepare statement
$stmt = $conn->prepare($sql);
// execute the query
$stmt->execute();
// echo a message to say the UPDATE succeeded
echo $stmt->rowCount() . " records UPDATED successfully";
}
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
and here if the form:
<form class="update-form" action="<?php echo $_PHP_SELF ?>" method="post">
<p id="input-headers">Event Name</p>
<p id="update-input-field-wrapper">
<input type="text" name="updateName" value="">
</p>
<p id="input-headers">Event Location</p>
<p id="update-input-field-wrapper">
<input type="text" name="updateLocation" value="">
</p>
<p id="input-headers">Event Date</p>
<p id="update-input-field-wrapper">
<input type="text" name="updateDate" value="" placeholder="01/01/2000">
</p>
<input type="submit" name="submit" value="Submit" id="updateBtn">
</form>
So to sum up I need this application to only update information of a field with an actual input and if the form field has no input I need that database info to remain the same. I appreciate any help with this as I am pretty new to these concepts... thanks!
I found a really handy solution to this! Here is how I implemented it into my code.
$sql = "UPDATE events SET event_name=IF(LENGTH('$update_event_name')=0, event_name, '$update_event_name'), event_location=IF(LENGTH('$update_event_location')=0, event_location, '$update_event_location'), event_date=IF(LENGTH('$update_event_date')=0, event_date, '$update_event_date') WHERE event_id=$deleteRecId";
It basically just checks whether the string is empty or not. If it's empty it won't be updated. If it isn't empty it'll go through with the update! Very simple way to achieve this effect when creating an update form.
Using your current code structure, you can do this.
Use SQL to select * from event ID. Populate your update_event_xxx with the parameters.
If $_POST[xx] is blank, ignore. Else, update_event_xx = $_POST[xx]

how to update mySQL database using a post method in php

i have created a leaderboard for a website which displays users high scores for a game. but whe the user goes to edit their high score, it doesnt change in the database or on the screen. does anybody know how to update the database using a post method. my code is below.
require_once('../sokodatabase.php');
//require_once('../sokodatabase.php');
//require_once('../sokodatabase.php');
if(isset($_POST['userId'])){
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$query = "
UPDATE leaderboardhighscores
SET highScores=".$_POST["highScores"].", rankNo=".$_POST["rankNo"]."
WHERE userId=".$_POST["userId"];
var_dump($_POST);
echo $query;
#mysqli_query($dbc, $query);
}
}
$manager = new DatabaseManager;
$manager->SelectHighScores();
?>
<form method="post" action="highScores.php">
high score <input type="text" name="highScores"/>
rankNo <input type="text" name="rankNo"/>
userId <input type="text" name="userId"/>
<input type="submit" value="Submit">
</form>
You have to provide attention to SQL injections!
Normally, you check for the submit button:
<input type="submit" name="submit" value="Submit">
Then
if(isset($_POST['userId'])){
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
goes to:
if(isset($_POST['submit'])){
If your query does not work, you can make die($query) to see it and perform it via phpMyAdmin. Or you can use mysqli_error to display any occured error after executing it.
Please note, that with your code only numeric values are possible. If your fields are not numeric, you should use this:
$query = "
UPDATE leaderboardhighscores
SET highScores='".mysqli_real_escape_string($dbc, $_POST["highScores"])."', rankNo='".mysqli_real_escape_string($dbc, $_POST["rankNo"])."'
WHERE userId=".intval($_POST["userId"]);
Need name for the submit input type in-order to submit the form...
Like
<input type="submit" name="userId" value="Submit">
if(isset($_POST['userId']))

How do I add a row to mySQL using PHP?

I am trying to add an "admin" section of my website. Right now I am working on a section to add a new row to my MySQL database.
The first file is my admin.php:
<html>
...
<body>
<form action="add.php" method="post">
<input type="text" name="order" />
<input type="text" name="newstatus" />
<input type="submit" value="Add" />
</form>
</body>
</html>
My goal here is to add 2 pieces of data (the table only has 2 columns right now) to the new row.
Then, I have my add.php file:
<?
//declare my connection variables - I'll move these to a secure method later
mysql_connect($servername, $username, $password) or die (mysql_error ());
// Select database
mysql_select_db($dbname) or die(mysql_error());
// The SQL statement is built
$sql="INSERT INTO $tblname(id, status)VALUES('$order', '$newstatus')";
$result=mysql_query($sql);
if($result){
echo "Successful";
echo "<BR>";
echo "<a href='admin.php'>Back to main page</a>";
}
else {
echo mysqli_errno($this->db_link);
}
?>
<?php
// close connection
mysql_close();
?>
Anytime i input any data (non-duplicate of what is already in the table), it gives me an error. If I clear my table completely of all data, it will input once. I am getting a duplicate key error, but my key should be "orders", which is unique every time I input it.
Suggestions?
If you are actually inserting a new row, you shouldn't fill the ID yourself but rather set it as AUTO_INCREMENT in your database. And then, have you form as such:
<form action="add.php" method="post">
<input type="text" name="newstatus" />
<input type="submit" value="Add" />
</form>
And your PHP code like so:
$newstatus = mysql_real_escape_string($_POST['newstatus']); // note the usage of $_POST variable
$sql="INSERT INTO `$tbl_name` (`status`) VALUES ('$newstatus')";
$result = mysql_query($sql) or die('Failed executing query: '.mysql_error());
AUTO_INCREMENT can be set up in phpMyAdmin with the following query:
ALTER TABLE `WorkOrders` MODIFY `id` INTEGER NOT NULL AUTO_INCREMENT;
Finally, don't use mysql_* functions, they are deprecated.
I am guessing the 'id' field of your table is a primary key. If that's the case, you cannot have two rows that have the same identifier.
By your variable name newstatus, it seems to me like you're trying to update the status of an order ; is it the case? If yes, you should use a UPDATE SQL query of the form:
UPDATE table SET status='somestatus' WHERE id=someid

php mysql; writing data to database

having a bit of trouble adding some data to a database. I have the file new_entry.php which is a form, which posts the data added to insert_new.php.
Every time the fields are filled in and submitted the data does not go to the database with the error message "Could not add the data to table" appearing..any ideas?
NEW_ENTRY.PHP
<body>
<form method="post" action="insert_new.php"><!-- form sent to insert_new.php-->
Section: <input type="text" name="section"/><br />
Food: <input type="text" name="food"/><br />
Description: <input type="text" name="description"/><br />
Price: <input type="text" name="price"/><br />
<br />
<input type="submit" value="submit"/>
</form>
</body>
INSERT_NEW.PHP
<?php
include 'library/connect.php';//connect to databse
$section = $_REQUEST["section"]; // get data from the HTML form on new student form
$food = $_REQUEST["food"];
$description = $_REQUEST["description"];
$price = $_REQUEST["price"];
mysql_query ("INSERT INTO food_menu (section, food, description, price) VALUES ('$section', '$food', '$description', $price)")/* insert the data to the food_menu table*/
or die ("Could not add the data to table");//error message
header('Location:index.php');//auto redirect to view page
include 'library/closedb.php';
?>
It seems that you have a mistake at the end of your MySQL query near price.
Please replace the code below with existing line:
mysql_query ("INSERT INTO food_menu (section, food, description, price) VALUES ('$section', '$food', '$description', '$price')")
Tell me the result please.
First: Don't do this. You really need to research SQL Injection or you will be very sorry.
Secondly, your price has no numeric validation (assuming it's going into a numeric column)... this is also bad... what if someone put in a dollar sign or something?
Next, please post your table definition and connection code (not the connection values).
You can also get more feedback if you do something like:
or die (mysql_error());//error message

Categories