Every time I run my code or add new date to database my values get added again to tables. I don't know if it is an issue with how I create table or add values.
my code:
$uzk_len="create table if not exists buyers
(
id int(4) primary key auto_increment,
code varchar(4),
name varchar(30),
adress varchar(30)
)";
$uzk_lenv=mysql_query($uzk_len) or die ("table not created");
$uzk_duom="insert into buyers
(code,name,adress)
values
('1001','Maxima','Tilzes 25'),
('1002','IKI','Tilzes 111'),
('1003','Rimi','Saules 58'),
('1004','Norfa','Pramones 195')";
$uzk_duomv=mysql_query($uzk_duom) or die ("Failed to insert");
Drop the table before creating new.
DROP TABLE IF EXISTS buyers;
Related
I wrote a query to put records in a table and at the same time create another. The table is created but the data is not entered. Where am I wrong? This is my code:
$sql = "INSERT INTO progetti
(data, ora, nome_progetto, anagrafica_id, preventivo, budget, eurora, scadenza, scontoaggiuntivo, ref1, tel_ref1, mail_ref1, contenuto, stato_id)
VALUES
('".$_POST["data"]."',
'".$_POST["ora"]."',
'".$_POST["nome_progetto"]."',
'".$_POST["anagrafica_id"]."',
'".$_POST["preventivo"]."',
'".$_POST["budget"]."',
'".$_POST["eurora"]."',
'".$_POST["scadenza"]."',
'".$_POST["scontoaggiuntivo"]."',
'".$_POST["ref1"]."',
'".$_POST["tel_ref1"]."',
'".$_POST["mail_ref1"]."',
'".$_POST["contenuto"]."',
'".$_POST["stato_id"]."'
)";
"CREATE TABLE $_POST[nome_progetto] (
id INT(11) AUTO_INCREMENT PRIMARY KEY,
data date,
intervento varchar(30),
descrizione varchar(70),
ore int(2)
)";
Alright I have the foreign keys set up and I'm able to join the tables via the sql tab in phpmyadmin, but I can't figure out how to get things to work properly when I allow a user to input the values via a form. Right now I'm just playing around with a very basic form that allows first name, last name, and phone number. First and Last name get sent to a table named Customer and phone number gets passed to a table called Customer_Number. The problem is that now when I enter values into the input fields, First and Last name saved to the DB table, but phone number doesn't save and spits out this error message Cannot add or update a child row: a foreign key constraint fails (``.Customer_Number, CONSTRAINT Customer_Number_ibfk_1 FOREIGN KEY (Customer_ID) REFERENCES Customer (Customer_ID))
Is there a way I can just add these values and the foreign key for my Customer_Number table update according to the correct customer?
Here is my code:
<?php
$con=mysqli_connect("");
if(mysqli_connect_errno()){
echo "There was a mistake connecting". mysqli_connect_errno();
}
$First=mysqli_real_escape_string($con,$_POST["FirstName"]);
$Last=mysqli_real_escape_string($con, $_POST["LastName"]);
if(!empty($_POST["FirstName"]) && !empty($_POST["LastName"])){
$sql="INSERT INTO Customer(First,Last)
VALUE('$First', '$Last')";
if(!mysqli_query($con,$sql)) {
die("ERROR". mysqli_error($con));
}else{
echo"record added";
}
}
mysql_close($con);
?>
<?php
$con=mysqli_connect("");
if(mysqli_connect_errno()){
echo "There was a mistake connecting". mysqli_connect_errno();
}
$Phone=mysqli_real_escape_string($con,$_POST["Number"]);
if(!empty($_POST["Number"])){
$sql="INSERT INTO Customer_Number(Number)
VALUE('$Phone')";
if(!mysqli_query($con,$sql)) {
die("ERROR". mysqli_error($con));
}else{
echo"record added";
}
}
mysql_close($con);
?>
And here is my table information:
CREATE TABLE `Customer` (
`Customer_ID` int(11) NOT NULL AUTO_INCREMENT,
`First` varchar(255) NOT NULL,
`Last` varchar(255) NOT NULL,
PRIMARY KEY (`Customer_ID`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1
CREATE TABLE `Customer_Number` (
`Num_ID` int(11) NOT NULL AUTO_INCREMENT,
`Customer_ID` int(11) NOT NULL,
`Number` varchar(255) NOT NULL,
PRIMARY KEY (`Num_ID`),
KEY `Customer_ID` (`Customer_ID`),
CONSTRAINT `Customer_Number_ibfk_1` FOREIGN KEY (`Customer_ID`) REFERENCES `Customer` (`Customer_ID`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1
I know there has got to be a way to do this, but I'm new to this and my google searches has only really covered how to do this via phpMyAdmin and manually entering in the foreign key values.
Since Customer_Number.Customer_ID is a foreign key pointing to the corresponding Customer row, you need to set Customer_Number.Customer_ID to the correct value when inserting the number after inserting the Customer.
As long as you're using the same connection (ie skip closing/reopening it between the queries), you can use LAST_INSERT_ID() to get the Customer_ID of the just inserted customer, something like (the SQL part only);
INSERT INTO Customer(First,Last)
VALUES ('$First', '$Last')
INSERT INTO Customer_Number(Customer_ID, Number)
VALUES (LAST_INSERT_ID(), '$Phone')
when I run this php file in my wamp server it connects to database, selects database but not create table .
the output is this:
connected to database succussfully.
connected to database store_db succussfully.
table users was not created.
what is the problem???
php code:
<?php
$sql='CREATE TABLE users
(
PID INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(PID),
NAME CHAR(20),
PASSWORD CHAR(15),
)';
mysql_connect("localhost","root","") or die('could not connect to database.');
echo 'connected to database succussfully.<br>';
mysql_select_db('store_db') or die('database store_db not found.');
echo 'connected to database store_db succussfully.<br>';
mysql_query($sql) or die('table users was not created');
echo 'table users was created in database store_db succussfully.<br>';
?>
<?php
$sql='CREATE TABLE users
(
PID INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(PID),
NAME CHAR(20),
PASSWORD CHAR(15),
)';
remove the comma after PASSWORD CHAR(15),
in the event of an error, you can always retrieve errors using mysql_error().
however. you should not be using the old mysql functions. much better and more secure options exist in the PDO and MySQLi extensions.
Your $sql:
$sql='CREATE TABLE users
(
PID INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(PID),
NAME CHAR(20),
PASSWORD CHAR(15),
)';
should be:
$sql='CREATE TABLE users
(
PID INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(PID),
NAME CHAR(20),
PASSWORD CHAR(15)
)';
You should remove comma right after PASSWORD CHAR(15)
To get the proper error message always use below code so that you can figure out exact error in future.
mysql_query($sql) or die(mysql_error());
Make sure the MySQL user you are attempting to create the table with has permissions to do so. (e.g. the user has been granted the 'CREATE' privileges for that database.)
Probably a simple overlook, but I cannot seem to create a table with my PHP script. My first question is that I want to add a table to an existing DB. How do I tell the server which DB to create the table in? The code to create a table is pretty simple, but here it is ..
CREATE TABLE Countr(ID INT IDENTITY(1,1) PRIMARY KEY,Page VARCHAR(50),
Month INT, Always INT);
Any assistance would be appreciated.
In your PHP server you should be connecting to your database. Your code might be like this:
mysqli_connect("sqlserver.mysite.com", "username", "password") or die("SQL Error: Cant connect to database.");
Then you should do:
mysqli_select_db("database_name") or die("SQL Error: Cant select database");
to select the database before performing any other sql statements. Such as creating tables.
http://dev.mysql.com/doc/refman/5.0/en/use.html
USE my_db1;
CREATE TABLE ...
USE my_db2;
CREATE TABLE ...
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
mysql_select_db('database_name', $link);
CREATE TABLE Countr(ID INT IDENTITY(1,1) PRIMARY KEY,Page VARCHAR(50), Month INT, Always INT);
Try this code to create table in any database.
CREATE TABLE db_name.Countr(ID INT IDENTITY(1,1) PRIMARY KEY,Page VARCHAR(50), Month INT, Always INT);
Note: Current database user has create table privileges in the other database.
$sql = "CREATE TABLE wp_shifts (
user_id bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT,
transact_id int(64),
hours decimal(10,2),
date varchar(64),
time1 varchar(64),
PRIMARY KEY (user_id)
)";
$results = $wpdb->query($sql);
Create a Table
The CREATE TABLE statement is used to create a table in MySQL.
We must add the CREATE TABLE statement to the mysqli_query() function to execute the command.
The following example creates a table named "Persons", with three columns: "FirstName", "LastName" and "Age":
<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Create table
$sql="CREATE TABLE Persons(FirstName CHAR(30),LastName CHAR(30),Age INT)";
// Execute query
if (mysqli_query($con,$sql))
{
echo "Table persons created successfully";
}
else
{
echo "Error creating table: " . mysqli_error($con);
}
?>
I have set up four additional tables for my plugin to use what I am trying to do is take a name and assign it a ID then use this data to populate drop down menus with a name and the same for class and position I am unsure as to how to do this correctly this is what i have so far.
$sql = "CREATE TABLE $tableName (
recordID int NOT NULL AUTO_INCREMENT,
PRIMARY KEY(recordID),
driverID int,
driverName varchar(30),
classID int,
driverClass varchar(20),
posID,
driverPosition varchar(6),
trackName varchar(30),
raceDate date
);";
$sql = "CREATE TABLE $driverTableName (
driverID int NOT NULL AUTO_INCREMENT,
PRIMARY KEY(driverID),
driverName varchar(30)
);";
$sql = "CREATE TABLE $classTableName (
classID int NOT NULL AUTO_INCREMENT,
PRIMARY KEY(classID),
className varchar (20)
);";
$sql = "CREATE TABLE $posTableName (
posID int NOT NULL AUTO_INCREMENT,
PRIMARY KEY(posID),
posName varchar(6)
);";
The bottom three tables will store the data I want to populate the drop down boxes to create a record with I am unsure as to how to link them to the top table where this record will be stored.
This is pretty much a indexing issue. If you are going to access the database separately to the standard calls that Wordpress provides, you should at the very least use http://codex.wordpress.org/Class_Reference/wpdb as it will save you some coding time.
The rest of it is a MySQL question. (Assuming you are using MySQL) In how to properly index the data together and then parsing the data as it comes in.