<?php
mysql_connect("mysql6.000webhost.com","a6124751_murali1","***");
$db= mysql_select_db("a6124751_signup");
$topic=$_GET["Topic"];
$question=$_GET["Question"];
$company =$_GET["Company"];
$query = "INSERT INTO questions (topic, question, company) VALUES ($topic, $question, $company)";
$sql1=mysql_query($query);
if (!$sql1) {
die('Invalid query: ' . mysql_error());
}
?>
this is my php code in server where there is a table named 'questions' and i am trying to insert the data into it from the input got from the GET method using form at front end, i can figure out that data is coming properly from the client which i have checked using echo. I am getting an error as
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 'name, type your question here, company)' at line 1
Don't know what is the error in the query. anyone find it out asap. thank you
You need to quote your values
('$topic', '$question', '$company')
since those are strings.
Plus, you should escape your data for a few reasons. Not let MySQL complain about certain characters such as hyphens etc., and to protect against SQL injection.
Use prepared statements:
https://en.wikipedia.org/wiki/Prepared_statement
Reference(s):
https://en.wikipedia.org/wiki/SQL_injection
How can I prevent SQL injection in PHP?
http://php.net/manual/en/function.mysql-real-escape-string.php
Edit:
As an example using your present MySQL API:
$topic = mysql_real_escape_string($_GET['topic']);
$question = mysql_real_escape_string($_GET['question']);
$company = mysql_real_escape_string($_GET['company']);
I don't know what your inputs are called, so that's just an example.
You mentioned about using $_GET for debugging but using a POST method.
Change all $_GET to $_POST above.
Try this
<?php
$db = mysqli_connect('mysql6.000webhost.com', 'a6124751_murali1', 'default#123', 'a6124751_signup');
if (!$db) {
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
$topic = $_GET["Topic"];
$question = $_GET["Question"];
$company = $_GET["Company"];
$query = "INSERT INTO questions (topic, question, company) VALUES ('$topic', '$question', '$company')";
$sql1=mysqli_query($db, $query);
if(!$sql1)
{
die('Invalid query: ' . mysqli_error($db));
}
?>
Fixes in your code
The mysql extension is deprecated and will be removed in the future:
use mysqli or PDO instead
You need to quote your values ('$topic', '$question', '$company')
You have to put the values in single qoutes, if that are char types:
$query = "INSERT INTO questions (topic, question, company) VALUES ('$topic', '$question', '$company')";
But you should not longer use the deprecated mysql_*API. Use mysqli_* or PDO with prepared statements.
Related
My test code is:
<?php
$connessione = mysql_connect("***", "***", "***");
mysql_select_db("***", $connessione);
$risultato = mysql_query("SELECT * FROM servem_vote", $connessione);
if(mysql_query("INSERT INTO servem_vote (uid,lastvote) VALUES ($uid,now()) ON DUPLICATE KEY UPDATE lastvote=now();
")) {
header('location:/home.php'); }
else {
echo "Error: " . mysql_error(); }
mysql_close($con);
?>
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 'now()) ON DUPLICATE KEY UPDATE lastvote=now()' at line 1
DB:
http://prntscr.com/ef7544
Where am I doing wrong?
You are missing $uid in the code you shared. You don't set that value anywhere but you attempt to use it as part of your INSERT query.
If it's coming from form data, grab it from $_REQUEST superglobal variable before attempting to use it:
$uid = $_REQUEST['uid']
If it's NOT an integer in the MySQL table, you need to wrap it in single quotes as part of your statement.
INSERT INTO servem_vote (uid,lastvote) VALUES ('$uid',now())
ON DUPLICATE KEY UPDATE lastvote=now();
I don't know what purpose this line serves:
$risultato = mysql_query("SELECT * FROM servem_vote", $connessione);
You don't seem to do anything with the result set from this query.
MOST IMPORTANTLY: As many others have commented you need to be sanitizing your data and you should be relying on PDO or mysqli* functions to safely interact with your database. See answers here
Have some problem I couldn't find solution for, though searched through many sources (and questions here too). So, here it is.
With the PHP-code below I suppose to collect data from a HTML-form and send it to a local WAMP-server. But, though final check shows me "Success!", no new rows in the database's table are found, it stays empty. Names are correct, commands are (as I see it) too, so I just don't know what's wrong.
I hope you guys could help me. ^^
//Check if user submited a form
if (isset($_POST['submit'])) {
//Check if from is properly filled
if (empty($_POST['itemName']) || empty($_POST['itemPic']) || empty($_POST['itemPrice']) || empty($_POST['itemProvider'])) {
echo '<script>alert ("Fill out the form please!")</script>';
} else {
$conn = new mysqli('localhost:3306', 'root', '', 'goods-review');
//Check if connection established
if (mysqli_connect_errno()) {
exit('Connect failed: ' . mysqli_connect_error());
}
//Sending data
$newItem = array('itemName' => $_POST['itemName'], 'itemPic' => $_POST['itemPic'], 'itemPrice' => $_POST['itemPrice'], 'itemProvider' => $_POST['itemProvider']);
$sql = "INSERT INTO goods (itemName, itemPic, itemPrice, itemDate, itemProvider) VALUES ('" . $newItem['itemName'] . "', '" . $newItem['itemPic'] . "', '" . $newItem['itemPrice'] . "', date('Y:m:d, H:i:s'), '" . $newItem['itemProvider'] . "')";
//Check if sent
if ($sql) {
echo '<script>alert ("Success!")</script>';
} else {
echo '<script>alert ("Error!")</script>';
}
$conn->close();
}
}
The code is just assigning a string value to a variable.
$sql = "INSERT ...";
And the string value is not submitted to the database; it's not being executed as a SQL statement. There's nothing magical about the name of the variable. As far as PHP is concerned, the code is just assigning a value to a variable. That's it.
If you want to execute a SQL statement, you need to add code that actually does that. It shouldn't be difficult to find an example of how to do that.
IMPORTANT NOTE: The code in the question appears to create a SQL statement that is vulnerable to SQL Injection. A much better pattern is to use prepared statements with bind placeholders.
Reference: mysqli_prepare
If there's some (unfathomable) reason that you can't use prepared statements, then at a minimum, any potentially unsafe values that are included in the SQL text must be properly escaped.
Reference: mysqli_escape_string
If you have setup the $newItem array first.
Normaly you will validate the user-input and ensure that the user-input has no SQL injections in it.
Read here about it: What is SQL injection?
After that
(You have to add $newItem['itemDate']=date('Y:m:d, H:i:s');)
$sql = "INSERT INTO goods (".implode(', ',array_keys($newItem)).")"
." VALUES ('".implode("', '",$newItem)."')";
if (mysqli_query($conn,$sql)){
echo '<script>alert ("Success!")</script>';
} else {
echo '<script>alert ("Error!")</script>';
}
If you are using this:
you dont have too keep an eye on the right field order
every field value becomes ' around them
you have less code to write
field count and order can change
Finally mysqli_query() returns FALSE if nothing is insert and you can check for that.
Sidenote: Try to use OOP Version of the MYSQLi Extention and Prepared Statments. Read about it here: mysqli, OOP vs Procedural
I'm trying to make my first registration script using PHP/SQL. Part of my code isn't working:
if(!$errors){
$query = "INSERT INTO users (email, password) VALUES ($registerEmail, $registerPassword)";
if(mysqli_query($dbSelected, $query)){
$success['register'] = 'Successfully registered.';
}else{
$errors['register'] = 'Registration did not succeed.';
}
}
When I test my code I get the error 'Registration did not succeed.' For reference, $errors and $success are arrays. Is there anything wrong with this part of my script?
$dbSelected is:
$dbLink = mysqli_connect('localhost', 'root', 'PASSWORD');
if (!$dbLink) {
die('Can\'t connect to the database: ' . \mysqli_error());
}
$dbSelected = mysqli_select_db($dbLink, 'devDatabase');
if (!$dbSelected) {
die('Connected database, but cannot select
devDatabase: ' . \mysqli_error());
}
I'm sure I am connecting and selecting the database.
Any help would be greatly appreciated! I am very new to PHP/SQL so forgive me for any noob mistakes.
Quote the string like below
$query = "INSERT INTO users (email, password) VALUES ('$registerEmail', '$registerPassword')";
You can also do
echo $query;
and take the output on the browser, copy and paste into PHPMyAdmin and execute it from there. It should tell you what is wrong with the query.
I suggest you to use prepared statement as using string concatenation in SQL Statement is prone to SQL injection attack. Refer the example PHP mysqli prepare
First off, PHP is deprecating mysql_ functions, you should migrate to PDO instead.
Also, make sure since you're using the older mysql_ functions to sanitize your entries using mysql_real_escape_string
Also, your entries need to be quoted. Here's a redo of your query string:
$query = "INSERT INTO users (email, password) VALUES ('{$registerEmail}', '{$registerPassword}')";
I post the data of dynamically generated textbox in PHP. When I post the data using real_escape_string(), i.e:
$ingredient = mysql_real_escape_string($_POST['ingredient']);
...it doesn't post data from textbox and I use simple $_POST['']; method i.e:
$ingredient = $_POST['ingredient'];
...it gives me error when I use a single quote (') in my text.
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 's', 'fgad', '55')' at line 2
this was my old post i solved the problem locally by enabling magic_quotes_gpc = On but when upload this on my server it does't work again so how can i turn on magic quotes on server.
Do you have an open database connection? mysql_real_escape_string needs a MySQL server to talk to in order to function.
You might want to try
$ingredient = $_POST['ingredient'];
$ingredient = mysql_real_escape_string($ingredient);
<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// escape variables for security
$firstname = mysqli_real_escape_string($con, $_POST['firstname']);
$lastname = mysqli_real_escape_string($con, $_POST['lastname']);
$age = mysqli_real_escape_string($con, $_POST['age']);
$sql="INSERT INTO Persons (FirstName, LastName, Age)
VALUES ('$firstname', '$lastname', '$age')";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
?>
you must used connection db see
http://php.net/manual/en/mysqli.real-escape-string.php
you can use also
string mysqli::real_escape_string ( string $escapestr )
I think this might be related to the "magic" quotes feature -- see this page for details: Magic Strings & SQL
Basically, because of problems with SQL injection attacks, they pre-escaped strings with quotes after a certain version of PHP (I think it was 5.0, but I could be wrong). So the end result is that now your software has to check for the software version and behave differently depending on whether the string is already escaped or not.
I am having trouble making this seemingly simple MySql query work. Can anyone spot the problem?
<?php
include "config.php";
$offerid = $_POST["offerid"];
$ip = $_SERVER["REMOTE_ADDR"];
mysql_query("INSERT INTO voted (offerid,ip) VALUES (".$offerid.",".$ip.")");
?>
You probably want some single quotes:
"INSERT INTO voted (offerid,ip) VALUES ('" . $offerid . "','" . $ip . "')"
You should also use intval and mysql_real_escape_string to avoid SQL injection vulnerabilities:
$sql = "INSERT INTO voted (offerid,ip) VALUES (" .
intval($offerid). ", '" .
mysql_real_escape_string($ip) . "')";
Another alternative which may be easier to read is to use sprintf:
$sql = sprintf("INSERT INTO voted (offerid, ip) VALUES (%d, '%s')",
$offerid, mysql_real_escape_string($ip));
To place a string value into query, you must perform 2 actions on it:
enclose it in quotes
and escape special characters.
So, query must be like this:
INSERT INTO voted (text) VALUES ('I\'m a programmer')
Armed with this knowledge, you can easily write a code to make valid query:
$offerid = mysql_real_escape_string($_POST["offerid"]);
$ip = mysql_real_escape_string($_SERVER["REMOTE_ADDR"]);
$sql = "INSERT INTO voted (offerid,ip) VALUES ('$offerid','$ip')"
mysql_query($sql) or trigger_error(mysql_error().$sql);
Note the trigger_error part.
It will provide you with comprehensive information on any error
my guess would be with quotes
mysql_query("INSERT INTO voted (offerid,ip) VALUES (\"".$offerid."\",\"".$ip."\")");
<?php
include "config.php";
$offerid = $_POST["offerid"];
$ip = $_SERVER["REMOTE_ADDR"];
mysql_query("INSERT INTO voted (offerid,ip) VALUES ('".mysql_real_escape_string ($offerid)."','".mysql_real_escape_string ($ip)."')");
?>
This adds the single quote marks around the strings you are inserting - as well as mysql_real_escape_string php function that will escape (add a backslash infront of) any security risk characters.
In addition to using intval(...) and mysql_real_escape_string(...) you could use parameterized statements (or placeholders) using PEAR::DB or PEAR::MDB2:
$dsn = "mysqli://testuser:testpass#localhost/test";
$conn =& DB::connect ($dsn); // using PEAR::DB, though it's been superseded
if (DB::isError ($conn)) {
die ("Cannot connect: " . $conn->getMessage () . "\n");
}
$result =& $conn->query ("INSERT INTO voted (offerid,ip) VALUES (?,?)", array($_POST["offerid"], $_SERVER["REMOTE_ADDR"]));
if (DB::isError ($result)) {
die ("INSERT failed: " . $result->getMessage () . "\n");
}
Using placeholders and parameters is pretty common on platforms other than PHP, so it's not a bad idea to understand the basic premise behind them.
If you're interested in using DB modules like these, I'd recommend checking out Writing Scripts with PHP's PEAR DB Module by Paul DuBois. Again, the module it describes is superseded, but I find it's nonetheless interesting and informative.