so i have this php code :
session_start();
$servername = "localhost";
$username = "root";
$dbname = "3890ask3_db";
$con = mysql_connect($servername, $username, "", $dbname)
or die("Failed to connect to MySQL: " . mysql_error());
$db=mysql_select_db($dbname,$con)
or die("Failed to connect to MySQL: " . mysql_error());
$query = mysql_query("SELECT * FROM register where Username = '$_SESSION[Username]'") or die(mysql_error());
$row = mysql_fetch_array($query) or die(mysql_error());
if(isset($_GET['selecttoy']))
{
$clname=$row['Name'];
$clsurname=$row['Surname'];
$clemail=$row['Email'];
$stoy=$_GET['selecttoy'];
$query2 = "INSERT INTO order (ClName, ClSurname, ClEmail, ToyCode , OrderID) VALUES ('$clname', '$clsurname', '$clemail' , '$stoy', ' ' )" ;
if (mysql_query($query2)) {
echo "Order created successfully!";
} else {
echo "Error: " . "<br>" . mysql_error($con);
}
}
?>
The php page can actually read the get variable,but as soon as i try to insert something in the database, i get this error message:
"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 'order (ClName, ClSurname, ClEmail, ToyCode , OrderID) VALUES ('mar', 'kyr', 'dgg' at line 1"
i tried everything but no result...can someone please help me?
thanks in advance....
You can not use order directly because it's reserved word. try to enclose it in (``). Like below:-
$query2 = "INSERT INTO `order` (ClName, ClSurname, ClEmail, ToyCode , OrderID) VALUES ('$clname', '$clsurname', '$clemail' , '$stoy', ' ' )" ;
Note:- Try to add sql error reporting code always.
stop using mysql_*, use mysqli_* or PDO.
your above code is open for SQL Injection. thanks.
Related
I am fairly new to SQL and I am trying to write code to insert information from a messages form. Here is the SQL code:
$con = mysqli_connect($hostname,$username,$password,$db);
// Check connection
if (mysqli_connect_error()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$name = mysqli_real_escape_string($con, $_POST['name']);
$email = mysqli_real_escape_string($con, $_POST['email']);
$message = mysqli_real_escape_string($con, $_POST['message']);
$sql = "INSERT INTO messages (name, email, message) VALUES ( '$name' , '$email' , '$message' )";
if (!mysqli_query($sql)) {
die ('Error: ' . mysqli_error());
}
else {
echo "<html><script language='JavaScript'> alert('Thank you for your submission.'),window.location = 'home'</script></html>";
}
This code returns "Error: " that I interpreted as it thinking there is an error, but there isn't any errors. The connection variables in mysqli_connect are all correct, but I am unsure if I am using the mysqli_real_escape_string correctly and even the $sql statement, because this code also doesn't insert anything into my database. Thanks in advance.
As per the mysqli_query() documentation, if you are using the procedural notation you need to include your mysqli link:
mixed mysqli_query ( mysqli $link , string $query [, int $resultmode = MYSQLI_STORE_RESULT ] )
This would suggest you need to pass in $con to mysqli_query() as you have with your other function calls as below:
mysqli_query($con, $sql)
Also, please look up and read about parametrization as your code as it is should not be used on a live site as you are vulnerable to SQL injection. Please take the time to read this and learn how to prevent it.
Try running the query this way
mysqli_query($con, $sql);
mysqli_query requires the link to your db connection which is "$con"
This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 6 years ago.
I'm new on StackOverflow. Hope I'm doing the questioning correctly.
I'm trying to insert data from an external XML (URL) into an SQL table, but I get:
Error: INSERT INTO 'table_name' ('price')VALUE ('5.95')
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 ''BBB' ('price')VALUE ('5.95')' at line 1
I'm able to ECHO and PRINT values from the XML and also able to INSERT non-xml values into the table. The code I'm using is:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "dbname";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$xml=simplexml_load_file("external_xml_url") or die("Error: Cannot create object");
foreach ($xml->product as $row) {
$price = $row -> price;
$sql = "INSERT INTO 'table_name' ('price')"
. "VALUES ('$price')";
}
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Would be great if someone can help me out on this one. I've the feeling I'm pretty close...
As far as I know, with MariaDB you have to use Backticks to "qoute" an object's name.
Try it like this:
$sql = "INSERT INTO `table_name` (`price`) VALUES ('$price')";
If you do not deal with dangerous object names you might use just
$sql = "INSERT INTO table_name (price) VALUES ('$price')";
If you got your price properly then you should check your query
Ex.
INSERT INTO table_name (price) VALUES ('$price')
I am trying to read and write to a database. Here is the code I have so far:
$mysql = mysqli_connect("example.com", "johndoe", "abc123"); // replace with actual credidentials
$sql = "CREATE DATABASE IF NOT EXISTS dbname";
if (!mysqli_query($mysql, $sql)) {
echo "Error creating database: " . mysqli_error($mysql);
}
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_close($mysql);
$mysql = mysqli_connect("example.com", "johndoe", "abc123", "dbname"); // replace with actual credidentials
$sql = "CREATE TABLE IF NOT EXISTS Users(ID INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(ID), username CHAR(15), password CHAR(15), email CHAR(50))";
if (!mysqli_query($mysql, $sql)) {
echo "Error creating table: " . mysqli_error($mysql);
}
$sql = "INSERT INTO Customers(username, password, email) VALUES(" . $username . ", " . $password . ", " . $email . ")";
if (!mysqli_query($mysql, $sql)) {
echo "Error: " . mysqli_error($mysql);
}
mysqli_close($mysql);
However, when I try to run it, it has an error:
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 1
Could anybody tell me how to fix this?
Please check syntax of mysqli, it takes 4 parameters.You also have to provide database name.
$link = mysqli_connect("myhost","myuser","mypassw","my_db");
You're missing database in mysqli_connect() call
$link = mysqli_connect("hostname","username","password","database") or die("Error " . mysqli_error($link));
Obviously the answer is in your error. You didn't select any database. When using this function mysqli_connect specify the database you want to connect to.
Here is the syntax of the function: http://www.w3schools.com/Php/func_mysqli_connect.asp .
1) Create your database outside of your application
2) Specify mysqli_connect with the database you want to select.
You can also use another function called mysqli_select_db . You can find the sytanx here : http://www.w3schools.com/php/func_mysqli_select_db.asp .
As already stated in the comment, you will also have to replace : "example.com" with your ip address, if you are running locally replace it with 127.0.0.1:3306 , if you didn't change the port when you installed your mysql database / "johndoe" with your database account, you can change that to "root" / "abc123" with your root account password DEFAULT : "" .
Good luck !
First check mysqli_select_db if it returns false then create database.
try like this:
$mysql = mysqli_connect("example.com", "johndoe", "abc123") or die(mysqli_connect_error()); // replace with actual credidentials
if (!mysqli_select_db($mysql,'hardestgame_accounts')) {
$sql = "CREATE DATABASE IF NOT EXISTS hardestgame_accounts";
if (!mysqli_query($mysql, $sql)) {
echo "Error creating database: " . mysqli_error($mysql);
}
}
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "CREATE TABLE IF NOT EXISTS Users(ID INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(ID), username CHAR(15), password CHAR(15), email CHAR(50))";
if (!mysqli_query($mysql, $sql)) {
echo "Error creating table: " . mysqli_error($mysql);
}
mysqli_close($mysql);
here is a good answer: Php mysql create database if not exists
Try using mysql_select_db in between the database connection and the table creation.
Also, mysql_ is deprecated, please use mysqli_ instead
Use ` backticks for MYSQL reserved words...
your table name is reserved word for MYSQL...
Change your table name.
I am trying to test if this query runs or not.But i am output with blank screen i.e no output. I am using xampp server.
<?php
$mysql_host='localhost';
$mysql_user='root';
$mysql_pass='';
$mysql_db='a_database';
$con_error='connection error';
$query="SELECT `name` FROM `users` WHERE `id`='1' "; //selecting name from databas where id is 1
$query_run=mysql_query($query); //this is my query
if($query_run)
{
echo 'success';
}
?>
Please help me with this. $query_run neither returns false here nor true. I am not able to understand where the problem is.
First of all try to avoid mysql_* functions from php > 5.4, use mysqli_* function like this.
connect to Databse before running a query like this
$con=mysqli_connect("localhost","my_user","my_password","my_db");
$query="SELECT `name` FROM `users` WHERE `id`='1' "; //selecting name from databas where id is 1
$query_run=mysqli_query($con,$query);
For php < 5.5 use this
$con=mysql_connect("localhost","my_user","my_password","my_db");
$query="SELECT `name` FROM `users` WHERE `id`='1' "; //selecting name from databas where id is 1
$query_run=mysql_query($con,$query);
First of all stop using mysql it is deprecated. Use mysqli now.
In your script you missed the connection to database. Add before your query:
$link = mysqli_connect($mysql_host,mysql_user,$mysql_pass,$mysql_db) or die("Error " . mysqli_error($link));
For more details see this link.
try this:::
<?php
$link = mysqli_connect("localhost","root","root","a_database") or die("Error " . mysqli_error($link));
$query = "SELECT name FROM users" or die("Error in the consult.." . mysqli_error($link));
$result = $link->query($query);
while($row = mysqli_fecth_array($result)) {
echo $row["name"] . "<br>";
}
?>
as mentioned there, use mysqli_*
I'm getting this error:
Invalid query: 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 'INET_ATON('188.92.x.x')' at line 1
While trying to insert IP Address in database. The column type is:
'LastIP int(10) unsigned NOT NULL,'.
The function to execute the query is:
function onNewUser($ip, $hostname, $con)
{
$query = "INSERT INTO tableMachine (LastIP, LastHostName) VALUES ".
"INET_ATON('".mysql_real_escape_string($ip, $con)."'), ".
"'".mysql_real_escape_string($hostname, $con)."'";
$result= mysql_query($query, $con);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
}
I call this function with the parameters:
$ip = $_SERVER['REMOTE_ADDR'];
$hostname = #gethostbyaddr($ip);
onNewUser($ip, $hostname, $con);
What's wrong with it guys?
your values list should be encapsulated inside of parenthesis if I am not mistaken
You should try this :
$query = "INSERT INTO tableMachine (LastIP, LastHostName) VALUES (".
"INET_ATON('".mysql_real_escape_string($ip, $con)."'), ".
"'".mysql_real_escape_string($hostname, $con)."')";
I just add parenthesis for VALUES(...)
Also, as #Shamil said, the functions mysql_* are depricated. You should use mysqli_*This link should help you with the mysqli_* functions.