Using PHP PDO query to execute a mySQL query. The query is made up of a multitude of information inputted from foreach(); so I have echo'd out the sql query. The problem lies here but I cannot see it.
This is the output of $sql
CREATE TABLE IF NOT EXISTS `page` (
`page_ID` INT AUTO_INCREMENT NOT NULL,
`url` varchar(200) NOT NULL,
`title` varchar(200),
`subtitle` TEXT,
`content` TEXT,
`parent` varchar(10),
`privacy` varchar(1),
`status` varchar(1),
`creation` varchar(30)
) CHARACTER SET utf8 COLLATE utf8_general_ci;
FYI the query is executed like this:
function createdbtable($table,$fields){
global $fsdbh;
$sql = "CREATE TABLE IF NOT EXISTS `$table` (";
foreach($fields as $field => $type){ $sql.= "`$field` $type,"; }
$sql = rtrim($sql,',');
$sql .= ") CHARACTER SET utf8 COLLATE utf8_general_ci"; return $sql;
if($fsdbh->exec($sql) !== false) { return 1; }
}
This is the error:
#1075 - Incorrect table definition; there can be only one auto column and it must be defined as a key
You forgot the primary key:
CREATE TABLE IF NOT EXISTS `page` (
`page_ID` INT AUTO_INCREMENT NOT NULL,
`url` varchar(200) NOT NULL,
`title` varchar(200),
`subtitle` TEXT,
`content` TEXT,
`parent` varchar(10),
`privacy` varchar(1),
`status` varchar(1),
`creation` varchar(30),
PRIMARY KEY (`page_ID`))
CHARACTER SET utf8 COLLATE utf8_general_ci
Error was quite explicit:
Schema Creation Failed: Incorrect table definition; there can be only one auto column and it must be defined as a key
You must specify the auto increment key as key.
edit:
And for the PHP code, I will go to something like that:
function createdbtable($table,$fields)
{
global $fsdbh;
$sql = "CREATE TABLE IF NOT EXISTS `$table` (";
$pk = '';
foreach($fields as $field => $type)
{
$sql.= "`$field` $type,";
if (preg_match('/AUTO_INCREMENT/i', $type))
{
$pk = $field;
}
}
$sql = rtrim($sql,',') . ', PRIMARY KEY (`'.$pk.'`)';
$sql .= ") CHARACTER SET utf8 COLLATE utf8_general_ci";
if($fsdbh->exec($sql) !== false) { return 1; }
}
Related
I have this code and for some reason it won't get inserted into my database. It's basically taking an array, turning it into a string and then submit the values.
(If you need me to edit to show my whole code, I will do so)
Code I am having issues with down below
$array = array($RaceNumber,$Track,$Num,$HorseName,$Odds,$Color,$Jockey,$Trainer,$PostTime,$Course,$RaceDistance,$Win,$Place,$Show);
for ($a=0; $a<$Num; $a++) {
$dataArray=array($RaceNumber[$a],$Track[$a],$Num[$a],$HorseName[$a],$Odds[$a],$Color[$a],$Jockey[$a],$Trainer[$a],$PostTime[$a],$Course[$a],$RaceDistance[$a],$Win[$a],$Place[$a],$Show[$a]);
$dataArray--;
for ($j=0; $j<$Num; $j++) {
$RaceNumber=$dataArray[0];
$Track=$dataArray[1];
$Num=$dataArray[2];
$HorseName=$dataArray[3];
$Odds=$dataArray[4];
$Color=$dataArray[5];
$Jockey=$dataArray[6];
$Trainer=$dataArray[7];
$PostTime=$dataArray[8];
$Course=$dataArray[9];
$RaceDistance=$dataArray[10];
$Win=$dataArray[11];
$Place=$dataArray[12];
$Show=$dataArray[13];
$sql="INSERT INTO `$Date` (RaceNumber,Track,HorseNum,HorseName,Odds,Color,JockeyName,TrainerName,PostTime,Course,RaceDistance,Win,Place,Show) VALUES ('$RaceNumber','$Track','$Num','$HorseName','$Odds','$Color','$Jockey','$Trainer','$PostTime','$Course','$RaceDistance','$Win','$Place','$Show')";
echo $sql;
mysqli_query($query2,$sql);
}
}
when I echo my $sql I get
INSERT INTO 2018-09-20 (RaceNumber,Track,HorseNum,HorseName,Odds,Color,JockeyName,TrainerName,PostTime,Course,RaceDistance,Win,Place,Show) VALUES ('1','FingerLakes','1','','','Red','','','','Dirt','','none','none','none')
But when I do my query, it isn't inserting into database.
Part of my code where I create the datatable
<?php
if(isset($_POST['submit'])) {
$Date = $_POST['date'];
$sql = "CREATE TABLE IF NOT EXISTS `$Date` (
`Id` int NOT NULL AUTO_INCREMENT PRIMARY KEY,
`RaceNumber` varchar(255) NOT NULL,
`Track` varchar(255) NOT NULL,
`HorseNum` varchar(255) NOT NULL,
`HorseName` varchar(255) NOT NULL,
`Odds` varchar(255) NOT NULL,
`Color` varchar(255) NOT NULL,
`JockeyName` varchar(255) NOT NULL,
`TrainerName` varchar(255) NOT NULL,
`PostTime` varchar(255) NOT NULL,
`Course` varchar(255) NOT NULL,
`RaceDistance` varchar(255) NOT NULL,
`Win` varchar(255) NOT NULL,
`Place` varchar(255) NOT NULL,
`Show` varchar(255) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8"
;
$query2 = mysqli_connect('localhost','root','','Races');
$z= mysqli_query($query2, $sql) or die("Table already exist.. please try again");
echo "Your Table ".$Date." is successfully created <br/>";
$RaceNum = $_POST['RaceNum'];
$i=1;
I am receiving in my error log of
2018-09-20 16:00:59 9444 [ERROR] Incorrect definition of table mysql.column_stats: expected column 'max_value' at position 4 to have type varbinary(255), found type varchar(255).
You are using a column named Show that's a reserved keyword in mysql, add backquotes to it and the insert query should work.
It's worth noting that you shouldn't name your table with only digits and hyphens.
For reference here is the complete list of the reserved keywords:
https://dev.mysql.com/doc/refman/8.0/en/keywords.html
I have an php array:
$cont_array = Array("613:m-ent:id=one","930:m-lk:id=one;x=180;y=79;which=1","1080:m-lev:id=one;");
I want to insert it into a MySQL table with table-name as variable, like $table_name = "user1".
In addition, I want to break each array-element by the first ":" .After executing my php code I get just an empty table.
I need help please. This is my code:
<?php
$connection = mysqli_connect('localhost','root','','prueba');
$cont_array = Array("613:m-ent:id=one","930:m-clk:id=one;x=180;y=79;which=1","1080:m-lev:id=one;");
$table_name = "user1";
$sql_1 = "DROP TABLE IF EXISTS `".$table_name."`;";
$sql_1 .= "CREATE TABLE `".$table_name."` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`usercod` varchar(20) NOT NULL DEFAULT '',
`pid` varchar(1000) NOT NULL DEFAULT '',
`name` varchar(1000) NOT NULL DEFAULT '',
`time` varchar(1000) NOT NULL DEFAULT '',
`all_act` varchar(1000) NOT NULL DEFAULT '',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;";
mysqli_multi_query($connection,$sql_1);
foreach ($cont_array as $row){
$break_e = explode(':', $row, 2);
$sql="INSERT INTO`".$table_name."` (usercode,pid,name,time,all_act) VALUES ("user","pid_value","user_name",'$break_e [0]','$break_e [1]');";
mysqli_query($connection,$sql);
}
?>
This is what I get:
This is what I would like to get:
Your SQL seem to have issue check below SQL statement.
$sql = "INSERT INTO $table_name (usercod,pid,name,time,all_act) VALUES ('user','pid_value','user_name','".$break_e [0]."','".$break_e [1]."')";
I am trying to create a "setup script" for my website. I would like to create the database, adding tables and some content at the same time. So far this is how I did it, but it seems kind off messy using multiple queries:
<?php
$servername = "localhost";
$username = "root";
$password = "password";
// 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 MYDB";
if ($conn->query($sql) === TRUE) {
echo "1. Database created successfully <br/>";
$conn->select_db("MYDB");
$sql_members = "CREATE TABLE MEMBERS (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
USERNAME VARCHAR(30) NOT NULL,
EMAIL VARCHAR(40) NOT NULL,
DISCOUNT VARCHAR(5),
PASSW CHAR(128),
ROLE VARCHAR(9)
)";
if ($conn->query($sql_members) === TRUE) {
echo "2. Table MEMBERS created successfully <br/>";
} else {
echo "Error creating table: " . $conn->error;
}
$sql_content = "CREATE TABLE CONTENT (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
TITLE VARCHAR(30) NOT NULL,
TEXT VARCHAR(30) NOT NULL
)";
if ($conn->query($sql_content) === TRUE) {
echo "3. Table CONTENT created successfully <br/>";
} else {
echo "Error creating table: " . $conn->error;
}
} else {
echo "Error creating database: " . $conn->error;
}
$conn->close();
?>
Is there a better way?
Thanks!
== UPDATE ==
I have tried to export the database and use the resulted .sql file as my setup query, but something is wrong, I get:
Error creating tables: 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 CONTACTS (ID, NAME, PHONE,
EMAIL, ADDRESS, CITY, `COUN' at line 12
CREATE TABLE IF NOT EXISTS `CONTACTS` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`NAME` varchar(25) COLLATE utf8_romanian_ci NOT NULL,
`PHONE` varchar(16) COLLATE utf8_romanian_ci NOT NULL,
`EMAIL` varchar(35) COLLATE utf8_romanian_ci NOT NULL,
`ADDRESS` text COLLATE utf8_romanian_ci NOT NULL,
`CITY` varchar(16) COLLATE utf8_romanian_ci NOT NULL,
`COUNTRY` varchar(16) COLLATE utf8_romanian_ci NOT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_romanian_ci AUTO_INCREMENT=2 ;
INSERT INTO `CONTACTS` (`ID`, `NAME`, `PHONE`, `EMAIL`, `ADDRESS`, `CITY`, `COUNTRY`) VALUES
(1, 'Peter Brown', '0742062307', 'office#shop.com', 'Avenue 13.', 'Santaclaus', 'Austria');
== SOLUTUION ==
I needed "multi_query()" for executing my multiple queries.
You can try this too :p
$errors = [];
$table1 = "CREATE TABLE MEMBERS (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
USERNAME VARCHAR(30) NOT NULL,
EMAIL VARCHAR(40) NOT NULL,
DISCOUNT VARCHAR(5),
PASSW CHAR(128),
ROLE VARCHAR(9)
)";
$table2 = "CREATE TABLE CONTENT (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
TITLE VARCHAR(30) NOT NULL,
TEXT VARCHAR(30) NOT NULL
)";
$tables = [$table1, $table2];
foreach($tables as $k => $sql){
$query = #$conn->query($sql);
if(!$query)
$errors[] = "Table $k : Creation failed ($conn->error)";
else
$errors[] = "Table $k : Creation done";
}
foreach($errors as $msg) {
echo "$msg <br>";
}
You could export the whole database including all tables using the command line or using PhPMyAdmin. Then query the content of the file in php to create the database.
you can create a file and put all your sql queries in it..
CREATE TABLE MEMBERS (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
USERNAME VARCHAR(30) NOT NULL,
EMAIL VARCHAR(40) NOT NULL,
DISCOUNT VARCHAR(5),
PASSW CHAR(128),
ROLE VARCHAR(9)
);
CREATE TABLE CONTENT (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
TITLE VARCHAR(30) NOT NULL,
TEXT VARCHAR(30) NOT NULL
);
then in your php code:
$query = file_get_contents ('queries.sql');
if ($conn->query($query) === TRUE) {
echo "all tables created successfully <br/>";
} else {
echo "Error creating tables: " . $conn->error;
}
I am working on a PHP script where I am using PDO to insert data in mySQL. I am getting an error "23000",1062,"Duplicate entry 'email#email.com-username' for key 'email' but its inserting the data in database.
So here is my PHP codes:
if(isset($_POST['email'])){
$this->db = new connect();
$this->db = $this->db->dbConnect();
$this->encryption = new Encryption();
isset($_POST['timezone']) AND $_POST['timezone'] != 'null' ? date_default_timezone_set($_POST['timezone']): date_default_timezone_set('America/Chicago');
$this->email = $_POST['email'];
$this->username = $_POST['username'];
$this->password = $this->encryption->encode($_POST['password']);
$this->dTime = date("Y-m-d H:i:s");;
$this->sessionKey = $_POST['key'];
$this->country = $_POST['country'];
$this->region = $_POST['uregion'];
$this->browser = $_POST['browser'];
$this->ip = $_POST['accessFrom'];
$regMessage = array('error'=>false);
try{
$query = "INSERT INTO `users` (
id, email, uname, password, regtime, sessionkey, country, region, browser, ip
) VALUES (
(SELECT MAX(id) + 1 FROM `users` AS `maxId`), :email, :uname, :password, :regtime, :sessionkey, :country, :region, :browser, :ip
)";
$register = $this->db->prepare($query, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
if($this->sessionKey === $_SESSION['token']){
$register->bindParam(':uname', $this->username);
$register->bindParam(':email', $this->email);
$register->bindParam(':password', $this->password);
$register->bindParam(':regtime', $this->dTime);
$register->bindParam(':sessionkey', $this->sessionKey);
$register->bindParam(':country', $this->country);
$register->bindParam(':region', $this->region);
$register->bindParam(':browser', $this->browser);
$register->bindParam(':ip', $this->ip);
$register->execute();
if($register->rowCount() > 0){
$regMessage = array('error'=>false);
}else{
$regMessage = array('error'=>true);
}
}else{
throw new PDOException ('Error');
}
}
catch(PDOException $e){
//this is where I am getting error so I am echoing pdo exception error
$regMessage = array('error'=>$e);
}
header('Content-Type: application/json');
echo json_encode($regMessage);
}else{
header('Location: /');
}
At the error, it is showing me duplicate entry of emailid + username for key email which looks like email#email.com-username
But in data base, I am getting email id only in email column and username only in username column.
So can any one tell me whats wrong in my codes?
My users table structure is
CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`email` varchar(250) CHARACTER SET utf8 NOT NULL,
`uname` varchar(20) CHARACTER SET utf8 NOT NULL,
`password` varchar(100) CHARACTER SET utf8 NOT NULL,
`regtime` datetime NOT NULL,
`sessionkey` varchar(10) CHARACTER SET utf8 NOT NULL,
`country` varchar(25) CHARACTER SET utf8 NOT NULL,
`region` varchar(25) CHARACTER SET utf8 NOT NULL,
`browser` varchar(25) CHARACTER SET utf8 NOT NULL,
`ip` varchar(16) CHARACTER SET utf8 NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `email` (`email`,`uname`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
So can anyone tell me where and what is wrong?
Thank you for helping me.
The phrasing in the error message: 'email#email.com-username' for key 'email' directly corresponds to your unique key UNIQUE KEY 'email' ('email','uname'). With that line, you are creating a compound key, which you can think of as an invisible column in the index that is comprised of email-uname. There will not be a column added to your table with this format, and you are seeing the expected behavior that email and uname are treated separately in the table and together for the key.
If you want to test over and over again with the same email and username combo, you'll need to delete that row every time. Without doing this, the error you are seeing is exactly what I would expect to see if you are POST-ing the same data over and over again.
I want to also mention that you have (appropriately) specified that your id column is AUTO_INCREMENT, but then you are calculating the value manually. I would like to discourage you from doing this, and instead use NULL as the insert value. MySQL will use the correct key value in this column, and you will avoid the potential for key collision if you ever had two of these things executing at the same exact moment.
CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`email` varchar(250) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
`uname` varchar(20) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
`password` varchar(100) CHARACTER SET utf8 NOT NULL,
`regtime` datetime NOT NULL,
`sessionkey` varchar(10) CHARACTER SET utf8 NOT NULL,
`country` varchar(25) CHARACTER SET utf8 NOT NULL,
`region` varchar(25) CHARACTER SET utf8 NOT NULL,
`browser` varchar(25) CHARACTER SET utf8 NOT NULL,
`ip` varchar(16) CHARACTER SET utf8 NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
this is the solution.
I am trying to read from a database in MySQL and insert my data in another database in MySQL .
my first table is like this
CREATE TABLE IF NOT EXISTS `link` (
`_id` bigint(20) NOT NULL AUTO_INCREMENT,
`country` varchar(30) COLLATE utf8 DEFAULT NULL,
`time` varchar(20) COLLATE utf8 DEFAULT NULL,
`link` varchar(100) COLLATE utf8 DEFAULT NULL,
PRIMARY KEY (`_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=6149 ;
and the second table is
CREATE TABLE IF NOT EXISTS `country` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`Name` varchar(15) CHARACTER SET utf8 NOT NULL,
`Logo` varchar(50) CHARACTER SET utf8 DEFAULT NULL,
PRIMARY KEY (`ID`),
UNIQUE KEY `Name_3` (`Name`),
UNIQUE KEY `ID` (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=8457 ;
There are about 6114 rows in first table that I'm trying to insert to second using this code
<?php
$tmp = mysqli_connect(******, *****, ****, *****); // First table in here
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$main = mysqli_connect(*****, *****, ****, ******); //Second table in here
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$req = "SELECT country FROM link";
$result = mysqli_query($tmp, $req) or die( mysqli_error($tmp) );
echo "-> ".mysqli_num_rows($result)."<br>";
while ($row = mysqli_fetch_array($result)) {
$con = $row["country"];
$req = "INSERT IGNORE INTO country (Name) VALUES ('$con')";
mysqli_query($main, $req) or die( mysqli_error($main) ) ;
}
?>
problem is the php code works but for 6114 take a very long time which I can't afford .
what is causing the code to take this long to work ? is it the "INSERT IGNORE" ?
is there any way I can do this faster ?
Since the databases are on the same server, you can simply use INSERT ... SELECT (which avoids having to bring the data into PHP and loop over the results executing separate database commands for each of them, so will be considerably faster):
INSERT INTO db2.country (Name) SELECT country FROM db1.link
you can try a create an index on column "country" of table Link.