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).
Related
I have an HTML form that is fairly simple:
HTML:
<form method="POST" id="form-1" name="form-1">
<p>
<input type="text" name="fm1q1">
<input type="number" name="fm1q1-score">
</p>
<p>
<input type="text" name="fm1q2">
<input type="number" name="fm1q2-score">
</p>
<p>
<input type="text" name="fm1q3">
<input type="number" name="fm1q3-score">
</p>
<p>
<input type="text" name="fm1q4">
<input type="number" name="fm1q4-score">
</p>
<p>
<input type="text" name="fm1q5">
<input type="number" name="fm1q5-score">
</p>
<button type="submit" name="submit">SUBMIT</button>
</form>
I'm using a simple Ajax call:
$('#form-1').on('submit', function(e){
e.preventDefault();
$.ajax({
type: 'POST',
url: 'submitForm.php',
data: $(this).serialize(),
success: function(data){
console.log(data);
},
error: function(xhr, ajaxOptions, thownError){
console.log(xhr.status);
console.log(thrownError);
}
});
});
The PHP that inserts the form data into a MySQL DB Table is like this:
require "config.php"; // Contains all my connection information
$answers = array($_POST['fm1q1'], $_POST['fm1q2'], $_POST['fm1q3'], $_POST['fm1q4'], $_POST['fm1q5']);
$scores = array($_POST['fm1q1-score'], $_POST['fm1q2-score'], $_POST['fm1q3-score'], $_POST['fm1q4-score'], $_POST['fm1q5-score']);
for ($i = 0; $i < 5; $i++) {
$sql = "INSERT INTO table_1 (answer, score) VALUES ('$answers[$i]', '$scores[$i]')";
$result = mysqli_query($conn, $sql);
if (!$conn->query($result) === TRUE) {
echo "Error: " . $sql . "--" . $conn->error. "\n";
}
}
$conn->close();
The problem I'm running into is that my Developer Tools say I have a Syntax error in the $sql= line, but I can't see what's wrong.
Error: INSERT INTO table_1 (answer, score) VALUES ('test', '123')--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 '1' at line 1
You're trying to execute the query twice. Once here:
mysqli_query($conn, $sql)
and once here:
$conn->query($result)
And furthermore, in the second attempt you aren't executing the query but rather trying to execute the results of the query. I'm not sure why it's failing with that exact error message, but I'd certainly expect it to fail somehow.
What has you confused is that you're outputting your first query after having checked if your second query has failed. So you're misleading yourself in your debugging.
Just remove that second query attempt. You already have the results from the first one:
$result = mysqli_query($conn, $sql);
if ($result !== TRUE) {
echo "Error: " . $sql . "--" . mysqli_error($conn) . "\n";
}
You should definitely make the choice of whether to use the function notation or the object notation with mysqli, and stay consistent with your choice. Trying to mix the two might work in some cases but it's ultimately going to cause confusion like this.
Also, and this is important... Your code is wide open to SQL injection. PHP provides considerable information on what that means here. And this is a great starting point for correcting it. Regardless of how you approach it, the bottom line is that you should never put user-modifiable data directly into a query as though it's part of the code. This allows user to put actual code in your query.
Not the whole issue in your code - but the initial error message is due to the table name having an underscore.
Update your SQL query to:
"INSERT INTO `table_1` (answer, score) VALUES ('$answers[$i]', '$scores[$i]')";
That should resolve the mysql error you saw.
However - you also need to look into improving your query.
Look at escaping the values (never trust posted data that could be manipulated to just write to your database), or ideally use prepared statements.
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.
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);
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.
HTML
<form action="inc/q/prof.php?pID=<?php echo $the_pID; ?>" method="post">
<select id="courseInfoDD" name="courseInfoDD" tabindex="1"><?php while($row3 = $sth3->fetch(PDO::FETCH_ASSOC)) {
echo "<option>".$row3['prefix']." ".$row3['code']."</option>"; }echo "</select>"; ?>
<input type="text" id="addComment" name="addComment" tabindex="3" value="Enter comment" />
<input type="hidden" name="pID" value="<?php echo $the_pID; ?>">
<input type="submit" name="submit" id="submit" />
</form>
PHP
$connect = mysql_connect("##", $username, $password) or die ("Error , check your server connection.");
mysql_select_db("###");
//Get data in local variable
if(!empty($_POST['courseInfoDD']))
$course_info=mysql_real_escape_string($_POST['courseInfoDD']);
if(!empty($_POST['addComment']))
$course_info=mysql_real_escape_string($_POST['addComment']);
if(!empty($_POST['pID']))
$the_pID=mysql_real_escape_string($_POST['pID']);
print_r($_POST);
echo $the_pID;
// check for null values
if (isset($_POST['submit'])) {
$query="INSERT INTO Comment (info, pID, cID) values('$the_comment','$the_pID','$course_info')";
mysql_query($query) or die(mysql_error());
echo "Your message has been received";
}
else if(!isset($_POST['submit'])){echo "No blank entries";}
else{echo "Error!";}
?>
?>
Table
commId int(11)
info text
date timestamp
reported char(1)
degree char(1)
pID int(11)
cID int(11)
It gives me "Error!" now, I try the db credentials and they are fine... ?? And the r_post() is still giving an error of Array()
Why isn't Array() accepting values? Anyone???
Like #user551841 said, you will want to limit your possibility of sql injection with his code.
You are seeing that error because you're code told it to echo that error if nothing was entered, which is the case upon first page load. You shouldn't need that until submit is done.
Edit: Sorry, I was assuming you are directly entering the page which needs the $_POST data without going through the form submit.
You also should do something along the lines of if(!isset($variable)) before trying to assign it to something less your server will spit out error of undefined variables.
if(!empty($_POST['courseInfoDD']))
$course_info=mysql_real_escape_string($_POST['courseInfoDD']);
do that to all of them.
Then you can check
if (!isset($user_submitted) && !isset($the_comment) && !isset($course_info) && !isset($the_pID) ){
echo "All fields must be entered, hit back button and re-enter information";
}
else{
$query="INSERT INTO Comment (info, pID, cID) values('$the_comment','$the_pID','$course_info')";
mysql_query($query) or die(mysql_error());
echo "Your message has been received";
}
Check that the hidden field "pID" has a value set from value=<?php echo $the_pID; ?>
Make sure that your data is valid before checking it.
For instance do
print_r($_POST);
and check if the keys and their data match up.
Also, as a side note, NEVER do what you're doing with :
$query="INSERT INTO Comment (info, pID, cID) values('$the_comment','$the_pID','$course_info')";
This is how mysql injection happens, either use prepared statements or
$course_info= mysql_real_escape_string($_POST['courseInfoDD']);
To answer to your question what is wrong here
you've got a huge gaping SQL-injection hole!!
Change this code
//Get data in local variable
$course_info=$_POST['courseInfoDD'];
$the_comment=$_POST['addComment'];
$the_pID=$_POST['pID'];
To this
//Get data in local variable
$course_info = mysql_real_escape_string($_POST['courseInfoDD']);
$the_comment = mysql_real_escape_string($_POST['addComment']);
$the_pID = mysql_real_escape_string($_POST['pID']);
See: How does the SQL injection from the "Bobby Tables" XKCD comic work?
For more info on SQL-injection.
i would change this line
if (isset($_POST['submit'])) {
to
if ($_POST) {
the sumbit button field will not always be posted, for example if you press return on keyboard instead of clicking on the submit button with the mouse.
Cleaner:
$submit = isset($_POST['submit']) ? true : false;
$comment = isset($_POST['comment']) ? trim($_POST['comment']) : '';
if ($submit && $comment) {
$query = 'INSERT INTO comments (comment) values("' . mysql_real_escape_string($comment) . '")';
//...
}
As you can see I place the escaping inside the query. And this is a good idea because sometimes you loose track of the complete code and this won't happen inside a query.