Can't add new records in MySQL - php

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;

Related

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();

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.

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.

Add a unique key to database

I've got a form on my website for users to input their fname, sname, company,phone,email which then gets updated to a database on submit. I also have a field in my database for a unique userID to incase users have same name and company ect. When submitting my form how is it possible to add in this field, a unique number so that it is +1 from the fields taken already. At the minute there are only 3 userIDs so i need the next inputted one to be 4 and so on.
At the moment I have this.
require_once('dbConnect.php');
//taken from a smarty template form.
$addForename = $_POST['forename'];
$addSurname = $_POST['surname'];
$addCompany = $_POST['company'];
$addContact = $_POST['contact'];
$addEmail = $_POST['email'];
public function addUser($addForename,$addSurname,$addCompany,$addContact,$addEmail)
{
$sql = "INSERT INTO `Users` (`Forename`, `Surname`, `ComanyName`, `Phone`, `Email`) VALUES ('".$addForename."','".$addSurname."','".$addCompany."','".$addContact."','".$addEmail."')";
$databaseAccess = new DatabaseConnect();
try
{
$result = $databaseAccess->connect($sql, "add");
}
catch (Exception $e)
{
throw new Exception("Adding User Failed !!!");
}
if ($result)
{
return 1;
}
else{return 0;}
}
thanks
If you are using phpmyadmin there should be a checkbox when youre creating a new column with "A_I" or Auto_Increment.. you have to check that and then it will count your entrys.
Create the row as an auto_increment in the database:
create table someName (ID int primary key auto_increment, col1 int ...);
Then when you are inserting data, either pass it a null, or don't insert that field like this:
insert into someName (col1) values (3);
or
insert into someName (ID, col1) values (null, 3);
You can modify your current table with the following:
ALTER TABLE someName MODIFY COLUMN ID INT NOT NULL AUTO_INCREMENT , ADD PRIMARY KEY (ID);
create the ID:
ALTER TABLE users ADD ID INT UNSIGNED
NOT NULL AUTO_INCREMENT, ADD PRIMARY KEY (ID);
and start the auto-increment where you want
ALTER TABLE tbl AUTO_INCREMENT = 4;
Create a column set it as a primary key and auto increment. You can even write a stored procedure for inserting in the table. That way you don't have to write query every time and not have to worry about escape characters. If you want the particular no to be returned from stored procedure use SCOPE_IDENTITY() in the stored procedure.

Categories