MySQLi cannot create new table in PHP - php

I'm getting frustrated with running basic SQL statements in PHP. I keep running into syntax errors that ask me to refer to the current server version of MySQL.
I'm trying to run the follow SQL query:
CREATE DATABASE mc_todo_app;
use mc_todo_app;
CREATE TABLE todos (
id INT PRIMARY KEY AUTO_INCREMENT,
task VARCHAR(255) NOT NULL,
completed BOOLEAN DEFAULT FALSE,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
In PHP I then try to run this script.
require "config.php";
// Create connection
$conn = mysqli_connect($host, $username, $password);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = file_get_contents('data/init.sql');
$result = mysqli_query($conn, $sql);
if (false === $result) {
printf("Error: %s\n", mysqli_error($conn));
} else {
echo "DB and Table successfully created!";
}
mysqli_close($conn);
This produces the following error message:
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 'use mc_todo_app;
CREATE TABLE todos (
id INT PRIMARY KEY AUTO_INCREMENT,
tas' at line 3
Here are the details of my Database server:
I'm even trying basic Table creation statements from W3Schools without success.
What am I doing wrong?

mysqli_query() can only execute one query at a time, while you are attempting to execute multiple queries. You can use mysqli_multi_query() instead.
$sql = file_get_contents('data/init.sql');
$result = mysqli_multi_query($conn, $sql);
http://php.net/mysqli.multi-query

Related

Inconsistency of MySQL syntax errors depending on whether query made from command line or mysqli_connect

A simple MySQL query is returning a syntax error over mysqli_connect, but the identical, copy-pasted query is successful in both the CLI and phpMyAdmin.
Consider this example for MySQL 8.0:
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "USE aTable; INSERT INTO aTable (`aColumn`) VALUES ('aValue');";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
When the PHP runs it prints an error:
USE aTable; INSERT INTO aTable (aColumn) VALUES ('aValue');
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 'INSERT INTO aTable (aColumn) VALUES ('aValue')' at line 1
However when the same query is pasted into phpMyAdmin it tells me:
1 row inserted.
Inserted row id: 6 (Query took 0.0063 seconds.)
USE aTable; INSERT INTO aTable (aColumn) VALUES ('aValue');
Why are they different?
Remove the USE from the PHP code because the database is already selected in the mysqli_connect method.
$sql = "USE aTable; INSERT INTO aTable (`aColumn`) VALUES ('aValue');";
Should be:
$sql = "INSERT INTO aTable (`aColumn`) VALUES ('aValue');";
Also, make sure that you're not using the database name in the INSERT query.

I can't find what *exactly* the syntax error is in mysql [duplicate]

This question already has answers here:
Why can't I run two mysqli queries? The second one fails [duplicate]
(2 answers)
Closed 4 years ago.
I am creating a simple database and it's table for learning purpose:
This is my php code(script.php)
<?php
$sql = file_get_contents("init.sql");
$servername = "localhost";
$username = "root";
$password = "";
// connect to database
$conn = new mysqli($servername, $username, $password);
if ($conn->connect_error) {
die("Connection error: " . $conn->connect_error);
}
if($conn->query($sql) == True){
echo "Database and Table has been created succesfully!";
}
else {
echo "\nError creating database and table: . $conn->error";
}
?>
And this is mysql file(init.mysql)
CREATE DATABASE test;
USE test;
CREATE TABLE Users (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
date_of_registration TIMESTAMP)
The exact error I am seeing is:-
Error creating database and table: . 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 'USE test; CREATE TABLE Users ( id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY ' at line 2
In my opinion, the code is syntactically correct but as you see I am getting an error
So I am struggling to find where is the error but no luck :(
Or I am blind enough to see it.
To process multiple queries in one call (you have three in your file), you need to use multi_query. Change
if($conn->query($sql) == True){
to
if($conn->multi_query($sql) == True){

SQLState 42000 syntax error. Possible table issue?

I'm stuck with a syntax error for a SQL query to insert data into a table.
Ah, the syntax error, most useless of all errors!!
Using the code modified from PHP Insert Data Into MySQL using both mysqli and PDO methods.
e.g.:
<?php
$servername = "localhost";
$username = "4w_write";
$password = "GjByhJzrQueHgTzw";
$dbname = "4w_test";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO 4w (email) VALUES ($email)";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Having stripped it down to a single variable which isn't using a keyword, I'm pretty sure the problem is with my table.
SQL Query:
INSERT INTO 4w (email) VALUES (myemail#gmail.com)
Error:
Error: INSERT INTO 4w (email) VALUES (myemail#gmail.com) 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 '#gmail.com)'
at line 1
SQL table (4w):
# Name Type Default
1 id [Primary,Index] int(11)
2 email varchar(255)
3 whatIs tinytext
4 whereIs text
5 whattodo text
6 imageURL text
7 whenRep timestamp CURRENT_TIMESTAMP
The email value is a string, so you need to surround it with quotes:
$sql = "INSERT INTO 4w (email) VALUES ('$email')";
Or, better yet, use a prepared statement and bind it's value.
Couldn't see the problem, missing quotes....
Original code:
$sql = "INSERT INTO 4w (email) VALUES ($email)";
Fixed code:
$sql = "INSERT INTO 4w (email) VALUES ('$email')";

Syntax error when running multiple queries through mysqli

I‘m trying to move rows from one table to another, when they‘re older than 6 hours. While my code works perfectly in PMA, I just get an error via PHP.
This is my PHP code:
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$timestamp6h = time() - 21600;
$sql="BEGIN;
INSERT INTO archiv6h SELECT * FROM links WHERE tweettimestamp < $timestamp6h
ON DUPLICATE KEY UPDATE archiv6h.tweetscount= archiv6h.tweetscount+ links.tweetscount, archiv6h.followerscount= archiv6h.followerscount + links.followerscount, archiv6h.tweettimestamp= archiv6h.tweettimestamp + links.tweettimestamp;
DELETE FROM links WHERE tweettimestamp < $timestamp6h;
COMMIT;";
if (!mysqli_query($conn, $sql)) {
printf("Errormessage: %s\n", mysqli_error($conn));
}
$result = mysqli_query($conn, $sql);
$conn->close();
I then get the following error message:
Errormessage:
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 'INSERT INTO archiv6h SELECT * FROM links WHERE tweettimestamp < 1521038638 ON ' at line 1
When I use this as a query in PMA, it works like intended:
BEGIN;
INSERT INTO archiv6h SELECT * FROM `links` WHERE tweettimestamp < 1521038638
ON DUPLICATE KEY UPDATE archiv6h.tweetscount= archiv6h.tweetscount+ links.tweetscount, archiv6h.followerscount= archiv6h.followerscount + links.followerscount, archiv6h.tweettimestamp= archiv6h.tweettimestamp + links.tweettimestamp;
DELETE FROM `links` WHERE tweettimestamp < 1521038638;
COMMIT;
Has someone an idea how to get the query running in PHP?
With BEGIN; and COMMIT; that are four statements. You can't run multiple statements in one mysqli_query() call. If you need a transaction, use mysqli::begin_transaction(). And only use one statement per mysqli_query() call:
$conn->begin_transaction();
$conn->query("INSERT ...");
$conn->query("DELETE ...");
$conn->commit();
Note that you should also configure mysqli to throw exceptions. I would write your script the following way:
// set connection variables
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = mysqli_connect($servername, $username, $password, $dbname);
$timestamp6h = time() - 21600;
$conn->begin_transaction();
$conn->query("
INSERT INTO archiv6h SELECT * FROM links WHERE tweettimestamp < $timestamp6h
ON DUPLICATE KEY UPDATE
archiv6h.tweetscount = archiv6h.tweetscount + links.tweetscount,
archiv6h.followerscount = archiv6h.followerscount + links.followerscount,
archiv6h.tweettimestamp = archiv6h.tweettimestamp + links.tweettimestamp
");
$conn->query("DELETE FROM links WHERE tweettimestamp < $timestamp6h");
$conn->commit();
If anything fails, $conn->commit(); will never be executed, and the script will output an error message. Threre is not even a need to close the conection, since it will be closed when the script ends.

How can I get mysql to print rows from a database table

I am trying to learn php from W3schools which includes a mysql section.So far I have completed every other part of the tutorial on w3school except the part that prints content from a database table. For some very weird reason , nothing displays when I run my code. Please how can I get this working and could my problem come from the fact that I am using MariaDB with Xampp instead of Mysql although they said it was practically the same syntax.
Here is the code
<?php
$servername = "localhost";
$username = "uhexos";
$password = "strongpassword";
$database = "fruitdb";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Create database
$sql = "CREATE DATABASE fruitDB";
if ($conn->query($sql) === TRUE) {
echo "Database created successfully";
} else {
echo "Error creating database: " . $conn->error;
}
$conn->close();
// Create connection
$conn = mysqli_connect($servername, $username, $password,$database);
// sql to create table
$complexquery = "CREATE TABLE MyFruits (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
FruitType VARCHAR(30) NOT NULL,
FruitTaste VARCHAR(30) NOT NULL,
FruitQuantity INT NOT NULL,
DatePurchased TIMESTAMP
)";
if ($conn->query($complexquery) === TRUE) {
echo "Table Fruits created successfully<br> ";
} else {
echo "Error creating table: " . $conn->error;
}
$entry = "INSERT INTO myfruits (fruittype,fruittaste,fruitquantity) VALUES ('orange','sweet','50'),('lemon','sour','10'),('banana','sweet','15')";
if ($conn->query($entry) === TRUE) {
echo "New records created successfully";
} else {
echo "Error: " . $conn->error;
}
$sql = 'SELECT id, fruitname, fruittaste FROM myfruits';
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC)) {
echo "EMP ID :{$row['id']} <br> ".
"EMP NAME : {$row['fruitname']} <br> ".
"EMP SALARY : {$row['fruittaste']} <br> ".
"--------------------------------<br>";
}
echo "Fetched data successfully\n";
mysql_close($conn);
?>
this is the output I get from all my echos.
Error creating database: Can't create database 'fruitdb'; database existsError creating table: Table 'myfruits' already existsNew records created successfully
or
Database created successfullyTable Fruits created successfully
New records created successfully
Based on the error message, you managed to create the database and tables once and now each time you run the code it fails because you can't reuse the names.
You definitely don't want to have code trying to erase & start fresh on your database every time. In fact, most often I find that you don't even create the database inside your regular code but use phpMyAdmin or some other admin page to do that. But creating tables inside code is normal enough. Two options:
1 - Create the table only if it does not already exist. This is extremely safe. However, if you want to start a table over again with a new structure, or start with it always empty, that won't work. To do that, just change CREATE TABLE to CREATE TABLE IF NOT EXISTS
2 - Delete the table before creating it. Before each CREATE TABLE command, add a command like DELETE TABLE IF EXISTS MyFruits
Remember database name is Case-insensitive, so it doesn't matter whether you create a DB name "fruitdb" or "fruitDb" both are same.That is the reason you are getting error. Also you don't have to create a new database when you execute any file. If you have already created the database than you only have make the connection with it.
Let's debug your code line by line.
Line 8 -
// Create connection
$conn = new mysqli($servername, $username, $password);
Here you are creating the connection with your database because you have already created that database. If you check your phpmyadmin, you'll find a database named "fruitdb"
Line 10 -
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
Here your checking whether the you are able to connect with your database. If not it will throw the error and your script will stop. Right now your code successfully runs till this point.
Line 15 -
// Create database
$sql = "CREATE DATABASE fruitDB";
Here you are again creating a database with same name and your code stops working as you already have it.
The error was from this line
$sql = 'SELECT id, fruitname, fruittaste FROM myfruits';
I accidentally put fruitname instead of fruittype and that is what caused it to fail. So for anyone else with thi problem my advice is to check your variable names if you are 100% sure of your syntax. Thanks for all the help.

Categories