Error 500 when using variables to instert to SQL database [duplicate] - php

This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
Closed 5 years ago.
I got this code, and it gives me an error 500.
I probaly got something wrong here, but i really need some help.
Here's my code
<?php include('index.php'); ?>
<?php include('config.php'); ?>
<?php
$fornavn = $_POST['fornavn'];
$efternavn = $_POST['efternavn'];
$postnummer = $_POST['postnummer'];
$alder = $_POST['alder'];
$sql = INSERT INTO medlemmer (fornavn, efternavn, postnummer, alder)
VALUES ('$fornavn', '$efternavn', '$postnummer', '$alder');
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
The POST tag is the same in index.php and so.
Please help.
Thanks in advance!

You need to put your query in string "" first
<?php include('index.php'); ?>
<?php include('config.php'); ?>
<?php
$fornavn = $_POST['fornavn'];
$efternavn = $_POST['efternavn'];
$postnummer = $_POST['postnummer'];
$alder = $_POST['alder'];
$sql = "INSERT INTO medlemmer (fornavn, efternavn, postnummer, alder)
VALUES ('$fornavn', '$efternavn', '$postnummer', '$alder');";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Also use prepared statement to prevent from sql injection
Turn PHP error ON so that you can get errors. Add following line in your PHP file
ini_set('display_errors',1);
error_reporting(E_ALL);

to first see any more possible errors, as it may help to find the problem type this at the beginning:
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
Personally as I always used "" around the SQL-Query, and I see you haven't done it, maybe you should add them too so make it:
$sql = "INSERT INTO medlemmer (fornavn, efternavn, postnummer, alder)VALUES
('$fornavn', '$efternavn', '$postnummer', '$alder')";
Also I assume $conn is defined in your config.php?

As mentioned in comments first make sure you have error reporting enabled error_reporting(E_ALL); and ini_set('display_errors',1).
Also look at this SQL query string which hasn't been wrapped in quotes.
$sql = INSERT INTO medlemmer (fornavn, efternavn, postnummer, alder)
VALUES ('$fornavn', '$efternavn', '$postnummer', '$alder');
Should be
$sql = "INSERT INTO medlemmer (fornavn, efternavn, postnummer, alder)
VALUES ('$fornavn', '$efternavn', '$postnummer', '$alder')";

Related

PHP and SQL uploading error [duplicate]

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 4 years ago.
I have a problem, I can't upload anything to database. In my database in the jelenlet table there is a jelen which is integer and a gyerekneve which is text.
Here is my php code:
<?php
$servername = "...";
$username = "...";
$password = "...";
$dbname = "...";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO 'jelenlet' ('gyerekneve', 'jelen') VALUES ('barmi', 0)";
if ($conn->query($sql) === TRUE) {
echo "Hozzaadtad ezt a nevet: ";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
And don't know what is the problem with the code. The page says:
Error: INSERT INTO 'jelenlet' ('gyerekneve', 'jelen') VALUES ('barmi',
0) You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near ''jelenlet' ('gyerekneve', 'jelen') VALUES ('barmi', 0)' at line
1
$sql = "INSERT INTO jelenlet (gyerekneve, jelen) VALUES ('barmi', 0)";
This will work. BUT make sure to use prepared statements when you will try to pass variables to this one and not static values. The problem was that you were using single-quotes when you didn't have to. If you want to escape fields in a query you can use this : `
This query would also work :
$sql = "INSERT INTO `jelenlet` (`gyerekneve`, `jelen`) VALUES ('barmi', 0)";

i can't find any error

can't reach header.php???
if ($_SERVER["REQUEST_METHOD"] == "POST") { $name = $_POST["firstname"]; $lastname = $_POST["lastname"]; $email = $_POST["email"]; $password = $_POST["password"]; $mobile = $_POST["mobile"]; $office_num = $_POST["office"];
$sql = mysqli_query($dbcon,"insert into `user_info`(`firstname`, `lastname`, `email`, `password`, `mobile`,`office_contact`) values('$name','$lastname','$email', '$password', '$mobile', $office_num)");
if (mysqli_query($dbcon, $sql)) {
echo "New record created successfully";
header("Location: header.php");
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($dbcon); } ?>
This is the error I am receiving:
Error: 1
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
The problem here is that you're using mysqli_query() twice.
$sql = mysqli_query($dbcon,"insert into... $office_num)");
^^^^^^^^^^^^ There
if (mysqli_query($dbcon, $sql))
^^^^^^^^^^^^ and there
The conditional statement is calling it again. You need to remove the first query call, which explains the 1 coming back as the error.
Your code is also prone to an sql injection; use a prepared statement:
https://en.wikipedia.org/wiki/Prepared_statement
You're also outputting before header with the following lines of code:
echo "New record created successfully"; // << Remove this line
header("Location: header.php");
Remove the echo statement for it and add exit; after header to avoid further execution.
Note: Make sure that the value for $office_num is indeed an integer such as 5551234 and not 555-1234. If it is the latter, you will need to wrap that variable with quotes as you did for the other string values.
Don't store plain text passwords, especially if you're going live with this.
Use password_hash() and password_verify() and please read over those manuals attentively:
http://php.net/manual/en/function.password-hash.php
http://php.net/manual/en/function.password-verify.php

Data which is succesfully added in database, doesnt show in database

im adding data in databese with php and received "succesful" but when i look into the database the data which is i have just added doesnt show. Here my codes
<?php
require ('db.php');
#$name = $_POST['name'];
#$surname = $_POST['surname'];
#$number = $_POST['number'];
#$mail = $_POST['mail'];
#$note = $_POST['note'];
$sql = "INSERT INTO customersinfo (name,surname,number,email,notes) VALUES ($name,$surname,$number,$mail,$note)";
$con->query($sql);
if ($sql)
{
echo "Succesful";
}
else
{
echo "error";
}
?>
this is also my db.php codes ;
<?php
$con = mysqli_connect("localhost","root","","customers");
if (mysqli_connect_errno()) {
printf(" Connection error :( %s\n", mysqli_connect_error());
exit();
}
?>
i also have one more question. When i try to add data in databese with mysqli_query() function, it doesnt work. for example;
mysqli_query($con, "INSERT INTO customersinfo (name,surname,number,email,notes) VALUES($name,$surname,$number,$email,$note)");
because of this , i had to use this code,its working now but i have no idea why mysqli_query() function is doesnt work
$sql = "INSERT INTO customersinfo (name,surname,number,email,notes) VALUES ($name,$surname,$number,$mail,$note)";
$con->query($sql);
if you help me it would be great, thank you.
Put single quote(') in values like this
$sql = "INSERT INTO customersinfo (name,surname,number,email,notes) VALUES ('$name','$surname','$number','$mail','$note')";
You are checking just $sql variable which doesn't provide sql resul, it's just a query.
Try
$result = $con->query($sql);
if($result)
{
echo "Succesful";
}else{
echo "error";
}
More proper way:
$sql = "INSERT INTO `customersinfo`
(`name`,`surname`,`number`,`email`,`notes`) VALUES
('{$name}','{$surname}','{$number}','{$mail}','{$note}')";
$result=$con->query($sql);
if (!$result) {
// Query has failed
}
You checked $sql in if condition which is not right because $sql is always true so that u get the result successful but actually value is not getting inserted in database.
take the result in some variable and used that in if condition.
after that you will get what actual error in your code.

insert into table error [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
here is my code
<?php
require '../connect/conn.php';
$quest = $_POST['domanda'];
$a1 = $_POST['risposta1'];
$a2 = $_POST['risposta2'];
$a3 = $_POST['risposta3'];
$a4 = $_POST['risposta4'];
$ins = "INSERT INTO melaraider SET domanda = '$quest',riposta1 = '$a1',riposta2 = '$a2',riposta3 = '$a3',riposta4 = '$a4'";
$result = mysqli_query($con, $ins);
if(!$result){
die("query error $ins:" . mysql_error());
}
mysql_close();
echo "all done!";
?>
everytime I execute that code I get a query error:
query error INSERT INTO melaraider SET domanda = 'quanto fa 2 +2?',riposta1 = '4',riposta2 = '6',riposta3 = '9',riposta4 = '2':
I really don't understand what is my mistake...
can someone please help me out?
Its a local test so I cant show a live version.
Try this code:
<?php
require '../connect/conn.php';
$quest = $_POST['domanda'];
$a1 = $_POST['risposta1'];
$a2 = $_POST['risposta2'];
$a3 = $_POST['risposta3'];
$a4 = $_POST['risposta4'];
$ins = "INSERT INTO melaraider (domanda, riposta1, riposta2, riposta3, riposta4) VALUES('" . $quest . "','" . $a1 . "','" . $a2 . "','" . $a3 . "','" . $a4 . "')";
$result = mysqli_query($con, $ins);
if(!$result){
die("query error $ins:" . mysql_error());
}
mysql_close();
echo "all done!";
?>
I believe your syntax is a little off. If using all the fields just specify just the data:
$ins = "INSERT INTO melaraider VALUES ('$quest','$a1',$a2','$a3','$a4')";
or specify the fields then data
$ins = "INSERT INTO melaraider (domanda,riposta1,riposta2,riposta3,riposta4)
VALUES ('$quest','$a1',$a2','$a3','$a4')";
http://www.w3schools.com/php/php_mysql_insert.asp
EDIT: Not quite fast enough!
You are using a combination of INSERT + UPDATE code, you can see here the full insert options.
In your case you should use
$ins = "INSERT INTO melaraider('domanda', 'riposta1', 'riposta2', 'riposta3', 'riposta4') VALUES('$quest','$a1','$a2','$a3','$a4');";
Cheers!
You are using the wrong syntax for an INSERT query.
Here are the docs:
http://dev.mysql.com/doc/refman/5.6/en/insert.html
Your query should look like:
INSERT INTO melaraider (domanda, riposta1, riposta2, riposta3, riposta4) VALUES ('$quest', '$a1', '$a2', '$a3', '$a4');
However, before you go any further with this code, you need to look into properly sanitizing your inputs. You should never directly put POST data into a query. See: What's the best method for sanitizing user input with PHP?
You should use Mysqli and not Mysql, you mixed them togheter.
Your insert query syntax was also wrong.
<?php
require '../connect/conn.php';
$quest = $_POST['domanda'];
$a1 = $_POST['risposta1'];
$a2 = $_POST['risposta2'];
$a3 = $_POST['risposta3'];
$a4 = $_POST['risposta4'];
$ins = "INSERT INTO melaraider (domanda, riposta1, riposta2, riposta3, riposta4)
VALUES ('$quest', '$a1', $a2', '$a3', '$a4')";
$result = mysqli_query($con, $ins);
if(!$result){
echo "query error $ins:" . mysqli_error($con); //Changed from mysql_error(). Changed from die() to echo, because you always should do mysqli_close()
} else {
echo "all done!";
}
mysqli_close($con); //changed from mysql_close()
?>
Like #patsweet said, you should think about sanitize the data before executing the query.
Change
$ins = "INSERT INTO melaraider SET domanda = '$quest',riposta1 = '$a1',riposta2 = '$a2',riposta3 = '$a3',riposta4 = '$a4'";
to this:
$ins = "INSERT INTO melaraider(domanda, riposta1, riposta2, riposta3, riposta4) VALUES('$quest','$a1', '$a2', '$a3', '$a4')";
NB: You only use SET when you are updating a value on the database.
For Example:
$ins = "UPDATE melaraider SET domanda = '$quest' WHERE mel_id = some_id";

failed to insert multiple data in mysqli using loop

I want to store one's friends of facebook into a table. The result of below code shows only a single record is inserted. It wasn't the problem of my loop because I echo the name, it all appeared.
foreach($user_friends['data'] as $friend){
//echo $friend['name'] . "</br>";
$userImg = "https://graph.facebook.com/".$friend['id']."/picture?width=200&height=200";
$friendsName = $friend['name'];
$stmt3 = $db->prepare("INSERT INTO allfriend(`uId`,`name`,`img`,`friendOf`) VALUES (?,?,?,?)");
$stmt3->bind_param('ssss', $user_fbid, $friendsName, $userImg, $user_fbid);
$stmt3->execute();
}
You're misusing the prepare / bind feature slightly. You only need to prepare once, but you do need to reset the statement after each use.
Also, you should check for failure of your statements. If you do that you may find out why things might work differently from what you expect.
Is it possible your column friend.uID is in fact a primary key? The code you've shown tries to insert the same value into multiple rows. That could be your problem.
Try this:
$stmt3 = $db->prepare
("INSERT INTO allfriend(`uId`,`name`,`img`,`friendOf`) VALUES (?,?,?,?)")
|| die "prepare failed: ". $db->error;
foreach($user_friends['data'] as $friend) {
//echo $friend['name'] . "</br>";
$userImg = "https://graph.facebook.com/".$friend['id']."/picture?width=200&height=200";
$friendsName = $friend['name'];
$stmt3->bind_param('ssss', $user_fbid, $friendsName, $userImg, $user_fbid)
|| die "bind_param failed " . $db->error;
$stmt3->execute()
|| die "execute failed " . $db->error;
$stmt3->reset()
|| die "reset failed " . $db->error;
}

Categories