I have this chunk of code running PHP on my webpage. I must have one small thing wrong, because when I hit the submit button on the form on this page it doesn't do anything! It has been driving me bonkers for hours.
Here is the form:
<form method="POST">
<strong><br>
</strong><p><input name="creaturein" type="hidden" value="Goblar"><br>
</p><table style="border: 1px;">
<tbody><tr>
<td></td>
<td>Creature</td>
<td>Stage</td>
<td>Gender</td>
<td>Frozen</td>
</tr>
<tr>
<td rowspan="2"><img src="http://static.eggcave.com/90by90/goblar_2.png"></td>
<td>Goblar</td>
<td><select name="stagein"><option selected="" disabled="">Unspecified</option><option value="Unspecified">Unspecified</option><option value="Stage1">Stage 1(Egg)</option><option value="Stage2">Stage 2</option><option value="Stage3">Stage 3</option><option value="Stage4">Stage 4</option></select></td>
<td><select name="genderin"><option selected="" disabled="">Unspecified</option><option value="Unspecified" selected="">Unspecified</option><option value="Female">Female</option><option value="Male">Male</option></select></td>
<td><select name="frozenin"><option selected="" disabled="">Unspecified</option><option value="Unspecified">Unspecified</option><option value="Yes">Yes</option><option value="No">No</option></select></td>
</tr><tr>
<td colspan="2">Notes: <input name="notesin" type="text" value=""></td>
<td><input name="update" type="submit" id="update" value="Update"></td>
<td><input name="delete" type="submit" id="delete" value="Delete"></td>
</tr>
</tbody></table>
</form>
And here is the code that should be updating the table:
// Info to connect to the Wishlist database
$servername = "****";
$dbusername = "****";
$password = "****";
$dbname1 = "****";
$dbname2 = "****";
// To connect to the database please
$conn = mysqli_connect($servername, $dbusername, $password, $dbname1);
// If unable to connect to the database display this error
if ($conn->connect_error) {
echo "Connection to wishlist failed";
die("Connection failed: " . $conn->connect_error);
}
// Get current user's username
$current_user = wp_get_current_user();
$username = $current_user->user_login;
if(isset($_POST['update'])){
$stage = $_POST['stagein'];
$gender = $_POST['genderin'];
$frozen = $_POST['frozenin'];
$notes = $_POST['notesin'];
$creature = $_POST['creaturein'];
$sql2 = 'UPDATE $username SET Stage = "$stage" AND Gender = "$gender" AND Frozen= "$frozen"' .
' AND Notes = "$notes" WHERE Creature = "$creature"';
if ($conn->query($sql2) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
// To connect to the database please
$conn2 = new mysqli($servername, $dbusername, $password, $dbname2);
// If unable to connect to the database display this error
if ($conn2->connect_error) {
echo "Connection to Creatures failed";
die("Connection failed: " . $conn2->connect_error);
}
$sql3 = "SELECT Stage$stage FROM Creatures WHERE Name = '$creature'";
if ($conn2->query($sql3) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn2->error;
}
$sql4 = "UPDATE $username SET Picture='$retval' WHERE Creature = '$creature'";
if ($conn->query($sql4) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
$conn2->close();
}
And the delete button doesn't work either.
if(isset($_POST['delete'])){
$stage = $_POST['stagein'];
$gender = $_POST['genderin'];
$frozen = $_POST['frozenin'];
$notes = $_POST['notesin'];
$creature = $_POST['creaturein'];
$sql5 = "DELETE FROM $username WHERE Creature = '$creature' AND Stage = '$stage' AND " .
"Gender = '$gender' AND Frozen = '$frozen' AND Notes = '$notes'";
if ($conn->query($sql5) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
}
// Close the connection to the database
$conn->close();
I'm not getting any error messages. I'm just so lost. SOS!
---------------------------------------------------------------------------
---------------------------------------------------------------------------
I have this! This is working for the most part
if(isset($_POST['update'])){
// prepare and bind
$stmt = $conn->prepare("UPDATE " . $username. " SET Stage = ?, Gender = ?, Frozen = ?, Notes = ? WHERE Creature = ?");
$stmt->bind_param('sssss', $stagebind, $genderbind, $frozenbind, $notesbind, $creaturebind);
// set parameters and execute
$stagebind = $_POST['stagein'];
$genderbind = $_POST['genderin'];
$frozenbind = $_POST['frozenin'];
$notesbind = $_POST['notesin'];
$creaturebind = $_POST['creaturein'];
$stmt->execute();
$stmt->close();
exit();
// To connect to the database please
$conn2 = mysqli_connect($servername, $dbusername, $password, $dbname2);
// If unable to connect to the database display this error
if ($conn2->connect_error) {
echo "Connection to Creatures failed";
die("Connection failed: " . $conn2->connect_error);
}
// prepare and bind
$stmt2 = $conn2->prepare("SELECT ? FROM Creatures WHERE Name = ?");
$stmt2->bind_param('ss', $stagebind, $creaturebind);
// set parameters and execute
$creaturebind = $_POST['creaturein'];
$stmt2->bind_result($picture);
$stmt2->fetch();
Until about here. It isn't saving the $picture information in my wishlist database.
// prepare and bind
$stmt3 = $conn->prepare("UPDATE " . $username . " SET Picture = ? WHERE Creature = ?");
$stmt3->bind_param('ss', $picture, $creaturebind);
// set parameters and execute
$creaturebind = $_POST['creaturein'];
$stmt3->execute();
$stmt3->close();
$stmt2->close();
$conn2->close();
}
You forgot to add <form method="POST">.By default, when the method is not added, the html consider form method='GET'.
UPDATE: You forgot to add the first parameter which is to used to inform the types of the fields.See below:
$stmt->bind_param('sssss',$stagebind, $genderbind, $frozenbind, $notesbind, $creaturebind);
UPDATE 2: Remove the exit(). Another adjustment, the question mark to retrieve colums wont work, use only the question mark in the where condition. See below:
// prepare and bind
$stmt2 = $conn2->prepare("SELECT $stagebind FROM Creatures WHERE Name = ?");
$stmt2->bind_param('s',$creaturebind);
Please see that your HTML form code doesn't state the form action or the method.
Try this:
<form action ="" method="POST">
If you don't mention this method, it's assumed that the method is GET, and therefore, your isset($_POST[...]) code isn't executed.
How isn't anyone flipping about those variables being used directly into a query? Seriously, please use prepared statements otherwise SQL injection will most likely to occur.
Related
I am trying to input data into a MySQL Database using PHP and a HTML Form but the data isn't saved into the database even though it shows that it has. Please show me how to ensure the form entries save to the database.
HTML
<form action="newproduct.php" method="post">
<table>
<tr>
<td>Username</td>
<td><input name="user" type="text"></td>
</tr> ...
<button type="submit">Go</button>
</form>
PHP
<?php
$servername = "localhost";
$username = $_POST["user"];
$password = $_POST["pass"];
$dbname = "bakefree_products";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO ".$_POST["range"]." (productname, image, frompricesize, paypalcode, productdesc, allergystandard, allergyglutenfree, allergyvegan, allergygfvegan)
VALUES ('".$_POST["productname"]."', '".$_POST["image"]."', '".$_POST["frompricesize"]."', '".$_POST["paypalcode"]."', '".$_POST["productdesc"]."', '".$_POST["allergystandard"]."', '".$_POST["allergyglutenfree"]."', '".$_POST["allergyvegan"]."', '".$_POST["allergygfvegan"]."')";
if (mysqli_query($conn, $sql)) {
echo "New product created successfully.";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
//show new number of products
$sql = "SELECT * FROM".$_POST["range"];
$result = $conn->query($sql);
if ($result->num_rows > 0) {echo "There are ".$result->num_rows ." products.";
} else {
echo "<br><br>There are no products in ".$_POST["range"];
}
mysqli_close($conn);
?>
RESULT
New product created successfully.
There are no products in TEST
Actually insertion should be working fine but you need to check the syntax of the select query here,
//show new number of products
$sql = "SELECT * FROM ".$_POST["range"]; // Added a space after `FROM`
And it should fetch data properly and show you the string, There are X products.
I'm trying to insert new record to SQL database using PHP from a HTML form.
I made a form using Post method
<form name="CreatNewMCQ" action="create.php" method="POST">
with a button to submit
<button type="submit" form="CreateNewMCQ">CREATE</button>
what I want to do is when I press the button, it will call create.php which is
<?php
$servername = "localhost";
$user = "admin";
$pass = "admin";
$dbname = "examples";
// Create connection
$conn = new mysqli($servername, $user, $pass, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$id = $_POST['id'];
$name = $_POST['name'];
$year = $_POST['year'];
$sql = "INSERT INTO cars (id, name, year)
VALUES ($id, $name, $year)";
if ($conn->query($sql) === TRUE) {
echo "Tạo mới thành công";
} else {
echo "Lỗi: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
then insert data from form to SQL database (id, name, year from the form).
I got some errors in SQL syntax. What mistake did I make?
Make sure all post values are getting correctly. You should make a condition check before inserting the data, For ex:
$id = isset($_POST['id']) ? $_POST['id'] : '';
$name = isset($_POST['name']) ? $_POST['name'] : '';
$year = isset($_POST['year']) ? $_POST['year'] : '';
if($id && $name && $year){
$sql = "INSERT INTO cars (id, name, year)
VALUES ($id, '$name', '$year')";
}else{
return "required fields are missing";
}
NB: Please post your html if possible.
try this:
<?php
/* Attempt MySQL server connection.*/
$servername = "localhost";
$user = "admin";
$pass = "admin";
$dbname = "examples";
$link = mysqli_connect($servername, $user, $pass, $dbname);
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Attempt insert query execution
$id = $_POST['id'];
$name = $_POST['name'];
$year = $_POST['year'];
$sql = "INSERT INTO cars (id, name, year)
VALUES ($id, '$name', '$year')";
if(mysqli_query($link, $sql)){
echo "Records inserted successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Close connection
mysqli_close($link);
?>
HTML Form :
<html>
<form name="test" method="post">
Enter name:<input type="text" name="name"/> <br>
Enter year :<input type="text" name="year"/><br>
<input type="submit" name="save" value="save" />
</form>
</html>
php code :
<?php
$conn=mysql_connect("localhost","root","passward");
$select_db=mysql_select_db("Atul",$conn);
if($conn)
{
echo "connected";
}
else
{
echo "Please try again";
}
if(isset($_POST['save']))
{
$name=$_POST['name'];
$year=$_POST['year'];
$insert_record="insert into test (name,year) values("$name","$year");
$result=mysql_query($insert_record);
if($result)
{
echo "Record inserted successfully";
}
else
{
echo "please try again";
}
}
?>
I'm quite new to PHP and an absolute beginner when it comes to SQL. I'm just learning the basics and I can't get my head around why my code is generating a duplicate entry every time the form is submitted, e.g.
Name: Joe Blogs Email: info#email.co.uk
Name: Joe Blogs Email: info#email.co.uk
The database has a table called user and two columns, name and email.
My index file looks like this, it has a simple form for name and email, and inserts the data on submit:
<form method="post" action="insert.php">
<input name="name" type="text">
<input name="email" type="email">
<input type="submit" value="Submit Form">
</form>
<?php
$servername = "localhost";
$username = "DB_USER";
$password = "PASSWORD";
$dbname = "DB_NAME";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sqlout = "SELECT name, email FROM user";
$result = $conn->query($sqlout);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<b>Name:</b> " . $row["name"]. " <b>Email:</b> " . $row["email"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
<form method="post" action="wipe.php">
<input type="submit" value="Wipe ALL Data">
</form>
This insert.php file is called when the form is submitted:
<?php
$servername = "localhost";
$username = "DB_USER";
$password = "PASSWORD";
$dbname = "DB_NAME";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO user ( name, email ) VALUES ( '{$conn->real_escape_string($_POST['name'])}', '{$conn->real_escape_string($_POST['email'])}' )";
$insert = $conn->query($sql);
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Back
I've probably made some basic mistakes but I'm not sure why it is adding duplicates. Is it something to do with connecting twice to the database in each file? Is there a better way to connect only once? Or is it caused by the form submission itself?
Because you call query twice:
$insert = $conn->query($sql);
if ($conn->query($sql) === TRUE) {
You should rewrite is as
$insert = $conn->query($sql);
if ($insert === TRUE) {
Also, you should really be using prepared statements.
Your code Call $conn->query twice
$insert = $conn->query($sql);// first time
if ($conn->query($sql) === TRUE) {// second time
if ($insert === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
You need change:
$sql = "INSERT INTO user ( name, email ) VALUES ( '{$conn->real_escape_string($_POST['name'])}', '{$conn->real_escape_string($_POST['email'])}' )";
$insert = $conn->query($sql);
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
to
$sql = "INSERT INTO user ( name, email ) VALUES ( '{$conn->real_escape_string($_POST['name'])}', '{$conn->real_escape_string($_POST['email'])}' )";
$status = $conn->query($sql);
if ($status === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
I have a html form, say example
<form action="form.php" method="post">
First name:<br>
<input type="text" id="fname" name="fname">
<br>
Last name:<br>
<input type="text" id="lname" name="lname">
<br><br>
<input type="submit" value="Submit">
</form>
and form.php
<?php
$servername = "localhost";
$username = "database1";
$password = "xxxxxxxx";
$dbname = "database1";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//escape variables for security
$fname = mysqli_real_escape_string($conn, $_POST['fname']);
$lname = mysqli_real_escape_string($conn, $_POST['lname']);
$sql = "INSERT INTO mytable (fname,lname)
VALUES ('$fname','$lname')";
if ($conn->query($sql) === TRUE) {
echo "Successfully Saved";
} else {
echo "Error: Go back and Try Again ! " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
The form.php is saving that data to database1 .
I want that data to be saved to another database database2 along with database1.
Is it possible ?? If yes then what changes should be made in the code ?
If it is not possible then is it possible to copy data from database1 to database2 automatically? Whenever a new row is added in database1 then it should automatically copied to database2.
I want the same data to be in two different database. How can I achieve any of the above said ??
From php you just have to create new connection to DB.
<?php
$servername = "localhost";
$username = "database1";
$password = "xxxxxxxx";
$dbname = "database1";
$servernameS = "localhost";
$usernameS = "database2";
$passwordS = "xxxxxxxx";
$dbnameS = "database2";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
$connS = new mysqli($servernameS, $usernameS, $passwordS, $dbnameS);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if ($connS->connect_error) {
die("Connection failed: " . $connS->connect_error);
}
//escape variables for security
$fname = mysqli_real_escape_string($conn, $_POST['fname']);
$lname = mysqli_real_escape_string($conn, $_POST['lname']);
$sql = "INSERT INTO mytable (fname,lname)
VALUES ('$fname','$lname')";
if ($conn->query($sql) === TRUE) {
echo "Successfully Saved";
} else {
echo "Error: Go back and Try Again ! " . $sql . "<br>" . $conn->error;
}
if ($connS->query($sql) === TRUE) {
echo "Successfully Saved";
} else {
echo "Error: Go back and Try Again ! " . $sql . "<br>" . $connS->error;
}
$conn->close();
$connS->close();
?>
What it sounds like you need is to setup replication.
Here is the official documentation on replication. Here is a simpler step-by-step guide setting it up.
If replication isn't what you wanted, you could accomplish the same thing by connecting to database2 in addition to database1 then running the query once on both.
You can use something like using mysqli::selectDB method:
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "test");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
/* return name of current default database */
if ($result = $mysqli->query("SELECT DATABASE()")) {
$row = $result->fetch_row();
printf("Default database is %s.\n", $row[0]);
$result->close();
}
/* change db to world db */
$mysqli->select_db("world");
/* return name of current default database */
if ($result = $mysqli->query("SELECT DATABASE()")) {
$row = $result->fetch_row();
printf("Default database is %s.\n", $row[0]);
$result->close();
}
$mysqli->close();
?>
Check out the manual.
Similar question as yours at SO.
I'm having problem with updating information in database. The echo pops out as successful but the database row stays blank - why? PHP code:
<?php
if (isset($_POST['gender'])) {
// Sanitize and validate the data passed in
$gender = filter_input(INPUT_POST, 'gender', FILTER_SANITIZE_STRING);
if ($stmt) {
$stmt->bind_param('s', $gender);
$stmt->execute();
$stmt->store_result();
if ($insert_stmt = $mysqli->prepare("INSERT INTO members gender VALUE ?")) {
$insert_stmt->bind_param('s', $gender);
}
}
echo "<div class='notemarg'> Your gender has been submitted</div>";
}
?>
and input form:
<form action="" method="POST">
<input type="radio" name="gender" value="male"> Male <br>
<input type="radio" name="gender" value="female"> Female <br>
<input type="submit" name="gender" value="Set gender" class="button">
</form>
I want to use mysqli->prepare to prevent SQL injection.
I fixed it with alternative way, where there is pre-defined input by button.
<?php
$servername = "";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if (isset($_POST['Female'])) {
$gender = $_POST['Female'];
$sql = "UPDATE members SET gender = '$gender' WHERE username = '".$_SESSION['username']."'";
if ($conn->query($sql) === TRUE) {
echo "<div class='notemarg'> Your gender has been submitted</div>";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
?>
And simple form:
<form action="" method="POST">
<input type="submit" name="Female" value="Female" class="button">
</form>
Thanks to all who wanted to help me, especially to anant kumar singh. I could not get that alter idea without his suggestions. Thanks!
UPDATE #1
It just pops out that echo "error"
<?php
if(isset($_POST['Female'])){
$servername = "";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if (isset($_POST['Female'])) {
$gender = $_POST['Female'];
$stmt = $conn->prepare('UPDATE members
SET gender = ?
WHERE username = ?');
$stmt->bind_param('s', $_POST['Female']);
$stmt->bind_param('s', $_SESSION['username']);
if ($conn->prepare === TRUE) {
echo "<font color='#00CC00'>Your gender has been updated.</font><p>";
} else {
echo "Error: " . $conn->prepare . "<br>" . $conn->error;
}
$conn->close();
}
}
?>
Don't know where is problem...
UPDATE #2
if(isset($_POST['Female'])){
$servername = "";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if (isset($_POST['Female'])) {
$gender = $_POST['Female'];
$sql = "
UPDATE members
SET gender = ?
WHERE username = ?
";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param('s', $_POST['Female']);
$stmt->bind_param('s', $_SESSION['username']);
$stmt->execute();
if ($mysqli->prepare($sql) === TRUE) {
echo "<font color='#00CC00'>Your gender has been updated.</font><p>";
} else {
echo "Error: " . $conn->prepare . "<br>" . $conn->error;
}
$conn->close();
}
}
UPDATE #3
I added also some notes in code so
<?php
// I had here twice the ifisset here and
if(isset($_POST['Female'])){
$servername = "";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//here the second one so I deleted that ifisset here...
$gender = $_POST['Female'];
$sql = "
UPDATE members
SET gender = ?
WHERE username = ?
";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param('s', $_POST['Female']);
$stmt->bind_param('s', $_SESSION['username']);
$ok = $stmt->execute();
if ($ok == TRUE) {
echo "<font color='#00CC00'>Your gender has been updated.</font><p>";
} else {
echo "Error: " .$stmt->error; // This is the line that shows the error
}
$conn->close();
}
?>
I'm not sure what is problem... It pops the error on echo "No data supplied for parameters in prepared statement"
Following an answer being posted with a huge security vulnerability, it is worth taking a moment to fix this. There is a way to fix it so you can use your string concatenation approach, but it is generally not as good as parameterisation.
All you need to do is to take your working query, and convert it to a parameterised form. Something like this:
// Expects valid $mysqli object here
$sql = "
UPDATE members
SET gender = ?
WHERE username = ?
";
$stmt = $mysqli->prepare($sql);
// ** As we discovered, the binding needs to happen in one
// ** call, not across several
$stmt->bind_param('ss', $_POST['Female'], $_SESSION['username']);
$stmt->execute();
Looking at your original code, there seems to have been two problems: the statement wasn't prepared at all (and so the program should have exited with a fatal error) and there was a syntax error in the original SQL statement.
In your new code, you're missing the execute() call.