PHP Form Submission - Syntax Errors - php

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.

Related

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

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

pg_query(): Query failed: ERROR: column "x" does not exist LINE 2: SET name=x

I have been working on something like a sign up form for a facebook app but instead of INSERT it UPDATE because before that I have already INSERT
$inserP = "INSERT INTO particular (id, name)
VALUES ($userid, 0)";
pg_query($conn, $inserP);
and I come across this error after submitting the form with the username tom:
pg_query(): Query failed: ERROR: column "tom" does not exist LINE 2: SET name=tom
Here is my form
<form action="update.php" method="post">
<input type="text" name="username" id="username" autocomplete="off" />
<input type="image" name="confirm" src="/images/confirm.png"/>
</form>
Here is my update.php
require('conn.php');
require('getfacebookapi.php');
$userid = idx($facebook->api('/me/'), 'id', string);
$username=$_POST['username'];
$pszz = "UPDATE particular
SET name=$username
WHERE id=$userid";
if(preg_match("/^[a-zA-Z]+$/", $username)) {
pg_query($conn, $pszz);}
There is absolutely nothing wrong with my pg_pconnect.. Can someone tell me where I went wrong and how to fix this error? I'm new to both php and sql... Thanks!!
Never, never compose SQL statements by string concatenation or interpolation. Use bind parameters (PDO or at least pg_query_params).
You need to put quotes around your strings values, otherwise it will think it's a column.
SET name='tom'
WHERE id='someid'
name is a text field; inserting into text fields requires single-quotes around the value: 'tom'

what is the equivalent of ispostback(.NET) in PHP?

I just start coding in PHP,
i wrote my first php + mysql program for inserting data through web form. it works fine, but whenever i refresh the page, it automatically saves null record to my database.
i know the solution in .NET is ispostback, but not in php?
can somebody give me some idea in PHP.
Code is here:
<body>
<form action="mySQLTest.php" method="post">
First Name :<input type="text" name ="txtFirstName"/> <br/>
Last Name: <input type="text" name ="txtLastName"/> <br/>
Age : <input type="text" name= "txtAge" /> <br/>
<input type="submit"/>
</form>
<?php
$con = mysql_connect("localhost","root","");
if(!$con)
{
die('Could not Connect:' .mysql_error());
}
mysql_select_db("test", $con);
if($_REQUEST[])
{
$sql1 = "Insert into info(FirstName, LastName, Age) Values('$_POST[txtFirstName]','$_POST[txtLastName]','$_POST[txtAge]')";
}
if(!mysql_query($sql1, $con))
{
die('Error: '.mysql_error());
}
else
{
echo "1 Record Added";
}
mysql_close($con)
?>
</body>
Have you tried if ($_SERVER['REQUEST_METHOD']=='POST')
updated answer:
if ($_SERVER['REQUEST_METHOD']=='POST') {
[insert...]
header('Location: added_record.php');
}
When you use the POST-method, it's better (imho) to use $_POST rather than $_REQUEST. To check whether you have data, you could use isset($_POST['txtFirstName']);. If you need all data, it's best to do this for all input fields, resulting in
if(isset($_POST['txtFirstName']) && isset($_POST['txtLastName']) && isset($_POST['txtAge'])) {
// do stuff
}
If you want to know if there was any field submitted using post, you could use if(!empty($_POST)) {.
On a side note: I know you are just starting PHP, it could be quite dangerous to use user-generated code in queries. When you are building stuff online, for everyone to reach, please read a bit about SQL injection. This will also prevent your code from breaking when someone enters an apostrophe (').

Categories