PDO creating a table with a foreign key - php

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.

Related

Uncaught PDOException: column does not exist

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?

Retrieving variables from a mySQL table to be used in another row in the same table?

I realize my question may be a bit trivial, but I am new to SQL/mySQL and have not found an answer to my question through google. SO this is the mySQL table I am working with.
create table Contribution
(
ContributionID int not null auto_increment,
CreatedByUserId int not null,
StoryID int not null,
PreviousCID int,
NextCID int,
OriginalCID int,
Content longblob not null,
CreatedDate datetime not null default 'getdate()',
primary key (ContributionID)
);
alter table Contribution add constraint FK_CONTRIBU_REFERENCE_CONTRIBU2 foreign key (PreviousCID)
references Contribution (ContributionID);
alter table Contribution add constraint FK_CONTRIBU_REFERENCE_CONTRIBU3 foreign key (NextCID)
references Contribution (ContributionID);
alter table Contribution add constraint FK_CONTRIBU_REFERENCE_CONTRIBU4 foreign key (OriginalCID)
references Contribution (ContributionID);
What I want to make is a php file to add a new contribution to this table. The new contribution will get a PreviousCID and NextCID from previous existing contributions. How can I get these as variables to add to my new contribution.
Thanks in advance.
Edit: Added the Foreign Keys
first i think you should make a foreign key for PreviousCID and NextCID to Table Contribution itself Like That:
--
-- Constraints for table `contribution`
--
ALTER TABLE `contribution`
ADD CONSTRAINT `contribution_ibfk_1` FOREIGN KEY (`PreviousCID`) REFERENCES `contribution` (`ContributionID`),
ADD CONSTRAINT `contribution_ibfk_2` FOREIGN KEY (`NextCID`) REFERENCES `contribution` (`ContributionID`);
than for php i dont understand what your approach to get:
The new contribution will get a PreviousCID and NextCID from previous existing contributions
but i think this will help you:
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$existing_contribution_id = $_POST['SOME_VARIBALE']; //Here get existing contribution
//get from previous existing contributions
$query = "SELECT * FROM contribution Where =".$existing_contribution_id ;
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result);
//insert new contribution
$sql = "INSERT INTO contribution (CreatedByUserId, StoryID, PreviousCID,
NextCID , OriginalCID , Content)VALUES ('some_user_id', 'some_story_id',".
$row['PreviousCID'].",".$row['NextCID'].", 'some_OriginalCID' , 'some_content')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();

Can't add new records in MySQL

Basically I can create a record using this, but it won't automatically update my ID column to allow for new records. Would i need to add in a expression to update the counter? Or is there a button or switch to make using phpmyadmin to automatically create the new id on submit?
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "message";
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 = "INSERT INTO adminmessages (UserName, Message, Score)
VALUES ('SammyWest', 'Test1', '100')";
// use exec() because no results are returned
$conn->exec($sql);
echo "New record created successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
Table Schema
1 IDPrimaryIndex int(255) No None Change Change Drop Drop
Primary Primary
Unique Unique
Index Index
Spatial Spatial
Fulltext Fulltext
More
2 UserName varchar(255) No None Change Change Drop Drop
Primary Primary
Unique Unique
Index Index
Spatial Spatial
Fulltext Fulltext
More
3 Message varchar(255) No None Change Change Drop Drop
Primary Primary
Unique Unique
Index Index
Spatial Spatial
Fulltext Fulltext
More
4 Score int(255) No None Change Change Drop Drop
Primary Primary
Unique Unique
Index Index
Spatial Spatial
Fulltext Fulltext
More
You must define your id column to be an auto-increment primary key field using :
ALTER TABLE adminmessages CHANGE id id INT AUTO_INCREMENT PRIMARY KEY;

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

Can't create table (errno: 150) on FOREIGN KEY

I saw a lot of same question but I couldn't solve my case.
If I run this code:
<?php
include_once($_SERVER['DOCUMENT_ROOT'].'/config.php');
$servername = HOST;
$username = USERNAME;
$password = PASSWORD;
$dbname = DB;
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// sql to create table
$sql = "CREATE TABLE IF NOT EXISTS Articls (
id INT(10) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(254) COLLATE utf8_persian_ci NOT NULL
) DEFAULT COLLATE utf8_persian_ci";
if ($conn->query($sql) === TRUE) {
echo "Table Articls created successfully";
} else {
echo "Error creating table: " . $conn->error;
}
/////////////////////////////////////////////////////////////////////////
$sql = "CREATE TABLE IF NOT EXISTS Tags (
id INT(10) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
id_articls INT(10) UNSIGNED NOT NULL,
name VARCHAR(256) COLLATE utf8_persian_ci NOT NULL,
FOREIGN KEY(Tags.id_articls) REFERENCES Articls(Articls.id)
) DEFAULT COLLATE utf8_persian_ci";
if ($conn->query($sql) === TRUE) {
echo "Table Tags created successfully";
} else {
echo "Error creating table: " . $conn->error;
}
$conn->close();
?>
I get this error: ( If I remove FOREIGN KEY it works)
Table Articls created successfully Error creating table: Can't create
table 'admin_wepar.Tags' (errno: 150)
Edit
If a change into Articls.id and Tags.id_articls I got this error:
Table Articls created successfullyError 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 'FOREIGN KEY
(Tags.id_articls) REFERENCES Articls(Articls.id) ) DEFAULT COLLA' at
line 5
You need to declare both Articls.id and Tags.id_articls signed or unsigned
Tags.id_articls is a signed integer while Articl.id is an unsigned integer. MySQL requires referencing field to be exactly the same type. Make Tags.id_articls unsigned to have it work.
Additionally, the table names in the column lists are not allowed in MySQL. It is always clear which table is meant: first the referencing table and then the referenced table. So change
FOREIGN KEY(Tags.id_articls) REFERENCES Articls(Articls.id)
into
FOREIGN KEY(id_articls) REFERENCES Articls(id)
and it will work.

Categories