I have an SQL syntax error when inputing data - mysql

I'm a beginner programmer and I'm getting a problem that I cannot seem to overcome. I predict it's a small syntax error but I don't know.
The code I'm using is the following:
<?php
$x=$_POST['firstname'];
$y=$_POST['lastname'];
$servername = "localhost";
$username = "root";
$password = "";
$dbname="db1";
//Create connection
$conn = new mysqli($servername, $username, $password,$dbname);
//Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
$sql = "INSERT INTO 'user' ('fname', 'lname') VALUES ('$x','$y')";
if ($conn->query($sql) === TRUE) {
echo "New record created succesfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
?>
Once I press submit to input the data the following error comes up:
Connected successfullyError: INSERT INTO 'user' ('fname', 'lname') VALUES ('rty','rty')
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 ''user' ('fname', 'lname') VALUES ('rty','rty')' at line 1
Any help? Thanks in advance.

update your query replace single quote(') from table name and column name with (`), Like
$sql = "INSERT INTO `user` (`fname`, `lname`) VALUES ('$x','$y')";

Related

mysql select - CONCAT no longer working with MariaDB upgrade

This code is part of a database search autocomplete function. It was coded a while ago but the database has since been upgraded from mysql to MariaDB.
This is the part of the code giving an error.
$sql = 'SELECT tree_id, tree_common_name, tree_botanical_name FROM all_trees';
for($i = 0; $i < $p; $i++) {
$sql .= 'WHERE CONCAT(tree_common_name,tree_botanical_name) LIKE ? ';
}
$stmt = $conn->prepare($sql);
if($stmt === false) {
$user_error = 'Wrong SQL: ' . $sql . '<br>' . 'Error: ' . $conn->errno . ' ' . $conn->error;
trigger_error($user_error, E_USER_ERROR);
}'
The error message
PHP Fatal error: Wrong SQL: SELECT tree_id, tree_common_name, tree_botanical_name FROM all_treesWHERE CONCAT(tree_common_name,tree_botanical_name) LIKE ? <br>Error: 1064 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 '(tree_common_name,tree_botanical_name) LIKE ?' at line 1 in /home/wiwi1740/public_html/includes/autocomplete.php on line 73
I've looked at using
$sql .= 'WHERE CONCAT_WS(' ',tree_common_name,tree_botanical_name) LIKE ? ';
but still throws an error.
Any tips would be appreciated. This code originally came from someone else that I adapted for my client.

Check if email already exists in database and add/change data

I've got a form which has 14 numeric inputs and 2 text inputs - name and email. Someone is adding data and it's saved to the database - I've done it. But when someone is adding data for the second time using the same email address, database should override the data in specific row with that email.
I read about UPDATE in sql but I don't know how to make a query which will check if that email exists and after that add or update data.
<?php
$servername = "localhost";
$username = "username";
$password = "pass";
$dbname = "test";
$quantity = $_POST['quantity'];
$quantity2 = $_POST['quantity2'];
$quantity3 = $_POST['quantity3'];
$quantity4 = $_POST['quantity4'];
$quantity5 = $_POST['quantity5'];
$quantity6 = $_POST['quantity6'];
$quantity7 = $_POST['quantity7'];
$quantity8 = $_POST['quantity8'];
$quantity9 = $_POST['quantity9'];
$quantity10 = $_POST['quantity10'];
$quantity11 = $_POST['quantity11'];
$quantity12 = $_POST['quantity12'];
$quantity13 = $_POST['quantity13'];
$quantity14 = $_POST['quantity14'];
$name = $_POST['name'];
$email = $_POST['email'];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO Results (1paracwierc, 1paracwierc2, 2paracwierc, 2paracwierc2, 3paracwierc, 3paracwierc2, 4paracwierc, 4paracwierc2, 1parapol, 1parapol2, 2parapol, 2parapol2, final, final2, name, email)
VALUES ($quantity, $quantity2, $quantity3, $quantity4, $quantity5, $quantity6, $quantity7, $quantity8, $quantity9, $quantity10, $quantity11, $quantity12, $quantity13, $quantity14, '$name', '$email')";
if ($conn->query($sql) === TRUE) {
echo "Saved.";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Use insert . . . on duplicate key update. You can do this if you have a unique key on what you want to be unique:
create unique index idx_results_name_email (name, email);
Then, the database will enforce uniqueness. The statement you want is:
INSERT INTO Results (1paracwierc, 1paracwierc2, 2paracwierc, 2paracwierc2, 3paracwierc, 3paracwierc2, 4paracwierc, 4paracwierc2, 1parapol, 1parapol2, 2parapol, 2parapol2, final, final2, name, email)
VALUES ($quantity, $quantity2, $quantity3, $quantity4, $quantity5, $quantity6, $quantity7, $quantity8, $quantity9, $quantity10, $quantity11, $quantity12, $quantity13, $quantity14, '$name', '$email')
ON DUPLICATE KEY UPDATE 1paracwierc = VALUES(1paracwierc),
1paracwierc2 = VALUES(1paracwierc2),
. . .
final2 = VALUES(final2);

Warning: mysql_select_db() expects parameter 2 to be resource,

<?php
$servername = "localhost";
$username = "root";
$password = "Rachel";
$db = "hairdressingapointments";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $db);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected Sussessfully";
mysql_select_db('Hairdressingapointments', $conn) or die(mysql_error());
$sql = "SELECT `ApointmentDate`, `ApointmentTime` FROM `apointments` WHERE `staff_id`=1 && `quantity`>0";
if(!mysql_query($sql)){
die('Error: ' . mysql_error());
}
echo $sql;
mysql_close();
?>
spent hours trying to figure this out and im guessing its something so simple. getting back the following error:
Warning: mysql_select_db() expects parameter 2 to be resource, object given in C:\wamp2\www\hairdressingapointments\TeresaApointments.php on line 15 which is,
mysql_select_db('Hairdressingapointments', $conn) or die(mysql_error());
You already connected to the database using
mysqli_connect(...);
So, you do not need
mysql_select_db(....);
Also change the query to this
$sql = "SELECT ApointmentDate, ApointmentTime FROM apointments WHERE staff_id=1 AND quantity>0";
If you use SQLWorkbench or SQLYog or some other tool, you can enter your SQL and make sure it is valid before adding it to your script.
Also, make sure the table name is really
apointments
and not
appointments
I got this information from php.net - mysqli_connect

mysql_query return error on submit

define('DB_NAME','swiftx');
define('DB_USER','root');
define('DB_PASSWORD','123456');
define('DB_HOST','localhost');
if (isset($_POST['submit'])){
$connection = mysqli_connect(DB_HOST,DB_USER,DB_PASSWORD);
if (!$connection) {
die("Database connection failed: " . mysqli_error());
}else{
echo("Database Connected");
}
// 2. Select a database to use
$db_select = mysqli_select_db($connection, DB_NAME);
if (!$db_select) {
die("Database selection failed: " . mysqli_error());
}
$value = $_POST['name'];
$value2 = $_POST['attendance'];
$sql = "INSERT INTO people (Name,Email) VALUES ('$value','$value2')";
if(!mysqli_query($sql)){
die ("ERROR:". mysqli_error()); //error here <<<<<<<<
}
}
mysqli_close($connection);
why is mysql returing error "mysqli_query() expects at least 2 parameters"
i am following a website tutorial , i double check again and again , i have done noting wrong , can anyone help me fix it ? i have no idea what i doing wrong.
for mysqli_query() we need to pass two parameters
$query
$link_identifier
in your case $query is $sql and $link_identifier is $connection..it mean you need to use mysqli_qeury() in this way
mysqli_query($sql, $connection)
Your error "mysqli_query() expects at least 2 parameters" is pretty self-explanatory. It expects two parameters you are giving just one.
Try this:
if(!mysqli_query( $connection, $sql) ){

Getting 2 Notice: Undefined Variable errors

The two errors are as below:
Notice: Undefined variable: HawA_Homes in C:\wamp\www\HawA_CIS241\InsertRecord.php on line 48
Notice: Undefined variable: HawA_Homes in C:\wamp\www\HawA_CIS241\InsertRecord.php on line 56
I've checked my names and they appear correct and I am not sure how to proceed now.
Code is as below:
<?php
$hostName = "localhost";
$databaseName = "test";
$userName = "root";
$password = "";
$tableName = "HawA_Homes";
//try to connect report error if cannot
$db = new mysqli($hostName, $userName, $password, $databaseName) or die(" Could not connect:" . mysql_error());
print(" Connection successful to host $hostName <br /> <br />"); //report connection success
//Get data to create a new record
$Address = $_REQUEST["address"];
$DateBuilt = $_REQUEST["dateBuilt"];
$Value = $_REQUEST["value"];
$Size = $_REQUEST["size"];
$Number_of_floors = $_REQUEST["floors"];
$sql = "INSERT INTO $HawA_Homes('Address','DateBuilt','Value','Size','Number_of_floors')VALUES{'$Address','$DateBuilt','$Value','$Size','$Number_of_floors')"; //Create insert query for new record
//try to query dataase / store returned results and report error if not successful
if(!$result =$db->query($sql))
{
//die('There was an error running the query[' .$db->error . ']';
}
print("SQL query $sql successful to database: $HawA_Homes <br /><br />"); //report sql query successful.
?>
You have these notices because the variable $HawA_Homes isn't declared in your code before being used at line 48 and 56. (These are just notices, they are not critical errors, you can avoid displaying them by adding error_reporting(E_ALL & ~E_NOTICE); at the begining of your code, like explained here)
In fact, you used $HawA_Homes instead of $tableName in these lines. Replace them, you won't have notices anymore for these lines.