INSERT INTO in php and SQL syntax error [closed] - php

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 7 years ago.
Improve this question
Im self learning mySQL and php few days and now Im stuck on this error and cant help myself. Can you look at code, Thanks!
this is error
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 ')' at line 7
here is the page
switch($_GET['action']) {
case 'add':
switch($_GET['type']) {
case 'movie':
$query = 'INSERT INTO
movie
(movie_name, movie_year, movie_type)
VALUES
("' . $_POST['movie_name'] . '",
' . $_POST['movie_year'] . ',
' . $_POST['movie_type'] . ')';
break;
}
break;
}
if (isset($query)) {
$result = mysql_query($query, $db) or die(mysql_error($db));
}
I think problem may be in here
<td><select name='movie_type'>
<?php
$query = 'SELECT movietype_label FROM movietype ORDER BY movietype_id';
$result = mysql_query($query, $db) or die (mysql_error($db));
while ($row = mysql_fetch_assoc($result)) {
foreach ($row as $value) {
echo '<option value="' . $row['movietype_id'] . '">';
echo $row['movietype_label'] . '</option>';
}
}
?>
</select></td>
and here is print_r on
Array(
[movie_name] => asd
[movie_type] =>
[movie_year] => 2015
[submit] => ADD)

Shouldn't you be using a double quote " instead of single quote ' like below. You are mixing single and double quote.
$query = "INSERT INTO
movie
(movie_name, movie_year, movie_type)
VALUES
('" . $_POST['movie_name'] . "',
'" . $_POST['movie_year'] . "',
'" . $_POST['movie_type'] . "')";

Granted this is ugly, but would be surprised if it fails.
$query = "INSERT INTO
movie (movie_name, movie_year, movie_type)
VALUES
('"
. $_POST['movie_name'] . "','"
. $_POST['movie_year'] . "','"
. $_POST['movie_type'] . "')";
Also, you need to cleanse your data. Data acted upon directly from user without cleansing, or sent through proper separation of code, can, and someday will, contain sql injection.
Ugly code like the above starts to take on some beauty with mysqli and pdo, plus the parameters are safely separated, and all the moaning about injection goes away.

Related

PHP SQL no results with strings [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 6 years ago.
Improve this question
I am currently using PHP and SQL to throw back some paramters I enter in a form.
I can search numbers perfectly fine and it gives me the correct results but anytime I use a search like "443265dsa44dd" it displays nothing even though it's in the database.
$searchedID = $_POST['uuid'];
$sql = "SELECT name, contact, phone, address FROM test WHERE id = '.$searchedID.'";
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo "Name: " . $row["name"] . "<br>" . "Contact: " . $row["contact"] . "<br>" . "Phone: " . $row["phone"] . "<br>" . "Address: " . $row["address"] . " ";
}
}
The id is a primary key and set to VARCHAR, any ideas what is happening here?
You have an error when trying to include the searchedID into the sql-string.
Either concat like this:
$sql = "SELECT name, contact, phone, address FROM test WHERE id = '" . $searchedID . "'"
// note, the additional quotes
OR
let php parse that var for you (possible only inside double-quotes):
$sql = "SELECT name, contact, phone, address FROM test WHERE id = '$searchedID'"
BUT
You are vulnerable to sql-injection. So use prepared statements!

Inserting multiple session variables from PHP into mySQL database, why isn't it working [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
Hi I cannot get the below query to work in order to insert the session data into the database, Could anyone please tell me what is wrong with it or what I can do to fix it? Thanks in advance.
<?php
session_start();
if (isset($_POST['sub'])) {
$host='localhost';
$user='root';
$pass='';
$db='theatre_booking';
$con=mysqli_connect($host,$user,$pass,$db);
$row = $_POST['row'];
$_SESSION["row"]=$row;
$zone = $_POST['zone'];
$_SESSION["zone"]=$zone;
$quantity = $_POST['numberOfTickets'];
$_SESSION["numberOfTickets"]=$quantity;
$sql="INSERT INTO booking(PerfDate, PerfTime, Name, Email, RowNumber)
VALUES
'{$_SESSION['date']}',
'{$_SESSION['time']}',
'{$_SESSION['name']}',
'{$_SESSION['email']}',
'{$_SESSION['row']}')";
if ($con->query($sql) === TRUE) {
echo "Booking successful";
} else {
echo "Error: " . $sql . "<br>" . $con->error;
}
}
?>
you are missing opening bracket '(' after values in insert statement.
$sql="INSERT INTO booking(PerfDate, PerfTime, Name, Email, RowNumber)
VALUES (
'{$_SESSION['date']}',
'{$_SESSION['time']}',
'{$_SESSION['name']}',
'{$_SESSION['email']}',
'{$_SESSION['row']}')";
if ($con->query($sql) === TRUE) {
echo "Booking successful";
} else {
echo "Error: " . $sql . "<br>" . $con->error;
}
Missing opening parenthesis after VALUES and I suggest you explicitly write the variables in the string.
Don't rely on php variable expansion, it's also much easier to read.
$sql='INSERT INTO booking(PerfDate, PerfTime, Name, Email, RowNumber)
VALUES
("' . $_SESSION["date"] . '",
"' . $_SESSION['time'] . '",
"' . $_SESSION['name'] . '",
"' . $_SESSION['email'] . '",
"' . $_SESSION['row'] . '"
)';

Why my queries work weirdly? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I get this two queries with the same variables :
$query = 'UPDATE payee SET payee="oui", datePaiement=\'' . $datePaiement . '\',paiement="'.$paiement.'", typePaiement="' . utf8_decode($moyenPaiement) . '" WHERE id_commande=' . $commande->getNum() . '';
$connexion->exec($query);
$query2 = 'UPDATE commande SET mpaiement="' . utf8_decode($moyenPaiement) . '",pxttc="'.$paiement.'" WHERE noCommande=" . $commande->getNum() . "';
$connexion->exec($query2);
For the first one, my $paiement isn't save in my DB. I get a $paiement = 0 while in my second one $paiement is save as I want.
I have the same pattern in my second query $moyenPaiement, moyenPaiement is save as I want but he is not save in my first query.
Sorry for my explanation, it's maybe confused.
You should not combine both single and double quotes, it will be confusing. Try this:
$query = 'UPDATE payee SET payee="oui", datePaiement="' . $datePaiement . '", paiement="'.$paiement.'", typePaiement="' . utf8_decode($moyenPaiement) . '" WHERE id_commande="' . $commande->getNum() . '"';
$connexion->exec($query);
$query2 = 'UPDATE commande SET mpaiement="' . utf8_decode($moyenPaiement) . '", pxttc="'.$paiement.'" WHERE noCommande="' . $commande->getNum() . '"';
$connexion->exec($query2);
Later edit:
Don't forget to print your queries if something weird happens. These queries can be tested in phpMyAdmin too.
print_r($query);

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

parsing error at line 17 how to fix it

It is showing parsing error on line 17 I have thoroughly checked it but unable to find error.So how do I fix this error.it is insert_city_query.php
<?php
include('../../Connections/autodealers.php');
//error_reporting(0);
$cityname=$_POST['cityname'];
$cityorder=$_POST['cityorder'];
$status=$_POST['status'];
if($status="Enabled")
$status=1;
else
$status=0;
$query = "INSERT INTO ".$db_prefix."city (cityname,cityorder,status) values
(
'" . addslashes($cityname) . "' ,
'" . addslashes($cityorder) . "' ,
'" . addslashes($status) . " '
WHERE LCASE='strtolower($_REQUEST['cityname'])')";
echo $query;
$result=mysql_query($query);
if(!$result)
{
die ('ERROR: '.mysql_error());
header("Location: " .$base_url. "admin/city_insert.php" );//if query fails
}
else
{
header("Location: " .$base_url. "admin/cities.php" );//if query suceeds
}
mysql_close($autodealers);
?>
Change your query to,
$query = "INSERT INTO ".$db_prefix."city (cityname,cityorder,status) values
('" . addslashes($cityname) . "' ,
'" . addslashes($cityorder) . "' ,
'" . addslashes($status) . " '
WHERE LCASE='" . strtolower($_REQUEST['cityname']) . "')";
Note: Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
Warning: The query is vulnerable with SQL Injection if the value (s) of the variables came from the outside. Please take a look at the article below to learn how to prevent from it.
How to prevent SQL injection in PHP?
You do not use strtolower() as a function.
You should change this line:
WHERE LCASE='strtolower($_REQUEST['cityname'])')";
to
WHERE LCASE='".strtolower($_REQUEST['cityname'])."')";

Categories