I have a table called client and I am trying to update the contact number, but for only the id that is typed in. I have a form that creates two textfields for the data to be changed. My problem is im unsure on how i can only update data for only the id that is entered.
Code:
<form method="post" name="update" >
Client ID:
<br>
<input type="text" name="clientid"><br>
Contact Number:
<br>
<input type="text" name="contactno"><br>
<input type="submit" name="submit" value="Update"><br><br>
</form>
<?php
if(isset($_POST['submit'])){
$client = $_POST['clientid'];
$contact = $_POST['contactno'];
$result= $pdo->prepare ("UPDATE client SET client_contact_number='$contact' WHERE client_id='$client'");
$result->execute;
}
?>
your syntax should be:
mysqli_query($connection, $sql_query)
you're missing the $connection object in your method.
PHP docs: http://php.net/manual/en/mysqli.query.php
*Original version of this question used procedural syntax - hence my answer.
Related
This question already has answers here:
Why shouldn't I use mysql_* functions in PHP?
(14 answers)
Closed 1 year ago.
I am trying to insert data into a database from HTML form using php. I made two files html form and other is PHP script. When I click on submit in html form, it shows me the php code. I am using wamp server for database. I put my html files in C:/wamp64/www directory and html files at my local directory. The database table is :
id int(11)
fname varchar(30)
salary int(11) . Id is not auto-incremented and it is a primary key.
Html code:
<html>
<body>
<h2>Employee's Information</h2>
<form action="employee.php" method="POST">
<label for="id">Enter employee id:</label><br>
<input type="text" id="id" name="id" value=""><br>
<label for="fname">Enter First name:</label><br>
<input type="text" id="fname" name="fname" value=""><br><br>
<label for="salary">Enter Employee Salary:</label><br>
<input type="text" id="salary" name="salary" value=""><br><br>
<input type="submit" id="submit" name="submit" value="Submit">
</form>
</body>
</html>
Php code:
<?php
$mysql_hostname="localhost";
$mysql_username="root";
$mysql_password="";
$mysql_database="employee";
$con=mysql_connect($mysql_hostname,$mysql_username,$mysql_password);
if(!$con){
die('Connection Error: '.mysql_error());
}
mysql_select_db($mysql_database, $con);
if(isset($_POST['submit']))
{
$s_id = $_POST['id'];
$s_name = $_POST['fname'];
$salary = $_POST['salary'];
$employeeinsert = "INSERT INTO employee1
(id, fname, salary)
VALUES('".$s_id."','".$s_name."','".$salary."')";
if(!mysql_query($employeeinsert,$con)) {
echo "Error: " .mysql_error($con);
} else {
echo "1 record added";
}
}
?>
The code is neither giving any error on submitting data nor it is inserting the data into the database.
I am not getting what the error is.
If this is false then the code successfully produces no output:
if(isset($_POST['submit']))
Which is what's happening, since the condition is false. The form has a submit button, but that button has no name attribute to its value isn't sent to the server:
<input type="submit" value="Submit">
Give it a name:
<input type="submit" name="submit" value="Submit">
It's always a good idea to have some kind of indication of any given code branch, even if just logging something somewhere so you can see what's happening. Code will happily produce no output/result if that's what it's instructed to do, but as you've discovered it can leave you with no information about what's happened.
As an aside, and this is important, your code is wide open to SQL injection. You'll want to start addressing that.
i just learned about this new insert script into my database to avoid mysql injections.. but of some reason it doesn't work... My charts name is messages and then i got id and message as the text i want to come to the database...
Here is my new code:
<?php
$meddelanden = $_POST['message'];
$namn = $_SESSION['user'];
include ("connect.php");
$sql = $con->prepare('INSERT INTO messages (message,namn) VALUES (?,?)');
$sql->bind_param("ss",$meddelanden,$namn);
$sql->execute();
$sql->close();
$con->close();
?>
<form action = "meddelanden.php" id = "fromen2" method = "post">
<input type="text" name="message" id = "type" autocomplete="off"
placeholder="type your chat message">
<input type="submit" name="submit" value="Send">
</form>
Please explain what im doing wrong, i wont approve the answer if you just say what i should do instead! Thanks for any help!
You should replace si with s since you are binding only one string in it and no integers ( if $meddelanden is not an integer). Use this instead
$sql->bind_param("s",$meddelanden);
S is string, I is integer. By putting SI you are stating two variables are being passed.
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']))
So I'm creating a small program with 2 forms, one to add data to a database, and one to delete from it. I've managed to create the first input form, but I'm slightly confused as to how I would get the second form to work. In the database "tasks" I have a table called "ID" which has the columns "ID", "Name" and "Hours"
Here's what the two HTML forms look like
<h2>Add Tasks</h2>
<form action="test.php" method="get">
Name of Task: <input type="text" name="name"><br />
Hours: <input type="number" name="hours"><br />
<input type="submit" value="Add" name="submit">
</form>
<h2>Delete Tasks</h2>
<form action="delete.php" method="get">
ID: <input type="number" name="ID"><br />
<input type="submit" value="Delete">
</form>
And the PHP for the first form "Add tasks" which inserts data
$servername = "localhost";
$username = "root";
$password = "root";
$conn = new mysqli($servername, $username, $password, "Tasks");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
};
if (isset($_GET['submit'])) {
mysqli_select_db ($conn,"Tasks");
$name = $_GET['name'];
$hours = $_GET['hours'];
$sql = "INSERT INTO ID (Name, Hours) VALUES ('".$name."','". $hours."')";
$results = mysqli_query($conn,$sql);
$query = "SELECT `Name` FROM `ID`";
$result = mysqli_query($conn, $query);
$x=0;
And the PHP for the second form which deletes tasks. This is the part that is not working
if (isset($_GET['submit'])) {
mysqli_select_db ($conn, "Tasks");
$id = $_GET['id'];
$sql = "DELETE FROM ID (ID) VALUES ('".$id."')";
$query = "SELECT `Name` FROM `ID`";
$result = mysqli_query($conn, $query);
$x=0;
How should I format the PHP for the second button. I've basically reused the code for the first form. Do I need to differentiate it somehow from the first button? Currently the page is showing up completely blank. I'm a complete novice so any help would be appreciated.
Your SQL Statement
"DELETE FROM ID (ID) VALUES ('".$id."')"
is wrong.
It should be
DELETE FROM table_name
WHERE some_column=some_value;
. So, change your statement to
DELETE FROM ID WHERE ID='$id'
Suggestions
You should use POST method for action which will result in data edit.
You should check the input, make sure it did not contain SQL statement. A good way is to use $stuff = mysql_real_escape_string($_GET["stuff"]).
I see you have name 'ID' in the form but your are trying to get 'id'. That could be the problem
The sql statement for deletion should look something like the snippet below.
$sql = "DELETE FROM ID WHERE `id`=".$id.";";
$results = mysqli_query($conn,$sql);
In addition to above answers you should give different name to the both form input tags as
<h2>Add Tasks</h2>
<form action="test.php" method="get">
Name of Task: <input type="text" name="name"><br />
Hours: <input type="number" name="hours"><br />
<input type="submit" value="Add" name="submit">
</form>
<h2>Delete Tasks</h2>
<form action="delete.php" method="get">
ID: <input type="number" name="ID"><br />
<input type="submit" value="Delete" name="delete">
</form>
So for adding into database , you can use
if (isset($_GET['submit'])){
// your code here
}
And for deleting from database , you can use
if (isset($_GET['delete'])){
mysqli_select_db ($conn, "Tasks");
$id = $_GET['id'];
$sql = "DELETE FROM ID (ID) WHERE ID='".mysql_real_escape_string($id)."' ;
$query = "SELECT `Name` FROM `ID`";
$result = mysqli_query($conn, $query);
$x=0;
}
This will solve all the problems.
If you are using same name for the type="submit" in both forms than you can use POST method on one form and GET method on the other.
And yes mysql_real_escape_string is used to prevent SQL INJECTION.
I am attempting to create a form where an admin can update a webpage's data. I am taking the form's $_POST variables and sending them to the handler (in this case, UpdateInfo_SA.php). From there I am trying to send it to the database (see snippet 1). There is no error, in fact the page is blank (which is expected, given the current code). However, the table does not update.
Info:
Table Name: LOGISTICS_SLIDESHOW
Updating OH_RECORDABLE_ENERGY to any value (just to test to see if this works) where LOGISTICS_UPDATEID=0 (this represents the first column of the table).
Snippet 1 (Form Handler - UpdateInfo.php):
<?php
require_once("mcl_Oci.php");
$objConnect = oci_connect("user", "pass", "(description=(address=(protocol=tcp)(host=HOST)(port=1533))(connect_data=(service_name=SID)))")
$strSQL = "UPDATE INTOXDM.LOGISTICS_SLIDESHOW ";
$strSQL .="SET OH_RECORDABLE_ENERGY = '6'";
$strSQL .="WHERE LOGISTICS_UPDATEID= 0 ";
$objParse = oci_parse($objConnect, $strSQL);
$objExecute = oci_execute($objParse, OCI_DEFAULT);?>
Snippet 2 (Form - SA_Update.php):
<?php
$objConnect = oci_connect("user", "pass", "(description=(address=(protocol=tcp)(host=HOST)(port=1533))(connect_data=(service_name=SID)))");
?>
<div align="center">
<span style="font-size:60px";>
<u>Update Page<br></u>
Schedule Adherence: OH Contractors<br>
</span>
<form method="post" action="UpdateInfo_SA.php">
<span style="font-size:30px;">
<u>Total YTD:<input type="number" name="SA_ytd_total" value="%"><br>
Total MTD:<input type="number" name="SA_mtd_total" value="%"><br>
Energy YTD: <input type="number" name="SA_ytd_energy" value="total"><br>
Energy MTD: <input type="number" name="SA_mtd_energy" value="total"><br>
Hydraker YTD: <input type="number" name="SA_ytd_hydraker" value="total"><br>
Hydraker MTD: <input type="number" name="SA_mtd_hydraker" value="total"><br>
NG Gilbert YTD: <input type="number" name="SA_ytd_gilbert" value="total"><br>
NG Gilbert MTD: <input type="number" name="SA_mtd_gilbert" value="total"><br></u>
<input type="submit" value="Submit">
</form>
As you can tell, the server is using php's to communicate with itself and the database. Thanks for any help you can give, it is very appreciated!!
Do you commit the transaction in your php, where open up the connection and update ?
Unless autocommit is turned ON or you commit ,the updated data is not available to the rest of world
EDIT: http://www.php.net//manual/en/function.oci-execute.php
The above link refers to the auto commit options available. Default is NO auto commit.. So all updates are rollbacked when the session is disconnected.