PHP not inserting data into MySQL but not showing error - php

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.

Related

php mysqli inserting duplicate value

I created a website where you insert radio button data to the database after you click submit button.
However, the problem is that whenever I click the submit button it inserts two duplicate values instead of one.
My code is the following:
<form action="test.php" method ="post" >
<b> what is you fav sport ؟ </b>
</br>
<input type="radio" name="sport1" value="football"> football
<input type="radio" name="sport1" value="basketball"> football
<?php
$servername = "";
$username = "";
$password = "";
$dbname = "";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error){
die("Connection failed: " . $conn->connect_error);
}
mysqli_query($conn, "set names 'utf8'");
?>
<input type="submit" name="submit" value="submit"/>
<?php
if(isset($_POST['submit']) && !empty($_POST)){
$sport1 = $_POST['sport1'];
$SQL = "INSERT INTO userTable (user_q1) VALUES ('$sport1')";
$result = mysqli_query($conn, $SQL);
if ($conn->query($SQL) === TRUE) {
echo "New record created successfully";
}else{
echo "Error: " . $SQL . "<br>" . $conn->error;
}
$conn->close();
}
?>
</form>
Any help would be be appreciated.
you are doing the same thing twice
Just use either
$result = mysqli_query($conn, $SQL)
//or
$conn->query($SQL)
mysqli_query and $conn->query() are used fro same purpose.
just remove any one of the statement, you will get what you need

php search works as seperate page, but not on same page

I'm working on a project where I can use multiple forms on an html page to search and update tables from a mysql database. I have created a basic html form that will run a search on a separate php file. When I try to integrate that same php script into that same html it finds no results. Any help would be appreciated.
basic html
<html>
<body>
<form name="search" method="post" action="searchresults.php">
<input name="search" type="text" size="40" maxlength="50" />
<input type="submit" name="Submit" value="Search" />
</form>
</body>
</html>
search php
<?php
$database = "dbname";
$username = "name";
$password = "pass";
$host = "host";
$conn = new mysqli($host, $username, $password, $database);
if ($conn->connect_error){
die("Failed:" . $conn->connect_error);
}
echo"Successful";
$query = $_POST['search'];
$query = htmlspecialchars($query);
$raw_results = mysqli_query($conn,"SELECT * FROM beers WHERE name LIKE '%".$query."%'");
if(mysqli_num_rows($raw_results) > 0){ // if one or more rows are returned do following
while($results = mysqli_fetch_array($raw_results)){
echo "<p><h3>".$results['Name']."</h3>".$results['Brewery']."</p>";
}
}
else{ // if there is no matching rows do following
echo "No results";
}
?>
This works separated, but if I copy the same php script and insert it into the main html it connects but finds no results. Tried using _GET instead of _POST removed the action field and Ive searched all over for similar issues. If I scale everything completely down it gives me a parse error for $query = htmlspecialchars($query); , any thoughts?
Apply if (isset($query)) {...}. Only when search name is valid can you gain results.
<?php
$query = $_POST['search'];
// Apply validation.
if (isset($query)) {
$query = htmlspecialchars($query);
echo"Successful";
$conn = new mysqli($host, $username, $password, $database);
if ($conn->connect_error) {
die("Failed:" . $conn->connect_error);
}
$raw_results = mysqli_query($conn, "SELECT * FROM beers WHERE name LIKE '%" . $query . "%'");
if (mysqli_num_rows($raw_results) > 0) { // if one or more rows are returned do following
while ($results = mysqli_fetch_array($raw_results)) {
echo "<p><h3>" . $results['Name'] . "</h3>" . $results['Brewery'] . "</p>";
}
} else { // if there is no matching rows do following
echo "No results";
}
}
?>

UPDATE for MySQL through PHP not working

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.

Getting User Data Based on Their Information

This first field is where a web visitor will enter in the 'cardname' hit submit and be directed to another page (dashboard2.php) where only his or her content will appear.
Enter your cardname to access your content<br>
<form action='dashboard2.php'>
<input type='text' name='cardname'/><input type='submit' value='retrieve card'/>
</form>
</body>
The page below is the page that is directed after the user enters in the 'cardname' from the first input field. However, I only want this second page to show the information based on the cardname that was entered. Right now, it shows every single cardname, questionone, answerone from that table.
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "flashcards";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT cardname, questionone, answerone FROM cards";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<br> ". $row["cardname"]. " ". $row["questionone"]. " " . $row["answerone"] . "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
You have to modify the query to accept a WHERE clause. For instance, WHERE cardname = mysqli_real_escape_string($conn, $_GET['cardname']) (The default method for any form is GET unless you specify method="post".).
You should learn about prepared statements for MySQLi and perhaps consider using PDO, it's really not hard.
It seems that you want to perform a search and not a display all the records.
Usually a search returns records that match a certain field, unless a specific ID or unique value was entered in the search. I'm not sure this is the case.
I put this together a little quick but hopefully it helps...
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "flashcards";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// escape the string to avoid SQL injections
$searchEscaped = $conn->real_escape_string($_POST['cardname']);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT cardname, questionone, answerone FROM cards WHERE cardname = '$searchEscaped' ";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
if($result->num_rows == 1){
// only one result found, show just that
$row = $result->fetch_assoc()
echo "<br> ". $row["cardname"]. " ". $row["questionone"]. " " . $row["answerone"] . "<br>";
}else{
// multiple rows found, show them all
while($row = $result->fetch_assoc()) {
echo "<br> ". $row["cardname"]. " ". $row["questionone"]. " " . $row["answerone"] . "<br>";
}
}
} else {
echo "0 results";
}
$conn->close();
?>

Why is my PHP / SQL generating duplicate database entries?

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

Categories