Uncaught PDOException: column does not exist - php

I'm new to PHP and I'm trying to do a query. I made a function getUser thats selects all the users from the user table.
function getUsers() {
global $conn;
$query = $conn->prepare("SELECT * FROM user ORDER BY userid DESC");
$query->execute();
return $query->fetchAll();
}
I heard that it can be case sensitive so I changed all my attributes to lower case to avoid problems but the query can't find any column whatever the name is.
This is my PDO connection which is connecting and not reporting any errors:
session_set_cookie_params(3600, '/~lbaw1641/proto/');
session_start();
$BASE_DIR = '/home/luiscosta/PhpstormProjects/LBAW-FEUP/';
$BASE_URL = 'LBAW-FEUP/';
//Connect to the database
try {
$dbuser = 'luiscosta';
$dbpass = '123';
$host = 'localhost';
$dbname = 'lbaw';
$conn = new PDO("pgsql:host=$host;dbname=$dbname", $dbuser, $dbpass);
}catch (PDOException $e) {
echo "Error : " . $e->getMessage() . "<br/>";
die();
}
$conn->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
Here's my error trace:
#0 /home/luiscosta/PhpstormProjects/LBAW-FEUP/database/users.php(15): PDOStatement->execute()
#1 /home/luiscosta/PhpstormProjects/LBAW-FEUP/controller/pages/top_scored_users.php(6): getUsers()
#2 {main}
thrown in /home/luiscosta/PhpstormProjects/LBAW-FEUP/database/users.php on line 15
And my user table DDL, which as you can see has all of the attributes in lower case:
CREATE TABLE "user"
(
userid INTEGER DEFAULT nextval('user_userid_seq'::regclass) PRIMARY KEY NOT NULL,
username VARCHAR(50) NOT NULL,
email VARCHAR(70) NOT NULL,
password VARCHAR(50) NOT NULL,
fullname VARCHAR(200),
about VARCHAR(500),
website VARCHAR(150),
signup_date DATE DEFAULT ('now'::text)::date NOT NULL,
last_login TIMESTAMP,
locationid INTEGER NOT NULL,
roleid INTEGER NOT NULL,
CONSTRAINT "FK_user_location" FOREIGN KEY (locationid) REFERENCES location (locationid),
CONSTRAINT "FK_user_userRole" FOREIGN KEY (roleid) REFERENCES "userRole" (roleid)
);
Do you guys have any idea what is wrong? Since I'm new, is there a better way to debug and check if my DB connection is up and running?

In PostgreSQL, user is a system information function, equivalent to current_user that returns the "user name of current execution context" (quoted from the documentation.) You can check this question for more details.
That's why you had to quote it when creating the table (CREATE TABLE "user" instead of CREATE TABLE user.)
The userid column from your table obviously doesn't exist in the return of that function. You may be able to get it to work by quoting "user" in your SELECT query, but I think the best solution is to just change the name of the table to something that doesn't already mean something to your database. Maybe users instead?

Related

Cannot create table with PHP

I want to create a table with variables passed into my php file. However, the SQL does not work when I pass in '12345' and works when I pass in 'a12345' instead.
This is my error that is given.
Error creating the table
query was
CREATE TABLE 123456 ( humidity VARCHAR(50) NOT NULL, temperature VARCHAR(50)
NOT NULL, gasquality VARCHAR(50) NOT NULL, timestamp DATETIME NOT NULL
DEFAULT CURRENT_TIMESTAMP)
mysqlerror: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
'123456 ( humidity VARCHAR(50) NOT NULL, temperature VARCHAR(50) NOT NULL,
gasq' at line 1
Creating database failed!
and my function that creates the table
function CreateTableNode(&$formvars)
{
$serialno = $formvars['serialno'];
$qry = "CREATE TABLE ".$serialno." (".
" humidity VARCHAR(50) NOT NULL, ".
" temperature VARCHAR(50) NOT NULL, ".
" gasquality VARCHAR(50) NOT NULL, ".
" timestamp DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP)";
if(!mysqli_query($this->connection,$qry))
{
$this->HandleDBError("Error creating the table \nquery was\n $qry");
return false;
}
return true;
}
I want to be able to create tables with numeric names like '12345' or '154124' for other purposes. Thanks alot!
My suggestion:
Provide a prefix to the table you created.
Moreover, I couldn't
see the primary key in your table. However, it is not necessary to
have it but if your table design doesn't have a primary key, you need
to rethink your design. It plays a vital role to join tables.
Your code can be rewritten as:
function CreateTableNode (&$formvars) {
$host = 'localhost';
$database = 'test';
$dbuser = 'root';
$dbpass = '';
try {
$pdo = new PDO('mysql:host=localhost; dbname=test', $dbuser, $dbpass);
} catch (PDOException $e) {
print "ERROR! : " . $e->getMessage() . "<br/>";
die();
}
$serialno = $formvars['serialno'];
$qry = "CREATE TABLE ".$serialno." ("."
`id` INT NOT NULL AUTO_INCREMENT ,
`humidity` VARCHAR(50) NOT NULL ,
`temperature` VARCHAR(50) NOT NULL ,
`gasquality` VARCHAR(50) NOT NULL ,
`timestamp` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ,
PRIMARY KEY (`id`)
)";
$stmt = $pdo->prepare($qry);
$stmt->execute();
$pdo = null;
return true;
}
You just need to wrap some elements in the query with quotes as the duplicated thread mentioned by underscore_d says:
$qry = "CREATE TABLE '$serialno' (
'humidity' VARCHAR(50) NOT NULL,
'temperature' VARCHAR(50) NOT NULL,
'gasquality' VARCHAR(50) NOT NULL,
'timestamp' DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP)";
This will fix your syntax errror in the query.
Marking to close the question as duplicated
The name of the entity was expected. (near "123456" at position 13)
Try adding a prefix to the table name as such
"t_12345"
CREATE TABLE t_12345
MySql does not allow numeric values as table name.
MySQL doesn't allow the creation of tables with names made solely of digits unless the name is quotes. See here
Identifiers may begin with a digit but unless quoted may not consist solely of digits.
Try quoting the name with backticks (`) or prefix the table name.
The error says "Creating database failed!".
So I assume you haven't selected the database in the connection query. You should do that or select it with "use mydatabase;" first. Of course, you may need to create the database first.
With PDO it would look like:
$conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
Please see dbname=myDB which preselects the right db for you.
Reference: https://www.w3schools.com/php/php_mysql_connect.asp
Using mysql functions, you can use:
mysql_select_db($dbname)
Reference: http://php.net/manual/en/function.mysql-select-db.php

Error performing sql query in PHP

I am trying to learn using mysql in php. I started off trying to create a table in mysql, and using the mysqli extension.
My code:
<?php
$truemsg = "Table created successfully";
$falsemsg = "Error creating table: ";
$servername = "localhost";
$username = "myuser";
$password = "mypass";
$db = "mytable";
// Create database
$sql = "USE ".$db.";".
'CREATE TABLE IF NOT EXISTS Authentication (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
userid VARCHAR(30) NOT NULL,
password VARCHAR(30) NOT NULL,
role VARCHAR(20) NOT NULL,
email VARCHAR(50)
);';
print "Sql command is ".$sql;
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
print "<p></p>";
if ($conn->query($sql) === TRUE) {
echo $truemsg;
} else {
echo $falsemsg . $conn->error;
}
$conn->close();
?>
The error is:
Sql command is USE mytable;CREATE TABLE IF NOT EXISTS Authentication ( id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, userid VARCHAR(30) NOT NULL, password VARCHAR(30) NOT NULL, role VARCHAR(20) NOT NULL, email VARCHAR(50) );
Error creating table: 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 'CREATE TABLE IF NOT EXISTS Authentication ( id INT(6) UNSIGNED AUTO_INCREMENT PR' at line 1
I tried pasting the same command on the mysql command line, and it works fine. What's the problem using this in php?
You are supposed to run queries one by one
$sql = "query one";
$conn->query($sql);
$sql = 'query two';
$conn->query($sql);
instead of coupling them all in one statement.
DO NOT use mysqi_multi_query() either, this asynchronous function is not intended for the everyday use.
Also, in this particular case USE query is superfluous. Database should go into constructor:
$conn = new mysqli($servername, $username, $password, $db);
^^^ here
Also, tell mysqli to throw errors by itself, automatically, instead of checking result of every database command manually:
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
This way you will get neat and clean code:
<?php
$servername = "localhost";
$username = "myuser";
$password = "mypass";
$db = "mytable";
// Create data table
$sql = 'CREATE TABLE IF NOT EXISTS Authentication (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
userid VARCHAR(30) NOT NULL,
password VARCHAR(30) NOT NULL,
role VARCHAR(20) NOT NULL,
email VARCHAR(50)
)';
// Create connection
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = new mysqli($servername, $username, $password, $db);
// Run a query
$conn->query($sql);
echo "Table created successfully";
This code will either report that table has been created successfully, or emit an error, with a detailed explanation on what went wrong.
This seems to be like a mysql multiple query problem
$conn->select_db($db);
you can use this function before the query to use the database and remove the use database statement from your query string , then you query string becomes
$sql = 'CREATE TABLE IF NOT EXISTS Authentication (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
userid VARCHAR(30) NOT NULL,
password VARCHAR(30) NOT NULL,
role VARCHAR(20) NOT NULL,
email VARCHAR(50)
)';
that may work for you ..

Problems automatically creating a mysql database so it can be used on a fresh computer using PHP

I am trying to automatically create the database and table so the website i am creating can be used on a fresh version of XXAMP. At the moment I used PHP myadmin to create the table. however when it loads on a fresh version of XXAMP the database will not be saved on the fresh computer. Therefore im trying to create PHP to automatically create the database and table so content can be added. This is my attempt at the moment but it doesn't seem to be working. Can anyone push me in the right direction?
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "contentdatabase";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// sql to create table
$sql = "CREATE TABLE items
id INT(10) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
itemName text NULL,
itemDescription text NULL,
itemPrice float NULL,
itemStock smallint(6) NULL,
itemImage VARCHAR(100) NULL,
)";
// use exec() because no results are returned
$conn->exec($sql);
echo "Table items created successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
What you want to do is known as database migration, and there are some frameworks available for it, please take a look at this which is a framework focused in DB migrations.
Replace the corresponding part of your code with the below. I have added comments in the relevant places. Remove the comments before running the code
// sql to create table
$sql = "CREATE TABLE items ( //yours lacks this opening parentheses
id INT(10) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
itemName text NULL,
itemDescription text NULL,
itemPrice float NULL,
itemStock smallint(6) NULL,
itemImage VARCHAR(100) NULL //I have removed the last comma (,)
)";
Thank you for your help!
I have got this semi working now thankfully! I can now create a new database and table. However I am now getting this error but i guess its some sort of if statement i need to add.
SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'item' already existsCREATE DATABASE contentdatabase1
SQLSTATE[HY000]: General error: 1007 Can't create database 'contentdatabase1'; database exists

PDO creating a table with a foreign key

I am having difficulty creating a table with MySQL (PDO) with a foreign key element, without the foreign key the table creates fine, but without I get this message:
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax;
I have tried searching for a solution and adapting the code, but seem to keep coming across this. Is there a fix or am I being a wally?
<?php
$servername = "localhost";
$username = "root";
$password = NULL;
$dbname = "testapplciants";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//sql to create the activity registered table
$sql = "CREATE TABLE Activity_Register (
Activity_id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
participant_id INT(6) FOREIGN KEY (participant_id) REFERENCES participants,
entry_number INT(2),
recorded_result INT(6),
entry_date TIMESTAMP
)";
// use exec() because no results are returned
$conn->exec($sql);
echo "Table Activity Recorder created successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
PRIMARY KEY in a column's definition is shorthand for a separate definition that reads PRIMARY KEY (`column_name`)
FOREIGN KEY has no such shorthand.
`participant_id` INT(6),
FOREIGN KEY (`participant_id`) REFERENCES `participants` (`id???`)
Note that you neglected the column name for the referenced table, and you should probably also have ON DELETE and ON UPDATE parameters too.

How to convert sqlite to mysql using PHP

I have converted sqlite database into mysql.
so then i need convert sqlite+php code into mysql+php code. do you have any document which containing methods to convert sqlite to mysql.
thanks..
this is my code
<?php
try {
//open the database
$db = new PDO('sqlite:cars.sqlite'); //will create the file in current directory. Current directory must be writable
//create the database if does not exist
$db->exec("CREATE TABLE IF NOT EXISTS cars (id INTEGER PRIMARY KEY, manufacturer TEXT, year INTEGER, price INTEGER)");
//select all data from the table
$select = $db->prepare('SELECT * FROM cars ORDER BY id ASC LIMIT 100');
$select->execute();
$out = array(
'cars' => $select->fetchAll(PDO::FETCH_ASSOC)
);
echo json_encode($out);
// close the database connection
$db = NULL;
}
catch (PDOException $e) {
print 'Exception : ' . $e->getMessage();
}
?>
mysql table:cars
CREATE TABLE IF NOT EXISTS `cars` (
`id` int(11) NOT NULL DEFAULT '0',
`manufacturer` text,
`year` int(11) DEFAULT '0',
`price` text,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
as you are using PDO, just create Mysql PDO object, change this part:
$db = new PDO('sqlite:cars.sqlite');
to something like:
$dsn = 'mysql:dbname=yourdbname;host=127.0.0.1';
$user = 'yourdbuser';
$password = 'yourdbpass';
$dbh = new PDO($dsn, $user, $password);
and you're done. You dont need to change anything other.
PDO is portable connection object, it can be used with several different database. more about PDO: http://php.net/manual/en/pdo.construct.php

Categories