PHP/HTML Form Feeding Blank Entries to MySQL - php

I am a PHP/MySQL Greenback here, and I have run into an issue with a simple form I am trying to feed into a MySQL database via PHP, that keeps feeding blank entries.
The form is live, connecting and feeding to the DB, however whenever I submit an entry, my confirmation echo's back that it Connected successfullyINSERT INTO db_name.events (eventname, eventprice, eventabout) VALUES ('', '', '') Works! even though the values were populated in the HTML form. Then when I log in and check the MySQL Database through PHPmyadmin I can see that it indeed created a new row in the table, but it is blank.
I have spent hours combing the syntax line by line and can't seem to find anything out of place and I have now added a bunch of troubleshooting steps in to try and solve it.
Any help is greatly appreciated!
The HTML form is as follows:
<form method="post" action="eventtestconnect.php"><table style="border: 0; margin-left: auto; margin-right:auto;text-align: left">
<tr>
<td>Event Name:</td>
<td><input name="name"></td>
</tr>
<tr>
<td>Event Price:</td>
<td><input name="price"></td>
</tr>
<tr>
<td>Event Description:</td>
<td><textarea name="description" cols="40" rows="5">
</textarea></td>
</tr>
</table>
<br><br>
<input type="submit" value="Submit">
</form>
And the PHP file that connects to this form is:
<?php
// connect to database
$dbhost = '111.111.11.111';
$dbuser = 'db_name';
$dbpass = 'pwpwpw';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
//select database
mysql_select_db("db_name", $conn);
if ($_POST)
{
// scrub inputs
$name = mysql_real_escape_string($conn, $_POST['name']);
$price = mysql_real_escape_string($conn, $_POST['price']);
$description = mysql_real_escape_string($conn, $_POST['description']);
// prepare query
$sql = "INSERT INTO db_name.events (eventname, eventprice, eventabout)
VALUES ('$name', '$price', '$description')";
// execute query
mysql_query($sql);
// close connection
mysql_close($conn);
echo $sql;
}
?>
Thanks in advance for any help, I have been browsing these forums grabbing help and tips. Seems like a great community!

You passing in the arguments to mysql_real_escape_string in the wrong order. It should be:
$name = mysql_real_escape_string($_POST['name'], $conn);

Related

Data inserted through PHP does not appear in phpMyAdmin

I have a simple PHP page that posts to a DB. I actually only use it for debugging because the real app receives posts from an Arduino:
SamplePost.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
</head>
<body>
<form action="data_post.php" method="post">
<table style="text-align: left; width: 100%;" border="0"
cellpadding="2" cellspacing="2">
<tbody>
<tr>
<td>Name(Temp):</td>
<td><input name="username" type="text"></td>
<td></td>
</tr>
<tr>
<td>Age(co2):</td>
<td><input name="age" type="text"></td>
<td></td>
</tr>
<tr>
<td>UVIndex:</td>
<td><input name="uvindex" type="text"></td>
<td></td>
</tr>
<tr>
<td>MQ2:</td>
<td><input name="mq2" type="text"></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td><input type="submit"></td>
</tr>
</tbody>
</table>
<br>
</form>
</body>
</html>
I recently used it to debug because I was having issues with the Arduino app not posting since 20 days ago. Oddly enough I discovered the DB username I had in the PHP was incomplete. Odd because it has been posting for years and I honestly don't remember having changed the DB username in the PHP, but whatever. So this is what it posts to:
data_post.php
<?php
$user = 'myusr';
$password = 'mypwd';
$server = 'localhost';
$database = 'mydb';
$pdo = new PDO("mysql:host=$server;dbname=$database", $user, $password);
$username=$_POST['name'];
$age=$_POST['age'];
$uvindex=$_POST['uvindex'];
$mq2=$_POST['mq2'];
$sql = "INSERT INTO example (name,age,uvindex,mq2,beer) VALUES (:username, :age, :uvindex, :mq2, 'NO')";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(":username", $username);
$stmt->bindParam(":age", $age);
$stmt->bindParam(":uvindex", $uvindex);
$stmt->bindParam(":mq2", $mq2);
$result = $stmt->execute(array(':username'=>$username, ':age'=>$age, ':uvindex'=>$uvindex, ':mq2'=>$mq2));
if($result) {
echo "Your text has been posted";
}// end if
else {
echo '0 results';
}// end else
file_put_contents("arduinopost.txt",$username);
?>
So after I corrected the DB username in code, I used the SamplePost.html and it worked because I got my success message from the PHP if-else and I refreshed my DB read file and the post appeared:
query.php
<html>
<body>
<?php
$servername = "localhost";
$username = "myusr";
$password = "mypwd";
$dbname = "mydb";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM example where id > (SELECT MAX(id) - 20 FROM example)";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id=" . $row["id"]. ". Temp=" . $row["name"]. ". CO2PPM=" . $row["age"]. ". UVIndex=" . $row["uvindex"]. ". MQ2R=" . $row["mq2"]. ". Timestamp=" . $row["timestamp"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
</body>
</html>
But the weird thing is that when I look for that entry in the DB via phpMyAdmin, it's simply not there. But I can see the data printed from the query.php on my screen and I've refreshed it multiple times, it's still there...
How can data be in a PHP page that reads from the DB, but not in the DB?
I added the screenshot of phpmyadmin, where are you can see, they records are ordered by descending timestamp, so i should be seeing the latest records, right?
As a side note, the arduino app started posting to the data_post.php page again successfully and I can now see the latest record in my query.php page but I cannot see the records in the phpmyadmin. Im thinking this is gonna turn up to be something silly but i was worried whatever the cause is, that it might be related to the arduino not being able to post. But at least now posting is working again.

adding record to MYSQL database wont work in PHP

Ive written PHP code to add a record to my database. When I click on the save button, then it should say "saved successfully", But all that happens is that the page refreshes with no added records in the database and no "saved successfully" message pops up.
My database connection works properly. So I cant figure out what the problem could be.
here is the PHP code:
<?php
error_reporting(0);
$con = mysqli_connect("localhost", "root", "password") or die("error");
if($con) {
mysqli_select_db("maplibrary",$con);
}
if (isset($_POST["save"])) {
$sql = mysqli_query("INSERT INTO member (memberID, firstName, surname, contactDetails)
VALUES('{$_POST['memberID']}',
'{$_POST['firstName']}',
'{$_POST['surname']}',
'{$_POST['contactDetails']}'
)");
if ($sql) {
echo "save successfully";
}
}
?>
here is the HTML code:
<!DOCTYPE html>
<html lang="en">
<head>
<title>ViewMembers</title>
</head>
<body>
<form action="" method="post">
<table style="border:1 #F00 solid;width:500px;overflow:auto;margin:auto;background:#999;">
<tr>
<td>Member ID</td>
<td><input type="text" name"memberID" /></td>
</tr>
<tr>
<td>First Name</td>
<td><input type="text" name"firstName" /></td>
</tr>
<tr>
<td>Surname</td>
<td><input type="text" name"surname" /></td>
</tr>
<tr>
<td>Contact Details</td>
<td><input type="text" name"contactDetails" /></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Save" name="save" /></td>
</tr>
</table>
</form>
</body>
</html>
You didn't add $conn as parameter of mysqli_query function.See usage :
http://www.w3schools.com/php/func_mysqli_query.asp
<?php
error_reporting(0);
$con = mysqli_connect("localhost","root","password") or die("error");
if($con)
{
mysqli_select_db("maplibrary",$con);
}
if (isset($_POST["save"]))
{
$sql = mysqli_query($con, "INSERT INTO member
(memberID,firstName,surname,contactDetails)
VALUES('{$_POST['memberID']}',
'{$_POST['firstName']}',
'{$_POST['surname']}',
'{$_POST['contactDetails']}'
)");
if ($sql)
{
echo "save successfully";
}
}
?>
Try this one:
<?php
$servername = "localhost";
$username = "username";//YOUR USER NAME!
$password = "password";//YOUR PASSWORD!
$dbname = "myDB"; //YOUR DB NAME!
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if (isset($_POST["save"])){
$var1 = $_POST['memberID'];
$var2 = $_POST['firstName'];
$var3 = $_POST['surname'];
$var4 = $_POST['contactDetails'];
$sql = "INSERT INTO member(memberID,firstName,surname,contactDetails)
VALUES ('".$var1."', '".$var2."', '"$var3."', '"$var4."')";
if ($conn->query($sql) === TRUE) {echo "successfully saved";}
else {echo "Error: " . $sql . "<br>" . $conn->error;}
}
$conn->close();
?>
hope i understood your problem... :)
BTW i suggest you to create a php file that will contain only the connection, because you may will need to connect to the database again in some point so you do not want to copy your code again and again...
so you can create a connect.php that will contain only the connection lines, you can include it (connect.php) inside of any page you want. it will make kit much easier.
look at: php include

writing on sql with php [duplicate]

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 7 years ago.
I wrote a code with a form:
<form method="post">
<table>
<tr>
<td style="text-align:right">Artista:</td>
<td><input type="text" name="artist" /></td>
</tr>
<tr>
<td style="text-align:right">Titulo:</td>
<td><input type="text" name="title" /></td>
</tr>
<tr>
<td style="text-align:right">Capa (link):</td>
<td><input type="text" name="cover" /></td>
</tr>
<tr>
<td colspan="2">
<center>
<input type="submit" style="margin-top:20px" />
</center>
</td>
</tr>
</table>
</form>
Then I wrote some php to get the info on form and put it on a mySQL database.
if (isset($_POST['submit'])){
$dbhost = 'HOST';
$dbuser = 'USER';
$dbpass = 'PASS';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
$artist = strtoupper($_POST[artist]);
$title = strtoupper($_POST[title]);
$cover = $_POST[cover];
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$sql = "INSERT INTO 'MusicList'('artist', 'title', 'cover', 'votes') VALUES ('".$artist."', '".$title."', '".$cover."', 0)";
mysql_select_db('DATABASE_NAME');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
echo "<center><h1>Success!</h1></center>";
mysql_close($conn);
}
However it seems something has gone wrong because it doesn't write anything on SQL. Can you tell me what did I wrote wrong?
Change the single quotes around MusicList to be backticks, and get rid of the single quotes around the column names like this:
$sql = "INSERT INTO `MusicList`(artist, title, cover, votes) VALUES ('".$artist."', '".$title."', '".$cover."', 0)";
SQL isn't expecting quotes here.
Also as Fred pointed out, you need to name your submit button, or else the if statement will always be false.
So something like:
<input type="submit" name="submit_button" style="margin-top:20px" />
and change the if statement to:
if (isset($_POST['submit_button'])){

Read and Write to SQL Database

I have the script that will write info to the database, but how can I have it print the variable "time" from the database after it updated the same query based on the email entered to write to database? This is for use with JSON.
<?php
if(!empty($_POST))
{
$dbhost = 'localhost';
$dbuser = 'casaange_testapp';
$dbpass = 'testapp1';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db('casaange_volunteertest');
$email= $_POST['email'];
$time= $_POST['time'];
$sql = "UPDATE users SET time= '$time' WHERE email = '$email'";
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not update data: ' . mysql_error());
}
if($retval){
$response["success"] = 1;
$response["message"] = "Update successful!";
die(json_encode($response));
}
//echo '{"success":1, "message":"Time added!"}';
mysql_close($conn);
}
else
{
?>
<form method="post" action="timeinsert.php">
<table width="400" border="0" cellspacing="1" cellpadding="2">
<tr>
<td width="100">Email:</td>
<td><input name="email" type="text" id="email"></td>
</tr>
<tr>
<td width="100">Time:</td>
<td><input name="time" type="text" id="time"></td>
</tr>
<tr>
<td width="100"> </td>
<td> </td>
</tr>
<tr>
<td width="100"> </td>
<td>
<input name="update" type="submit" id="update" value="Update">
</td>
</tr>
</table>
</form>
<?php
}
?>
</body>
</html>
I think what you want to know is whether the UPDATE query actually changed the value in the database?
You can use mysql_affected_rows() see how many rows changed as a result of your query - in your case it will be either 1 or 0.
If you need to return the time that you just put into the database, you can query the value that actually went into the database by selecting it back out with the email address as the key.
A few general observations about your code, if I may:
You must escape that POST data before putting it into an SQL query
like that. At best it'll be a source of bugs, worst a massive
security hole.
If you're writing new code, as you appear to be here, you should
consider using the newer MySQLi or PDO_MySQL extensions instead of
the old MySQL calls.
You can use json_encode to turn an associative PHP array into a JSON
object, instead of building a JSON string yourself.

Use a simple form and PHP to delete a mySQL record

I am trying to build a page that will allow the user to enter an employee number via a form and when they hit the "delete" button it will remove the corresponding record. The database is named "Crosshill", the Table is called "Employees" and the field I want to use is "employeeid".
It seems to connect fine to the DB, but the code below doesn't work. When you hit the "Delete" button it returns an error of:
Could not delete data: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE employeeid =' at line 1
Blockquote
<html>
<head>
<title>Delete an Employee</title>
</head>
<body>
<h3>Enter the Employee Number below to delete a record</h3>
<?php
if(isset($_POST['delete']))
{
$dbhost = '####';
$dbuser = '####';
$dbpass = '####';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$employeeid = $_POST['employeeid'];
$sql = "DELETE Employees ".
"WHERE employeeid = $employeeid" ;
mysql_select_db('Crosshill');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not delete data: ' . mysql_error());
}
echo "Deleted data successfully\n";
mysql_close($conn);
}
else
{
?>
<form method="post" action="<?php $_PHP_SELF ?>">
<table width="400" border="0" cellspacing="1" cellpadding="2">
<tr>
<td width="100">Employee ID</td>
<td><input name="employeeid" type="number" id="employeeid"></td>
</tr>
<tr>
<td width="100"> </td>
<td> </td>
</tr>
<tr>
<td width="100"> </td>
<td>
<input name="delete" type="submit" id="delete" value="Delete">
</td>
</tr>
</table>
</form>
<?php
}
?>
</html>
It's DELETE FROM <table> WHERE <condition>, the FROM is missing in your query.
You are missing "from" after delete..
It should be as DELETE from Employees WHERE condition.
To avoid such situations always do one thing, just echo the sql query and using "exit" after the same to terminate the further execution of the program.
Copy the query from browser and run the same in phpmyadmin or whatever other tool you use..
That practice will help you to find out the root cause of the problem..

Categories