i have a mysql database...
CREATE TABLE `applications` (
`id` int(11) NOT NULL auto_increment,
`jobref` int(11) NOT NULL,
`userid` int(11) NOT NULL,
`q1` text NOT NULL,
`q2` text NOT NULL,
`q3` text NOT NULL,
`sub_q1` text,
`sub_q2` text,
`sub_q3` text,
`timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
`printed` int(11) NOT NULL default '0',
PRIMARY KEY (`id`),
KEY `jobref` (`jobref`),
KEY `applications_ibfk_2` (`userid`),
CONSTRAINT `applications_ibfk_1` FOREIGN KEY (`jobref`) REFERENCES `jobs` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `applications_ibfk_2` FOREIGN KEY (`userid`) REFERENCES `users` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='InnoDB free: 9216 kB; (`jobref`) REFER `iwcjobs/jobs`(`id`) '
and this php file, using mysqli for data operations.
<?php
require_once '../includes/constants.php';
if(isset($_POST['submit'])) {
$q1 = $_POST['question1'];
$q1a = $_POST['ifNoQuestion1'];
$q2 = $_POST['question2'];
$q2a = $_POST['ifNoQuestion2'];
$q3 = $_POST['question3'];
$q3a = $_POST['ifNoQuestion3'];
$JobRef = $_POST['jobref'];
$UserRef = $_POST['id'];
$mysql = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME) or die('There was a problem connecting to the database');
if($stmt = $mysql->prepare('INSERT INTO `applications` VALUES (NULL,?,?,?,?,?,?,?,?,NULL,NULL)')) {
$stmt->bind_param('iissssss',$JobRef,$UserRef,$q1,$q2,$q3,$q1a,$q2a,$q3a);
$stmt->execute();
$stmt->close();
header('location: ../myApps.php?apr=y');
//echo ("<h2>success</h2> - $q1 . $q2 . $q3 . $q1a . $q2a . $q3a . $JobRef . $UserRef");
} else {
echo 'error: ' . $mysql->error;
}
} else {
echo 'errorStage2: ' . $mysql->error;
}
?>
The script is grabbing the correct values from the previous form, but not inserting them into the database. Any ideas people?
Thx in advance,
Aaron.
the way your insert query is currently written, you are trying to set id to NULL, which is a NOT NULL field.
it'd be better to structure the insert would be like this:
INSERT INTO 'applications' (jobref,userid,etc..) VALUES (?,?etc..)
this way, you not try to change id, and just let auto_increment do it's thing.
Related
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;
}
When I trying to run the code, this error shows up
Cannot add or update a child row: a foreign key constraint fails
(hotel_info.results, CONSTRAINT results_ibfk_5 FOREIGN KEY
(CustomerID) REFERENCES customer (CustomerID) ON DELETE CASCADE
ON UPDATE CASCADE)
Here is the code
$result = mysql_query("select customer.CustomerID from customer inner join results on customer.CustomerID = results.CustomerID where customer.Username = '".$aid."'");
if (false === $result)
{
echo mysql_error();
}
if (isset($_POST["submitbtn"]))
{
$LP = $_POST["LP"];
$budget = $_POST["budget"];
$checkin = $_POST["CheckIn"];
$checkout = $_POST["CheckOut"];
$unit = $_POST["unit"];
$smokep = $_POST["SmokeP"];
$spreq = $_POST["sp_req"];
if($checkin>$checkout)
{
?>
<script type="text/javascript">
alert("End Date must greater than Start Date.");
</script>
<?php
}
else
{
$query = mysql_query("INSERT INTO results(`LP`, `budget`, `CheckIn`, `CheckOut`, `unit`, `SmokeP`, `sp_req`, `CustomerID`) values ('$LP', '$budget',
'$checkin', '$checkout', '$unit', '$smokep', '$spreq', '$result')");
if (false === $query)
{
echo mysql_error();
}
echo "Reservation form has been submitted!<br>
<a href=view.php>view all</a>";
}
}
Here is the sql
CREATE TABLE IF NOT EXISTS `results` (
`BookID` int(10) NOT NULL AUTO_INCREMENT,
`LP` varchar(50) DEFAULT NULL,
`budget` varchar(50) DEFAULT NULL,
`CheckIn` varchar(50) DEFAULT NULL,
`CheckOut` varchar(50) DEFAULT NULL,
`unit` int(50) DEFAULT NULL,
`SmokeP` varchar(50) DEFAULT NULL,
`sp_req` varchar(255) DEFAULT NULL,
`CustomerID` int(10) NOT NULL,
PRIMARY KEY (`BookID`),
KEY `Username` (`CustomerID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=48 ;
CREATE TABLE IF NOT EXISTS `customer` (
`CustomerID` int(10) NOT NULL AUTO_INCREMENT,
`Username` varchar(50) NOT NULL,
`Password` varchar(50) NOT NULL,
`Email` varchar(50) NOT NULL,
`ContactNo` int(10) NOT NULL,
PRIMARY KEY (`CustomerID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;
I've already stuck for two days because of this error, please help.
from the error it is clear that foreign key constraint fails. Please check your customer table which must have CustomerID that you are trying to insert in results table insert query i.e. check value of $id. have you assigned any value for $id
$query = mysql_query("INSERT INTO results(`LP`, `budget`, `CheckIn`, `CheckOut`, `unit`, `SmokeP`, `sp_req`, `CustomerID`) values ('$LP', '$budget',
'$checkin', '$checkout', '$unit', '$smokep', '$spreq', '$id')");
In above query value for $id not set so first assign value to that.
I have made a user_login table, having pk = userid.
A credit_request table is created which references to userid as fk.
when the user login, he should see only his entries in the dashboard.
But, here i am not able to insert data, once i link a foreign key to it.
and even the data inserted through phpmyadmin is visible to all users.
Please help me out.
how to insert and retrieve data for logged in users.
<>
//Database setup for Credit request
//Insert data into Credit request
if(isset($_POST['taskid']))
{
$taskid =$_POST['taskid'];
$orderid = $_POST['orderid'];
$status = $_POST['status'];
$query1 = "INSERT INTO credit_request(taskid, orderid, status)
VALUES ('$taskid', '$orderid', '$status')";
if ($connect->query($query1) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $query1 . "<br>" . $connect->error;
}
}
//Display data for credit request
$query2 = "SELECT taskid, orderid, status FROM credit_request WHERE agentid = '$userid'";
$res = $connect->query($query2);
if ($res->num_rows > 0) {
// output data of each row
while($row = $res->fetch_assoc()) {
echo "<br>taskid: " . $row["taskid"]. " -orderid: " . $row["orderid"]. " --:" . $row["status"]."";
}
} else {
echo "0 results";
}
I think you have problem on update, on delete when creating foreign key..
Here's an example of how you'd build your schema:
CREATE TABLE `country` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`country_name` varchar(45) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
CREATE TABLE `state_table` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`state_name` varchar(45) DEFAULT NULL,
`country_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
CONSTRAINT `country_fk` FOREIGN KEY (`country_id`)
REFERENCES `country` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COMMENT='';
INSERT INTO country (country_name) VALUES ('US of A');
INSERT INTO state_table (state_name,country_id) VALUES
('Minnesota', 2),
('Arizona', 2);
See this fiddle for more.
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.
Got three tables (blogs, tags, and blogtags) all AI and ID set to primary key. I'm making a tagging system to keep track of my sites (localhost). The code below is sort of working, but mysql_insert_id just doesn't seem reliable enough since I get some duplicate rows and the occasional 0 value in it.
/// inserts the blog into blog table.
$insert = mysql_query("INSERT INTO blogs (id, url, user, pass, dname, islocal, cat2post) VALUES ('', '$blog', '$bloguser', '$blogpassword', '','NO','$_POST[cat2blog]')")or die( 'Error: ' . mysql_error());
$taggit1 = mysql_insert_id();
$page->content .= "<p class=\"alert\">Success - External blog Added!</p>";
/// let's see what tags we have and explode them.
//$tags = $_POST['tags'] which is an array of words seperated by comma
$tags = 'fishing';
$pieces = explode(",", $tags);
/// go through the tags and add to tags table if needed.
foreach ($pieces as $l){
$l = trim($l);
$query = "SELECT id FROM tags WHERE tag = '$l'";
$result = mysql_query($query) or die( "Error: " . mysql_error() . " in query $query");
$row = mysql_fetch_array($result);
$taggit2 = $row[0];
if ($taggit2 == '') {
$insert2 = mysql_query("INSERT INTO tags (id, tag) VALUES ('','$l')")or die( 'Error: ' . mysql_error());
$taggit2 = mysql_insert_id();
$page->content .= "<p class=\"alert\">This tag didn't exist - so I inserted a new tag</p>";
}
/// for each tag we have, let's insert the blogstags table so we can reference which blog goes to which tag. Blogstags_id should map to the id of the blog.
$insert3 = mysql_query("INSERT INTO blogstags (id, tag_id, blogstags_id) VALUES ('','$taggit2','$taggit1')")or die( 'Error: ' . mysql_error());
}
Guess I need a different solution than mysql_insert_id - ideas? Suggestions?
As requested table structures:
CREATE TABLE IF NOT EXISTS `blogs` (
`id` int(11) NOT NULL auto_increment,
`url` text NOT NULL,
`user` text NOT NULL,
`pass` text NOT NULL,
`dname` text NOT NULL,
`islocal` varchar(3) NOT NULL,
`cat2post` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=12 ;
CREATE TABLE IF NOT EXISTS `blogstags` (
`id` int(11) NOT NULL auto_increment,
`tag_id` int(11) NOT NULL,
`blogstags_id` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;
CREATE TABLE IF NOT EXISTS `tags` (
`id` int(11) NOT NULL auto_increment,
`tag` text NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=7 ;
mysql_insert_id() is working fine. The problem could be that you are using persistant connections. With persistant connections, all kinds of funky concurrency issues can happen. Don't use them unless you really, really have to.
Two options - you could switch to PostgreSQL which allows you to return an auto_incremented ID as part of the insert query.
Or, if you are sticking with MySQL, you can use the MySQL LAST_INSERT_ID() function -