PHP + MySQLi Query post null row - php

dear Stackoverflow users, I start learning PHP and MySQLi. And now I have some issues. On every page reload in DB added 1 full empty row, every cell is null. Can someone give me advice about issue? Code below:
PHP before html tag:
<?php
$mysqli = new mysqli("", "", "", "");
$mysqli->set_charset('utf8');
$name = $mysqli->real_escape_string($_POST['name']);
$email = $mysqli->real_escape_string($_POST['email']);
$link = $mysqli->real_escape_string($_POST['link']);
$query = "INSERT INTO demos (name, email, link) VALUES ('$name', '$email', '$link')";
$mysqli->query($query);
$mysqli->close();
?>
HTML inside body tag:
<form action="" method="post">
<input type="text" name="name" maxlength="20" required />
<input type="text" name="email" required />
<input type="text" name="link" required />
<input type="submit" value="Send" />
</form>

You should first check if your form is submitted by using isset or !empty.
By using isset, you can check wether or not a variable is set:
<?php
if(isset($_POST['name']) && isset($_POST['email']) && isset($_POST['link'])) {
// your code
}
?>
By using !empty, you can check if a variable is set and not empty. Note however that if you are using empty you can not submit a '0' or leave a field blank.
<?php
if(!empty($_POST['name']) && !empty($_POST['email']) && !empty($_POST['link'])) {
// your code
}
?>
Try using prepared statement for easier use and protection for SQL injection:
$stmt = $mysqli->prepare("INSERT INTO demos (name, email, link) VALUES(?, ?, ?)");
$stmt->bind_param("sss", $name, $email,$link);
$stmt->execute();
Read more about prepared statements: https://www.w3schools.com/php/php_mysql_prepared_statements.asp

Use var_dump to debug your code to make sure the values are not null
Add this before and after escaping the strings:
var_dump(array($name, $email, $link));
Also, switch to using prepared statements
$stmt = $mysqli->prepare("INSERT INTO demos (name, email, link) VALUES (?,?,?)");
$stmt->bind_param('sss', $name, $email, $link); // bind vars to the parameter
$stmt->execute(); // Execute statement

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 function returns no result

I wrote a simple php function in an attempt to learn php and functions within php.
The goal of the function is to upload a new user to a db
Here is my function
function upload_user($pId, $pName, $pEmail, $pPhone ){
$sql = "INSERT INTO users (member_id, name, email, phone) VALUES ('$pId', '$pName', '$pEmail', '$pPhone')";
mysql_query($sql);
}
Here Is my Form
<form name="register" method="post">
<input type="text" value="name" name="name">
<input type="text" value="email" name="email">
<input type="text" value="phone" name="phone">
<input type="submit" name="submit" value="register" />
</form>
if(isset($_POST['submit'])){
$id = rand(100, 10000);
$name = $_POST['name'];
$email= $_POST['email'];
$phone = $_POST['phone'];
upload_user($id,$name,$email,$phone);
}
I know I am connecting successfully to the db since I did a test to echo out if the connection is successful or not. I also have php errors switched onini_set('error_reporting', E_ALL); but it gives me no warnings or errors
My Problem
Nothing happens with the above function, i.e. the result is just blank. If anyone can point out to me what I am doing wrong it will be really appreciated.
I think most likely that the function doen't know about the database connection so you need to either pass the db connection object as a parameter to the function or use the global identifier inside the function.
function upload_user($dbconn, $pId, $pName, $pEmail, $pPhone ){
$sql = "INSERT INTO `users` (`member_id`, `name`, `email`, `phone`) VALUES ('$pId', '$pName', '$pEmail', '$pPhone')";
mysql_query($sql,$dbconn);
}
function upload_user($pId, $pName, $pEmail, $pPhone ){
global $dbconn;
$sql = "INSERT INTO `users` (`member_id`, `name`, `email`, `phone`) VALUES ('$pId', '$pName', '$pEmail', '$pPhone')";
mysql_query($sql,$dbconn);
}
Neither of these will return a value - what you return from the function is up to you , if indeed you even want to return a value. You could use the response from the query ( true or false ) as the return:
function upload_user($pId, $pName, $pEmail, $pPhone ){
global $dbconn;
$sql = "INSERT INTO `users` (`member_id`, `name`, `email`, `phone`) VALUES ('$pId', '$pName', '$pEmail', '$pPhone')";
return mysql_query($sql,$dbconn);
}
if(isset($_POST['submit'])){
$id = rand(100, 10000);
$name = $_POST['name'];
$email= $_POST['email'];
$phone = $_POST['phone'];
/* using ternary notation to echo something based on return value of function */
echo upload_user($id,$name,$email,$phone) ? 'Success' : 'Sorry, it failed';
}
You should be aware that certain words, in mysql and other rdbms, have special significance - so it is better to always ( imo ) to encase the field names in backticks. Also worth noting is that the mysql_* suite of functions are deprecated and it s advised to use either mysqli or pdo ~ and where you use user supplied content in your code ( form submission data generally or querystrings ) you should use prepared statements to guard against sql injection.
mysql accepts a link_identifier
link_identifier : The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If no connection is found or established, an E_WARNING level error is generated. reference
So you should pass a connection parameter as noted in other answers. After every connection made, you should close the connection so that you don't run into too manny connections server errors.

HTML Form won't submit to database

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.

How do I add a row to mysql db via php using controlled statements and html form for user input?

I am trying to build an "admin" section of my website. One where I can update customer status on work orders (or tickets if you prefer the term). I have it where I can input an int in a text field and hit submit to DELETE, but I cannot get my addRow function to work. It is not causing an error, which makes me believe that I am not passing my variables correctly.
Here are the forms on admin.php:
<form name="newRow" METHOD="post" ACTION="q.php">
Status of New Entry: <input type="text" value="Open" name="newStatus" /><br>
Type of Maintenance being completed: <input type="text" value="Software Maintenance" name="maintType" /><br>
<input type="submit" value="Add" name="newEntry" />
</form>
<form name="delRow" METHOD="post" ACTION="q.php">
<input type="text" name="deleteID" />
<input type="submit" value="Delete" name="delEntry"/>
</form>
As for my q.php, here is what I have after I connect to my db (which again, I have no problems using the delEntry/delRow section, so I can't see how a connection/mysqli initialization problem would be the issue:
//prepare statements
$addData = $conn->prepare("INSERT INTO $tname (status, mainttype) VALUES (?, ?)");
$addData->bind_param("s,s", $newStatus, $maintType);
$delData = $conn->prepare("DELETE FROM $tname WHERE id=?");
$delData->bind_param("i", $deleteID);
//end prepared statements
//if New Entry Button is pressed
$newStatus = isset($_POST['newStatus'])
? $_POST['newStatus']
: '';
$maintType = isset($_POST['maintType'])
? $_POST['maintType']
: '';
$addData->execute();
if ( false===$addData ) {
die('prepare() failed: ' . htmlspecialchars($mysqli->error));
}
else{
printf("rows inserted: %d\n", $addData->affected_rows);
}
//if Del Entry Button is pressed
if ( isset( $_POST['delEntry'] ) ) {
$deleteID = $_POST['deleteID'];
$delData->execute();
}
$addData->close();
$delData->close();
$conn->close();
?>
my columns are matching according to phpMyAdmin:
$addData = $conn->prepare("INSERT INTO $tname (status, mainttype) VALUES (?, ?)");
status and mainttype (yes 2 t). my ID (primary) is an auto_incriment so I left it out because I don't want to cause any key duplicate errors by accident. It's auto_incriment has been tested and seems to be working fine.
Too make it more fun, I added an echo $newStatus; after my prepared statement execution, and it comes back with the correct value. I appear to be having a problem with the addition of the new row. Still no error being generated.
printf("rows inserted: %d\n", $addData->affected_rows);
returns with 0 rows affected as well.
Simple comma issue. On:
$addData->bind_param("ss", $newStatus, $maintType);
I had it listed as:
$addData->bind_param("s,s", $newStatus, $maintType);

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