PHP/HTML forms and database inserting - php

I am going to start this off by saying -- yes I know there are other links similar to this and topics similar to this and I have read all of them and incorporated them into my code. However, I cannot figure it out and have tried everything I can.
Basically my goal is to take a users input from an html form called socialmedia.html:
<html>
<body>
<h1> Pulse submission page </h1><br>
<form action="action.php" method="post">
Title: <input type="text" name="posttitle"><br><br>
Content: <input type="text" name="content"><br><br>
<input type="submit">
</form>
</body>
</html>
and then send it to a php file called action.php:
<?php
$mysqli = new mysqli("DB HOST IP", "USER", "PASS", "DB NAME");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
echo $mysqli->host_info . "\n";
$posttitle = $_POST["posttitle"];
$content = $_POST["content"];
if(isset($_POST['submit'])){
$sql = "INSERT INTO `posts` (posttitle, content) VALUES ('$posttitle', '$content')";
echo 'post added to database';
}
if($sql){
echo 'success';
}
else{
echo 'failure';
}
$sql = "SELECT * FROM `posts`";
$res = $mysqli->query($sql);
if($res->num_rows > 0){
while($row = $res->fetch_assoc()){
echo "ID". $row["id"]. "<br/>";
echo "Title". $row["posttitle"]. "<br/>";
echo "Content". $row["content"]. "<br/>";
}
}
else
{
echo "No Record Found!";
}
?>
This file is SUPPOSED to insert the user's form values into the table posts:
this is the table posts
and then print the whole table to a webpage-- action.php this is what it prints (with the error checks and all):
this is the page, I blurred out the IP
NOTE: I manually inserted the first title and content to see if the code could read from the database (which it can)
honestly, I do not know where I went wrong and I have die extensive research at this point. It's probably going to end up being a syntax error and I'm gonna be kicking myself. It could have something to do with me using a Godaddy server and the phpMyAdmin and database being through there. I am using mysqli instead of PDO because PLESK and Godaddy do not support PDO yet.

<input type="submit" name="submit" /> try with this
if(isset($_POST['submit'])){
$sql = "INSERT INTO `posts` (posttitle, content) VALUES ('$posttitle', '$content')";
$save = $mysqli->query($sql);
if($save)
echo 'success';
else
echo 'failure';
}

several things to get you started
1) missing quote after PASS
mysqli("DB HOST IP", "USER", "PASS, "DB NAME");
2) you are not executing your INSERT query, missing $mysqli->query($sql);
if(isset($_POST['submit'])){
$sql = "INSERT INTO `posts` (posttitle, content) VALUES ('$posttitle',
'$content')";
echo 'post added to database';
}

You have to give name of the submit butto as
input type="submit" name="submit"
"INSERT INTO posts (posttitle, content) VALUES ('$posttitle', '$content')"

Related

Cannot get my PHP code to remove row in mysql

I am currently trying to make it so my PHP code can remove appointment records in mysql. I have been trying for quite some time without any luck.
Here is my code where you would select which appointment to remove. All of the appointments display correctly in a dropdown menu on this page.
<?php
session_start();
$db = mysqli_connect("localhost", "user", "pass", "database");
if (!$db) { die("Connection failed: " . mysqli_connect_error()); }
$sql2 = "SELECT a.appointmentID
FROM AppointmentDetail AS a, Customer AS c
WHERE a.customerID=c.customerID
AND a.appointmentStatus<>'completed'
AND emailAddress = '".$_SESSION['username']."';";
$result2 = mysqli_query($db, $sql2);
echo "<h2 class='ArticleHeader1'>Cancel one of your Upcoming Appointments</h2>";
echo "<form action='Example.php' method='post'>";
echo "<p> Select an AppointmentID from the list below </p>";
echo "<select type='text' name='appointmentCancel' required>";
while($row2 = mysqli_fetch_row($result2))
{foreach($row2 as $cell2)
echo "<option value='".$cell2."'>$cell2</option>";}
echo "</select>";
echo "<input type='submit' name='formDelete' value='Cancel Appointment' class='button'/>";
echo "</form>";
mysqli_close($db);
?>
Here is the Example.php form that I would submit to where I always get the "Sorry! There has been an error in canceling your appointment. Please contact your Administrator"
<?php
session_start();
$db = mysqli_connect("localhost", "user", "pass", "database");
if (!$db) { die("Connection failed: " . mysqli_connect_error()); }
if(isset($_POST['formDelete']))
{
$appointmentDelete = mysqli_real_escape_string($db, $_POST['appointmentCancel']);
$del_val = "DELETE FROM AppointmentDetail
WHERE appointmentID='".$appointmentDelete;."';";
$saved = mysqli_query($db, $del_val);
if($saved) {
echo "Your Appointment Has Been Successfully Cancelled!";
} else {
echo "Sorry! There has been an error in canceling your appointment.
Please contact your Administrator";
}
}
mysqli_close($db);
?>
I have tried using different SQL queries to remove records based on different fields other than appointmentID with no luck. But appointmentID is the simplest so since none of the fields are working, I must be doing something wrong.
I have also tried messing around with the quotes around $appointmentDelete and a few other variables with no luck.
I am pretty new to PHP and SQL so I really am just looking to get this basic functionality down.
I have cut out a lot of the additional code on my first PHP page to only include what I believe to be relevant.
There's an concatenation error in your delete query. Change it as bellow,
$del_val = "DELETE FROM AppointmentDetail WHERE appointmentID=$appointmentDelete";
Please refer PHP - concatenate or directly insert variables in string for more details about concatenation.

HTML form not populating MySQL DB as expected

When I save a form from html to php and finally store it in MySQL somewhere in that line it save the var= including what comes after the =
Here is my html:
<form action="searchResultsSave.php" method="POST">
What are we looking for? <input type="text" name="searchVar" />
<input type="submit" value="Submit">
</form>
Php:
$searchVar = file_get_contents('php://input');
$sql = "INSERT INTO g_information(searchVar) VALUES ('$searchVar')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
Finally my output in mysql is: "searchVar=cars" when it should just be "cars".
Where do you think I went wrong?
$searchVar = file_get_contents('php://input');
should be
$searchVar = $_POST['searchVar'];
This way you get the value of the search term.
You should read input variable from the form
<?php
$_POST["searchVar"];
?>
Then do some validation on the input, making sure no illegal characters are entered and data is safe to store in MySQL database
<?php
$_POST['searchVar'] = filter_var($_POST['searchVar'], FILTER_SANITIZE_STRING);
$sql = "INSERT INTO g_information(searchVar) VALUES ("'.$_POST['searchVar'].'")";
?>

PHP PSQL Insert Error

I'm trying to create a web interface for a baseball database but when I enter information into the forms and press submit it always gets to 'an error occurred'.
Here's the webpage with the form.
<html>
<?php
$dbconn = pg_connect("dbname=mine user=mine password=mine");
if ($dbconn) {
echo "Connection established <br/>";
}
echo "Here are the current NL West Teams <br/>";
$result = pg_query($dbconn, "SELECT Name, Record FROM Teams");
if (!$result) {
echo "An error occurred.\n";
exit;
}
while ($row = pg_fetch_row($result)) {
echo "Team: $row[0] Record: $row[1]";
echo "<br />\n";
}
?>
<form action="InsertPP.php" method="post">
Name: <input type="text" name="name"><br>
Team: <input type="text" name="team"><br>
Number: <input type="text" name="number"><br>
Handed: <input type="text" name="Handed"><br>
Position: <input type="text" name="Position"><br>
<input type="submit">
</form>
</html>
And here is the Insert PHP script.
<html>
<body>
<?php
$dbconn = pg_connect("dbname=mine user=mine password=mine");
if ($dbconn) {
echo "Connection established <br/>";
}
$_first = $_POST["Handed"];
$_second = $_POST["Position"];
$_third = $_POST["name"];
$_fourth = $_POST["number"];
$_fifth = $_POST["team"];
$Query = pg_query(dbconn, "INSERT INTO PosPlayer VALUES('$_first', '$_second', '$_third', $_fourth, '$_fifth)'");
if (!$Query) {
echo "An error occurred.\n";
exit;
}
echo "Your Player has been added!";
?>
</body>
</html>
I input the same values into postgres and the forms, and the player was created directly in postgres, but some error occurred when input into the form. Any ideas?
EDIT: I fixed the missing $ in front of the dbconn. Still getting the 'An error occurred'.
Check the end of the INSERT statement. You have
'$_fifth)'"
where you should have
'$_fifth')"
i.e. the closing quote for the value should be inside the closing parenthesis, not outside it.
You really should be using a prepared statement for this instead of a dynamic query. The syntax would be something like this (using the PostgreSQL driver):
$sql = "INSERT INTO PosPlayer VALUES($1, $2, $3, $4, $5)";
$result = pg_prepare($dbconn, "", $sql);
$result = pg_execute($dbconn, "", array($_first, $_second, $_third, $_fourth, $_fifth));
This will automagically handle proper quoting, escaping and type-matching of the variables' values to prevent (among other things) possible SQL injection attacks. Note that $1, $2, &c. is the pg driver's syntax for bind variables.
Replace
$Query = pg_query(dbconn, "INSERT INTO PosPlayer VALUES('$_first', '$_second', '$_third', $_fourth, '$_fifth)'");
By
$Query = pg_query($dbconn, "INSERT INTO PosPlayer VALUES('$_first', '$_second', '$_third', $_fourth, '$_fifth)'");
$ sign was missing from dbconn. Other than that, there seems to be nothing wrong with the code.

PHP can't update SQL

I'm using a php part in my site, where I have a textarea that get a text from a database. The user can edit this text and after he finish press the save button, and using UPDATE I will change the text in the database.
Here is my code:
<?php
$con=mysqli_connect("localhost","userdb","codedb","projectdb");
mysqli_set_charset($con, 'utf8');
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$myQueryfac="SELECT text FROM main WHERE id=1";
$result = mysqli_query($con,$myQueryfac);
while($row = mysqli_fetch_array($result)) {
$t1=$row['text'];
}
$form="<form action='adminindex.php' method='post'>
<textarea name='area1' maxlength='1500' cols='50' rows='10'>$t1</textarea>
<input type='submit' name='enter' value='Save'>
</form>";
if($_POST['enter']) {
$t1=$_POST['area1'];
mysqli_query($con,"UPDATE main SET text='$t1' WHERE id='1'");
}
echo $form;
mysqli_close($con);
?>
My problem is in the UPDATE query it seems like it ignores $t1 and nothing change in database. But if I put something random in there, "RANDOM TEXT", change it successful.
This is how you do it:
test.php
// DB Connect
$con=mysqli_connect("localhost","userdb","codedb","projectdb");
mysqli_set_charset($con, 'utf8');
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Handle POST
if (count($_POST))
{
// Save In DB
mysqli_query($con, sprintf("UPDATE main SET `text`='%s' WHERE id=%d",
mysqli_real_escape_string($con, $_POST['area1']),
1)); // id
// Success
echo "<p>Data updated.</p>";
}
// Load Existing Data
$myQueryfac="SELECT `text` FROM main WHERE id=1";
$result = mysqli_query($con, $myQueryfac);
$row = mysqli_fetch_array($result);
// Display Form
echo "<form action='test.php' method='post'>
<textarea name='area1' maxlength='1500' cols='50' rows='10'>". $row['text'] ."</textarea>
<input type='submit' name='enter' value='Save'>
</form>";
// DB Close
mysqli_close($con);
?>
What I've changed
Moved the post hander up (above the select statement), so that if an update occurs, the form will show the latest updated data
Your update query was treating the id as string, I formatted it to be a digit (%d)
Removed the while loop, you don't need it as it is a single row being returned
added sql-injection prevention (using sprintf and mysqli_real_escape_string)
added backticks `` around the db field name text (wasn't sure if this is a reserved word, because it's one of the sql data types)
Try to do
mysqli_query($con,"UPDATE main SET text='$t1' WHERE id=1");
Instead
mysqli_query($con,"UPDATE main SET text='$t1' WHERE id='1'");
It could be the WHERE condition that bring your problems
You are checking the $_POST array for a value not existing. enter is your submit button and will not send a value.
Try this:
if($_POST['area1']) {
$t1=$_POST['area1'];
mysqli_query($con,"UPDATE main SET text='$t1' WHERE id='1'");
}

Concatenate two HTML inputs and insert them into a MySQL database

I'm creating this web page for this class that I'm in and for it I need to concatenate two separate HTML form inputs with a space in between and insert them into a MySQL database. Specifically I ask the user for their first name and their last name in separate HTML form inputs and I have to concatenate those two input into a full name with a space in between (or else "Bob" and "Ross" concatenated would be "BobRoss" instead of "Bob Ross"). I don't know where to start when doing that. Also I need to check that the full name isn't already in the database before inserting it into the database, but I'm already doing that with the first name and last name so that shouldn't be too hard.
Here is the HTML page with the form inputs:
<html>
<head>
<link rel="stylesheet" href="Site.css">
<?php include("Header.php"); ?>
</div>
</head>
<body>
<div id="main">
<h1>About</h1>
<form action="Insert.php" method="post">
<p>First name:</p><input type="text" name="firstname"><br>
<p>Last name:</p><input type="text" name="lastname"><br>
<p>Age:</p><input type="text" name="age"><br>
<input type="submit">
</form>
<?php include("Footer.php");?>
</div>
</body>
</html>
And here is the PHP page where it inputs the data into the database. Currently I'm inputing the user's first name, last name, and age, but I need to concatenate the first and last name and make sure it isn't in the database and then insert it into the database and I haven't done that. Currently I make sure that the first name is unique, I make sure that the last name is unique, but I don't care whether the age is unique or not.
<?php
$con = mysql_connect("localhost","a7068104_user2","wiseguy1345");
if(!$con) {
die("could not connect to localhost:" .mysql_error());
}
header("refresh:1.5; url=NamesAction.php");
mysql_select_db("a7068104_world") or die("Cannot connect to database");
$name = mysql_real_escape_string($_POST['firstname']);
$query = "SELECT * FROM names_1 WHERE firstname='$name'";
$result = mysql_query($query);
if(mysql_num_rows($result) > 0 ){
echo "Your name is already in the database and will not be added again!";
}
else {
$query = "INSERT INTO names_1 (firstname) VALUES('$name')";
$result = mysql_query($query);
if($result) {
echo "Your first name was successfully added to the database!";
}
else{
echo "Your first name couldn't be added to the database!";
}
}
$name = mysql_real_escape_string($_POST['lastname']);
$query = "SELECT * FROM names_1 WHERE lastname='$name'";
$result = mysql_query($query);
if(mysql_num_rows($result) > 0 ){
echo "Your name is already in the database and will not be added again!";
}
else {
$query = "INSERT INTO names_1 (lastname) VALUES('$name')";
$result = mysql_query($query);
if($result) {
echo "Your first name was successfully added to the database!";
}
else{
echo "Your first name couldn't be added to the database!";
}
}
$name = mysql_real_escape_string($_POST['age']);
$query = "INSERT INTO names_1 (age) VALUES('$name')";
$result = mysql_query($query);
if($result) {
echo "Your name was successfully added to the database!";
}
else {
echo "Your name couldn't be added to the database!";
}
mysql_close($con);
?>
<html>
<head>
<link rel="stylesheet" href="Site.css">
<?php include("Header.php"); ?>
</div>
</head>
<body>
<div id="main">
<h1>Names</h1>
<p>You will be redirected back to the <b>Names</b> page in a moment.</p>
<?php include("Footer.php");?>
</div>
</body>
</html>
For a start you shouldn't be using mysql functions as this extension
is deprecated as of PHP 5.5.0, and will be removed in the future.
I suggest using the new improved PDO library and PDO Prepared Statements, see here.
As for the concatenation, you could simply do it like this:
$concatenated_name = $_POST['firstname'] . " " . $_POST['lastname'];
This would concatenate the names with a space in between.
You can then use $concatenated_name in your queries.
However I still strongly recommend you use PDO for all your functions.
$fullname = trim($_REQUEST['firstname']).trim($_REQUEST['lastname']);

Categories