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

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

Related

Eror in SQL syntax: Update query

I am a beginner to PHP and I am working on a profile page. The current problem is to change the name (This is a trial page that's why i am changing the name).For some reason i am getting the error:
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'lastName ='Lname' WHERE email ='qwerty#example.com'' at line 1.
<?php
include('server.php');
$db = mysqli_connect('localhost','root','','userdata');
$query = "SELECT * FROM data WHERE email = '".$_SESSION['username']."'";
$result = mysqli_query($db,$query);
$data = mysqli_fetch_assoc($result);
?>
<html>
<head>
<title>Profile</title>
</head>
<body>
<form method="POST" action="">
<p>First name: <input type="text" name="fname" value="<?php echo htmlspecialchars($data['firstName']); ?>" > </p>
<p>Last name: <input type="text" name="lname" value="<?php echo htmlspecialchars($data['lastName']); ?>"> </p>
<p><input type="Submit" name="confirm" value="Confirm"></p>
</form>
<?php
if(isset($_POST['confirm']))
{
$db = mysqli_connect('localhost','root','','userdata');
$query = "UPDATE data SET firstName ='".$_POST['fname']."' lastName ='".$_POST['lname']."' WHERE email ='".$_SESSION['username']."'";
mysqli_query($db,$query);
echo mysqli_error($db); //For checking error.Remove afterwords.
}
?>
<p>HOMEPAGE</p>
</body>
</html>
The server.php is a page where I manage the backend of the entire operation so it's not involved in this operation.The first PHP block takes data from the table. The HTML block creates a form where the user can edit the data. The PHP block should update data into the table.
I would appreciate any tips to further improve my page as i am still new to this.Thanks in advance
UPDATE:- Adding , to the query still does not change the situation.
you have an error in your sql statement (as the error message suggests). in mysql the error message usually points out the exact position where the error occurs, and it usually quotes the first character/word that causes the problem.
in your case, that's lastname. Your update query so far is:
UPDATE data SET firstName ='fname' lastName ='Lname' WHERE email ='qwerty#example.com'
-- ^ error occured here
when you look-up how UPDATE queries are supposed to look like (mysql docs) you'd find, that the different updated fields must be separated by comma:
UPDATE data SET firstName ='fname', lastName ='Lname' WHERE email ='qwerty#example.com'
-- ^ add this here
also, you're vulnerable to sql injections (please read up on them, and how to prevent them - this is done by prepared statements)
Please try with that(there was a missing comma on your SQL query).
$query = "UPDATE data SET firstName ='".$_POST['fname']."', lastName ='".$_POST['lname']."' WHERE email ='".$_SESSION['username']."'";
The other problem of using code that is open to sql injection is you can easily change the syntax of an sql statement from the input side. For example if for last name you input "O'connor", you change the syntax. Try to use echo $query and then analyse the output or better still,copy it and run it directly without using php
As mentioned in the comment. When updating multiple fields you need to comma separate them:
UPDATE data
set
field1="meh", /* <-- comma */
field2="foo"
where otherField="something"

Insert data from form into table not working, returns no error

I have created a form with a simple image upload (which i have previously used) and a few fields on. I am trying to get the data from this to insert into my mysql database but this isnt working as hoped. I cannot see anything wrong from my end.
<?php
error_reporting(E_ALL);
ini_set('error_reporting', 1);
require_once('../../includes/connection.inc.php');
if(isset($_POST['submit']))
{
$dir1 = '/xampp/htdocs/manchesterunited/img/teams/';
$file = $dir1 . basename($_FILES['file']['name']);
$name = $_FILES['file']['name'];
$temp = $_FILES['file']['tmp_name'];
move_uploaded_file($temp,$file);
mysqli_query($mysqli, "INSERT INTO league-table VALUES ('','".$_POST['team']."', '0','0','0','0','0','0','0','$name')");
}
?>
<!doctype html>
<html>
<head>
<title>Add team</title>
</head>
<body>
<a>Add Team To League</a>
<form action="add-team.php" method="POST" enctype="multipart/form-data">
<p><label for="file">Please select the team's badge: </label><input type="file" name="file"/></p>
<p><label for="team">Please enter the team:</label><input type="text" name="team"/></p>
<p><input type="submit" name="submit" value="Add"/></p>
</form>
<?php
if(isset($_POST['submit']))
{
echo "<br />Team has been added.";
}
?>
</body>
</html>
It doesn't return an error because you didn't check for (MySQL) errors in:
INSERT INTO league-table
MySQL sees that as league MINUS table
So, wrap it in ticks
INSERT INTO `league-table`
Or rename the table name using an underscore.
http://php.net/manual/en/mysqli.error.php
Adding or die(mysqli_error($mysqli)) to mysqli_query() would have thrown you something about it.
You're also open to an SQL injection. Use a prepared statement.
https://en.wikipedia.org/wiki/Prepared_statement
However, this:
if(isset($_POST['submit']))
{
echo "<br />Team has been added.";
}
You're better off using a conditional statement for your query instead.
Plus, you have the same conditional statement twice.
In a nutshell:
if(query) successful, echo success.
else, do error handling.

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 code not working as expected form will not submit the correct data

so I've got this code that supposedly sends you an email after you entered a valid one and answered a security question. My problem is the fact that the form won't submit the answer i've given it. It always echoes "submit" on the begging of the second php block. Also if u can spot any other errors i might have missed let me know please. Thanks anticipated.
<?php
define ('DB_SERVER','fenrir');
define ('DB_USERNAME','ArchivrTW');
define ('DB_PASSWORD','vPOZOa1txS');
define ('DB_DATABASE','ArchivrTW');
$connection = mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);
if(!$connection)
{
die('Could not connect because: ' . mysql_error());
}
?>
<?php
$test = $_POST['email'];
$query = "SELECT 'EMAIL' FROM 'USERS' WHERE 'EMAIL'=$test";
echo(strlen($query));
if(strlen($query) > 42)
{
$query1 = "SELECT 'SecurityQ' from 'USERS' WHERE 'EMAIL' =$test";
$query2 = "SELECT 'SecurityA' from 'USERS' WHERE 'EMAIL' =$test";
$result = mysqli_query($connection,$query);
$result1 = mysqli_query($connection,$query1);
$Results = mysqli_fetch_assoc($result);
$Results1 = mysqli_fetch_assoc($result1);
$Results2 = mysqli_fetch_assoc($result2);
echo($Results1);
}
?>
<form action="recover.php" method="post">
<p>Security Question Answer: <input type="text" name="answer" placeholder="Type your answer here" /> </p>
<p><input type="submit" name="answer" id="answer" /> </p>
</form>
<?php
$answer=$_POST['answer'];
echo($answer);
if (count($Results) >= 1 && strcmp($_POST['answer'],$Results2) == 0)
{
$REQ_STATUS = 1;
$new_passwd = rand(1,1000000);
$to = $email;
$subject = "Archivr-Forgot Password";
$msg = "Use this generated password to log in then change it using the Edit Profile Menu";
mail($to, $subject, $msg);
}
else
{
$message="Account not found or wrong security question answer";
}
if($REQ_STATUS == 1)
{
$update_query="UPDATE USERS set PASSWORD =".$new_passwd." where EMAIL ='". $to ."'";
}
?>
</body>
</html>
The first block works, problem is the form or the second block.
You are vulnerable to sql injection attacks;
You have duplicate field names:
<p>Security Question Answer: <input type="text" name="answer" placeholder="Type your answer here" /> </p>
^^^^^^^^^^^^
<p><input type="submit" name="answer" id="answer" /> </p>
^^^^^^^^^^^^^
Since the field names are the same, the submit button overwrites/replaces the text field, and you end up submitting a blank value.
You're using the incorrect identifier qualifiers for all your tables and columns being single quotes and not wrapping the $test variable in quotes; it's a string.
This one for example:
SELECT 'EMAIL' FROM 'USERS' WHERE 'EMAIL'=$test
should read as
SELECT `EMAIL` FROM `USERS` WHERE `EMAIL`='$test'
where you may have seen a tutorial somewhere, that the ticks resembled regular single quotes. They are not the same; those are two different animals altogether.
You will then need to follow the same method above and do the same for the rest of your queries.
Using this for example:
$result = mysqli_query($connection,$query) or die(mysqli_error($connection));
would have signaled a syntax error.
Then this mysql_error() - That should read as mysqli_error($connection). You cannot mix MySQL APIs. They do not intermix with each other.
You also don't seem to be doing anything with:
$update_query="UPDATE USERS set PASSWORD =".$new_passwd." where EMAIL ='". $to ."'";
Whether it's relevant to the question or not, you're not actually executing that 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.
References:
https://dev.mysql.com/doc/refman/5.0/en/identifier-qualifiers.html
http://php.net/manual/en/mysqli.error.php
Footnotes:
Your present code is open to SQL injection. Use prepared statements, or PDO with prepared statements, they're much safer.
Plus, since you're using the entire code in one file, you will get warnings to the effect of "Undefined index xxx....", therefore you will need to use a conditional isset() and or !empty() around your executable code and for the POST arrays.
Passwords:
I'm hoping you're using a modern-day password hashing method, since this looks to me, being related to resetting passwords.
For password storage, use CRYPT_BLOWFISH or PHP 5.5's password_hash() function. For PHP < 5.5 use the password_hash() compatibility pack.
Both your form field and your submit button have a name of "answer". Rename your submit button name to "submit" or something else.

Empty rows created by refreshing page

I've searched on the Internet to get my answer, but I couldn't find a helpful one. I've got a page called 'post.php' with a form where I can add an image and submit it to the database.
The big problem is when I go to mysite.com/post.php a new empty row is created automatically in the database, which I clearly don't want. I want only to update the database after clicking on the submit button my code:
the part of INSERT:
<?php
// POST.PHP POSTING NEW CONTENT
include 'config.php';
// values from form
$id=$_POST['id'];
$title=$_POST['title'];
$pic=$_POST['pic'];
$youtube=$_POST['youtube'];
$cat=$_POST['cat'];
// insert data to mysql
$sql = "INSERT INTO post(id, title, pic, youtube, cat)VALUES('$id', '$title', '$pic', '$youtube', '$cat')";
$result=mysql_query($sql);
// succes added
if(!$result){
echo "Something went wrong!";
}
else {
echo "Yeah, buddy! Your content is added.";
}
// end of post script ^^
?>
// end of insert
//POST IMAGE PAGE
if(isset($_GET['pic'])) {
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
title: <input name="title" type="text" id="title"><br />
Add url of image;<br />
<input type="text" name="pic" id="pic"/><br />
<?php
echo '
Category game:
<select name="cat"> ';
$query2 = mysql_query("SELECT * FROM `category`");
while($row=mysql_fetch_array($query2)){
echo '
<option value="'.$row["nameID"].'">'.$row["name"].'</option> ';
}
?>
</select>
<input type="submit" onclick="this.disabled = true" name="submit" value="submit">
</form>
<?php
// end script of posting picture
}
?>
You need to add some conditional code around the part that inserts into the database, checking for if any values has been received (if($myvar){ // do stuff }).
Add the rest of your code, specifically the part that adds stuff to the database as that is what's causing you problems, not the code you posted.
You need to wrap the whole block of database insertion code in an if statement. That way, it will not execute until the form has been submitted and $_POST['submit'] has a value:
include 'config.php';
if (isset($_POST['submit'])){
// values from form
$id=$_POST['id'];
// etc... code stays the same down to:
echo "Yeah, buddy! Your content is added.";
}
}//end if (don't forget to add this last bracket)
Also, you should switch to mysqli or PDO, and use parameterized queries. Otherwise, your site is open to a variety of gnarly attacks via SQL injection. It's not that hard to switch, and very, very important.
Check if the post have been set on the file that handles the database input.
if(isset($_POST['pic'])){
//do something
}
else{ // handle the exeption}
Also, you should not use mysql_* functions anymore. they are unsafe and deprecated as-of php 5.5

Categories