HTML Form won't submit to database - php

I want the data inputed into the form by the user to be submitted to a database. But for some reason my code isn't working?
<form action="newpostsubmit.php" method="post">
<h2 class="form-signin-heading">New Post (beta)</h2>
<div class="form-group">
<label for="title">Title</label>
<input type="text" class="form-control" name="title" id="title">
</div>
<br>
<div class="form-group">
<label for="post">Post</label>
<textarea class="form-control" rows="5" name="post" id="post"></textarea>
</div>
<br>
<input type="submit">
</form>
PHP submit
<?php
//Connecting to sql db.
$connect = mysqli_connect("localhost","root","pwd","db");
//Sending form data to sql db.
mysqli_query($connect,"INSERT INTO posts (title, post)
VALUES ('$_POST[title]', '$_POST[post]')";
?>

First, your $_POST variables are incorrect as you're forgetting to quote the item like $_POST['title'].
Second, you really should use prepared statements. They'll make your code cleaner and have the added benefit of protecting you against SQL Injection Attacks..
You should also perform minimal error checking of your connection and your queries, it is likely that you're missing some information that will help you to be successful. The errors are already in your error log, but you can make them echo out to the screen.
//Connecting to sql db.
$connect = mysqli_connect("localhost","root","pwd","db");
if (!$connect) {
echo "Connection failed: ". mysqli_connect_error();
exit();
}
//Sending form data to sql db.
$stmt = mysqli_prepare($connect, "INSERT INTO `posts` (`title`, `post`) VALUES (?,?)");
mysqli_stmt_bind_param($stmt, 'ss', $_POST['title'], $_POST['post'] );
// execute prepared statement
mysqli_stmt_execute($stmt);
// was there a problem?
if(mysqli_stmt_error($stmt)) {
echo "There was an error performing the query, " . mysqli_stmt_error($stmt);
}
There is a a lot going on here, but most notable is the prepare() where you use placeholders for your variables (?) and mysqli_stmt_bind_param() to bind your variables, as strings (s for each item) to the query.
Finally, check if there are any errors and echo those back to the screen with mysqli_stmt_error()
NOTE: Make sure to handle errors gracefully for your users, never displaying the actual problems to them which exposes your site to attacks. Echoing the information to the screen, as is being done here, is fine during the development stage.

You need to clean your POSTed variables to prevent SQL injections and other errors, and then quote them properly (as strings) on inserting them into the db.
$cleanTitle = mysqli_real_escape_string($connect,$_POST['title'];
$cleanPost = mysqli_real_escape_string($connect,$_POST['post'];
$sql = "INSERT INTO posts (title, post) VALUES ('$cleanTitle', '$cleanPost')";
$insert = mysqli_query($connect,$sql);
if(!$insert){
echo 'ERROR :'.mysqli_error($connect);
}

mysqli_query($connect,"INSERT INTO posts (title, post)
VALUES ('".$_POST[title]."', '".$_POST[post]."')";
query should be like this. Hope this helps.

Related

Insert php and html code into database and then fetching/getting it

So I'am trying to add Php code to the database it works when I insert it in the database. But when I go to the browser the Php code I added was commented
code:
$insert =
'</div>
<br><br><br>
<div class="posts-container">
<img src="'.$img.'" class="profpic"/>
<div class="editB-cont">
<img src="img/editB.png" class="editB"/>
</div>
<h1>'.$sender.'</h1>
<hr class="solid">
<p class="post-text-container">'.$post.'</p>
<br><br>
<img src="'."attatch/".$newfilename.'" class="attach"/>
<br><br>
<form action="post-comment" method="post">
<input type="hidden" name="parent-id" value="<?= echo $postId; ?>">
<input type="text" name="comment-text" placeholder="Comment...">
<input type="submit" value="Post" name="submit">
</form>
<br>
<div class="coments">
<?= include("get-comment.php"); ?>
</div><br>
</div><br><br>
';
$sql = "INSERT INTO posts (sender, post, sender_id, image_attach, sender_img) VALUES ('$sender', '$insert', $id, 'attatch/$newfilename', '$img')";
if (mysqli_query($conn, $sql)) {
header("Location: view-profile?id=$id");
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
}
Is there any way to fix this?
Like Dharman said, $insert should be divided, so assign your include to a variable and then create $insert like so:
'first part until div class=comments' . $includeVariable . 'second part';
Regarding the sql injection, just google php prepared statements, or check this w3schools article https://www.w3schools.com/php/php_mysql_prepared_statements.asp
EDIT
in get_comment.php
$comment = 'just a test';
return $comment;
then
$includeVariable = include('get_comment.php');
$insert = 'first part' . $includeVariable . 'second part';
EDIT 2
You could try using eval() to display $insert or that commented part of it, HOWEVER as php manual states:
Caution The eval() language construct is very dangerous because it allows execution of arbitrary PHP code. Its use thus is discouraged. If you have carefully verified that there is no other option than to use this construct, pay special attention not to pass any user provided data into it without properly validating it beforehand.
This leads to another issue, probably the most important one: storing blocks of code like that in a database is a sign of a seriously bad design, you should think how to avoid it and rewrite you code rather than try to make it work
EDIT 3
Your PDO is wrong, in $link->prepare() number of database columns you insert into and number of inserted values must be the same, for example, I insert two values into two columns:
INSERT INTO user(name, age) VALUES (:name, :age)
which is same as
INSERT INTO user(name, age) VALUES (?, ?)
then you bind parameters
$statement->bind_param('si', $name, $age)
where 'si' are parameters types: (s)tring and (i)nteger, check https://www.php.net/manual/en/mysqli-stmt.bind-param.php for details
then assing values to you variables
$name = 'John';
$age = 44;
finally execute
$statement->execute();

PHP Form isn't POSTing data to database

I made a simple form with two variables which should be sent to database after SUBMITing them. However even thought there is no bug reports, the database is still empty after submit. Where Can I look for mistake?
I already tried multiple ' or " or '", none of these worked. I can with no problem SELECT data from fdatabase so the connection is established.
$total = $_POST['kwota'];
$way = $_POST['sposob'];
echo $total . "<BR>" . $way;
$sql = "INSERT INTO payments (Total, Way) VALUES ('$kwota', '$sposob');";
mysqli_query($conn, $sql);
header("Location: ../index.php?Payment=success");
<form action="includes/Platnosc.inc.php" method="POST">
<input type="text" name="kwota" placeholder="kwota"><br>
<input type="text" name="sposob" placeholder="sposób"><br>
<button type="submit" name="submit">Dodaj płatność</button>
</form>
You are inserting $_POST array indexes as php variables. Change your query to this
$sql = "INSERT INTO payments (Total, Way) VALUES ('$total', '$way')";
However, I suggest you to use prepared statements to prevent from sql injections

Insert Text Fields into a Database with PHP and HTML

Im trying to add text to a database with a text entry, heres the part of the text entry of index.php:
<form action="steamauth/senddb.php" method="get">
<input type="text" name="username" placeholder="John Doe">
<input type="text" name="steamid" placeholder="12939124953">
<input type="text" name="server" placeholder="VanityRP | DarkRP"><br><br>
<input type="submit" class='btn btn-success' style='margin: 2px 3px;'>
</form>
Now heres the steamauth/senddb.php code:
$value1 = $_POST['username'];
$value2 = $_POST['steamid'];
$value3 = $_POST['server'];
$sql = "INSERT INTO StaffTeam (username, steamid, server) VALUES('".$value1."', '".$value2."', '".$value3."')";
if ($conn->query($sql) === TRUE) {
echo "Admin added succesfully, redirecting in 3 seconds...";
header( "refresh:3;url=http://vanityrp.site.nfoservers.com/index.php" );
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
So, now, the problem is, im getting empty records on the database, how can i fix that
There are 2 things wrong here.
First, you're using a GET method in your form, but then using POST arrays.
Both need to match. POST/POST and not GET/POST.
Then you're outputting before header with echo on top of headers.
How to fix "Headers already sent" error in PHP
Your present code is open to SQL injection. Use mysqli_* with prepared statements, or PDO with prepared statements.
If you are trying to pass data that MySQL will complain about, such as John's Bar & Grill (apostrophes), then you will need to escape your data; something you should be doing anyway.
I.e.:
$var = mysqli_real_escape_string($conn, $_POST['var']);
Your column types and lengths should also be correct and able to accomodate the data.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Displaying errors should only be done in staging, and never production.
Plus, make sure you are successfully connected to your database with mysqli_.
Different MySQL APIs do not intermix. (sidenote).

PHP Not Inserting Content in mySQL Database: Text, Images, Anything

So here is my dilemna that I've been reviewing and trying to break through for the last few days. I've created a basic login/register PHP system, which works fine. I've implemented a blog system that displays posts. I've written an add post function which does not post to the database, and it doesn't throw back an error function either.
I don't really understand because my register system works and adds new users, but the 'add blog post' does nothing. I can add from the database and it displays fine, but nothing here.
<?php
error_reporting(E_ALL & ~E_NOTICE);
session_start();
if (isset($_SESSION['id'])) {
$userId = $_SESSION['id'];
$username = $_SESSION['username'];
} else {
header('Location: login.php');
die();
}
if ($_POST['submit']) {
$title = strip_tags($_POST['title']);
$subtitle = strip_tags($_POST['subtitle']);
$content = strip_tags($_POST['content']);
mysqli_query($dbCon, $userREQ3);
$userREQ3 = " INSERT INTO `logindb`.`blog`
(`title`, `subtitle`, `content`) VALUES ('$title','$subtitle','$content')";
}
?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
Welcome, <?php echo $username; ?>, You are logged in. Your user id is <?php echo $userId; ?>.
Index
<form action="logout.php">
<input type="submit" value="Log me out!">
</form>
<form method="post" action="admin.php">
Title: <input type="text" name="title"/><br>
Subtitle: <input type="text" name="subtitle"/><br>
<br>
<br>
Content: <textarea name="content"></textarea>
<input type="submit" value="Write Post"/>
</form>
</body>
</html>
Your code is failing for two reasons.
Your conditional statement is looking for a named element called "submit"
You're trying to execute before the statement. Place your query (mysqli_query())"below" the values and do mysqli_query($dbCon, $userREQ3) or die(mysqli_error($dbCon));
Sidenote: Change if ($_POST['submit']) { to if (isset($_POST['submit'])) { it's better.
and <input type="submit" value="Write Post"/>
to <input type="submit" name="submit" value="Write Post"/>
SQL injection:
Your present code is open to SQL injection. Use mysqli with prepared statements, or PDO with prepared statements.
Also, you have variables in the body of your code, which may throw undefined variable x on initial page load.
Use a ternary operator for this
http://php.net/manual/en/language.operators.comparison.php
Use this for all your inputs/variables
As stated (in comments below): Make sure that you have connected to your database and using a mysqli method and not another API.
https://secure.php.net/mysqlinfo.api.choosing
Different MySQL APIs do not intermix with each other. Use the same MySQL API from connection to query.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Error reporting should only be done in staging, and never production.
Successful query or not:
To see if the query was indeed successful, or failed, check for errors and use affected_rows.
References:
http://php.net/manual/en/mysqli.error.php
http://php.net/manual/en/mysqli.affected-rows.php
PHP Not Inserting Content in mySQL Database: Text, Images, Anything
If you were trying to use images, then a valid enctype is required to be included in the form tags.
Depending on how/what you wanted to insert for the images, than that could be a factor.
If you're wanting to insert the image as a path is one thing, but using it "as an image", say a BLOB then that has limitations in size; use LONGBLOB and you must escape that data before going in the database.
Consult:
https://dev.mysql.com/doc/refman/5.0/en/blob.html
http://php.net/manual/en/features.file-upload.post-method.php
Try to generate the query first, then execute it...
$userREQ3 = " INSERT INTO `logindb`.`blog`
(`title`, `subtitle`, `content`) VALUES ('$title', '$subtitle','$content')";
mysqli_query($dbCon, $userREQ3);

Value from form doesn't appear in database properly

I just want to transfer the information from a text form into a database, but the value doesn't appear in the database properly. Here's what I have:
HTML code, for the form:
<form method="post" action="process.php">
<input type="text" maxlength="150" name="textbox">
<input type="submit" name="submit">
</form>
process.php
<?php
$con=mysqli_connect($host, $username, $password, $database);
$sql = mysqli_query($con,"INSERT INTO notes (User, Note)
VALUES ('test', '$_POST [textbox]')");
// I also tried writing $_POST ['textbox'] instead; didn't make a difference.
?>
However, the output in the database is as follows:
User: test
Note: Array [textbox]
How would I be able to correct the value in the Note column (i-e to make it the value entered in the form)?
First off...you had a space between $_POST and ['textbox'];
it shoulda just been $_POST['textbox']...
But also you need to sanitize the data first so...
Try this
$input = mysqli_real_escape_string($_POST['textbox']);
$sql = mysqli_query($con,"INSERT INTO notes (User, Note)
VALUES ('test', '$input')");
But really you should use PDO instead of the deprecated mysql_* functions...
Google PDO, and learn to do prepared statements.
Here it is with PDO...
$conn = new PDO("mysql:host=$host;dbname=$database",$username,$password);
$user = 'Test';
$note = $_POST['textbox'];
$sql = "INSERT INTO notes (User, Note) VALUES (:user,:note)";
$q = $conn->prepare($sql);
$q->execute(array(':user'=>$user,
':note'=>$note));
EDIT...
I also noticed your inputs aren't closed, there should be a / at the end of each...
<form method="post" action="process.php">
<input type="text" maxlength="150" name="textbox" />
<input type="submit" name="submit" />
</form>
You have a space between $_POST and [textbox]. $_POST is an array. Hence, Array [textbox], ie: ArraySPACE[textbox]
You should remove the space, then look into using prepared statements. You should not use user submitted data directly without sanitizing it first.
$sql = mysqli_query($con,"INSERT INTO notes (User, Note)
VALUES ('test', '{$_POST['textbox']}')");

Categories