Complicated SQL insert-update with inner select - php

I have to make a query, which inserts-or-updates in 1 line.
EDIT: I add the WORKING SQL query here.
$this->sqlSavePlot = $this->db->prepare(
"INSERT OR REPLACE INTO plots (id, level, X, Z, name, owner, helpers, denied, biome) VALUES
((select id from plots where level = :level AND X = :X AND Z = :Z),
:level, :X, :Z, :name, :owner, :helpers, :denied, :biome);"
);
Theoretically i want the same stuff in prepared MySQL statements
Currently the mess looks like this:
$this->sqlSavePlot = $this->db->prepare(
"INSERT INTO plots (`id`, `level`, `X`, `Z`, `name`, `owner`, `helpers`, `denied`, `biome`)
VALUES(id = (SELECT id FROM plots WHERE level = level AND X = VALUES(X) AND Z = VALUES(Z)), level = ?, X = ?, Z = ?, name = ?, owner = ?, helpers = ?, denied = ?, biome = ?)
ON DUPLICATE KEY UPDATE
id = VALUES(id),
level = VALUES(level),
X = VALUES(X),
Z = VALUES(Z),
name = VALUES(name),
owner = VALUES(owner),
helpers = VALUES(helpers),
denied = VALUES(denied),
biome = VALUES(biome);"
);
As you see, quite chaotic.
This is how the database looks like:
So in theory, if the user executes the savePlot function, several fields are replaced, like you can see in the PHP code. "sqlSavePlot" is the query i showed above
For some deeper explanation some PHP code:
public function savePlot(Plot $plot): bool{
print "------------------------------------------------------".PHP_EOL;
$this->db->ping();
$helpers = implode(',', $plot->helpers);
$denied = implode(',', $plot->denied);
if ($plot->id <= 0){
$stmt = $this->sqlSavePlot;
$stmt->bind_param('siisssss', $plot->levelName, $plot->X, $plot->Z, $plot->name, $plot->owner, $helpers, $denied, $plot->biome);
} else{
$stmt = $this->sqlSavePlotById;
$stmt->bind_param('isiisssss', $plot->id, $plot->levelName, $plot->X, $plot->Z, $plot->name, $plot->owner, $helpers, $denied, $plot->biome);
}
$result = $stmt->execute();
var_dump($stmt);
var_dump($result);
var_dump($plot);
$this->lastSave = time();
if ($result === false){
$this->plugin->getLogger()->error($stmt->error);
return false;
}
$this->cachePlot($plot);
return true;
}
A plot's id can either be -1 if "empty", or have an ID which is fetched from the savePlot function
I know that the messed up part is around the first "Values":
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 '?, X = ?, Z = ?, name = ?, owner = ?, helpers = ?, denied = ?,
biome = ?)
' at line 2
Could someone explain me what i could put instead?
EDIT: as requested, SHOW CREATE TABLE
CREATE TABLE `plots` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`level` text COLLATE utf8_unicode_ci,
`X` int(11) DEFAULT NULL,
`Z` int(11) DEFAULT NULL,
`name` text COLLATE utf8_unicode_ci,
`owner` text COLLATE utf8_unicode_ci,
`helpers` text COLLATE utf8_unicode_ci,
`denied` text COLLATE utf8_unicode_ci,
`biome` text COLLATE utf8_unicode_ci,
PRIMARY KEY (`id`),
KEY `XZ` (`X`,`Z`)
) ENGINE=InnoDB AUTO_INCREMENT=3609 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci

I think you want something more like this:
INSERT INTO plots (`id`, `level`, `X`, `Z`, `name`, `owner`, `helpers`, `denied`, `biome`)
SELECT id, p.level, p.X, p.Z, ?, ?, ?, ?
FROM plots p
WHERE p.level = ? AND X = ? AND Z = ?
ON DUPLICATE KEY
UPDATE name = VALUES(name),
owner = VALUES(owner),
helpers = VALUES(helpers),
denied = VALUES(denied),
biome = VALUES(biome);
You need to be careful about the order of the arguments. I am guessing that id is the primary key and (X, Z, level) is declared as unique (how you identify duplicates). You only specify that you want to change name in the event of a collision, but this sets all the values (as in your version).

Fixed up my Query with the answer provided by #Gordon Linoff
Turns out i even had a logical issue.. i mixed up the "saveByID" and "saveByXZ"..
public function savePlot(Plot $plot): bool{
$this->db->ping();
$helpers = implode(',', $plot->helpers);
$denied = implode(',', $plot->denied);
if ($plot->id >= 0){
$stmt = $this->sqlSavePlotById;
$stmt->bind_param('isiisssss', $plot->id, $plot->levelName, $plot->X, $plot->Z, $plot->name, $plot->owner, $helpers, $denied, $plot->biome);
} else{
$stmt = $this->sqlSavePlot;
$stmt->bind_param('siisiisssss', $plot->levelName, $plot->X, $plot->Z, $plot->levelName, $plot->X, $plot->Z, $plot->name, $plot->owner, $helpers, $denied, $plot->biome);
}
$result = $stmt->execute();
$this->lastSave = time();
if ($result === false){
$this->plugin->getLogger()->error($stmt->error);
return false;
}
$this->cachePlot($plot);
return true;
}
The fixed up query:
$this->sqlSavePlot = $this->db->prepare(
"INSERT INTO plots (`id`, `level`, `X`, `Z`, `name`, `owner`, `helpers`, `denied`, `biome`)
VALUES((SELECT id
FROM plots p
WHERE p.level = ? AND X = ? AND Z = ?),?,?,?,?,?,?,?,?)
ON DUPLICATE KEY
UPDATE name = VALUES(name),
owner = VALUES(owner),
helpers = VALUES(helpers),
denied = VALUES(denied),
biome = VALUES(biome);"
);
$this->sqlSavePlotById = $this->db->prepare(
"UPDATE plots SET id = ?, level = ?, X = ?, Z = ?, name = ?, owner = ?, helpers = ?, denied = ?, biome = ? WHERE id = VALUES(id);"
);
Thanks alot to everyone! Hope this helps others in the future!

Related

Calling mysql procedure from php with in and out paramenter

Please help me out. I'm trying to insert the records in 2 tables, in 1st table I can insert but for the second table I can't.
I have 3 stored procedures
HotelInsert
GetAccommodationByName
AvailbiltyInsert
It seems like the 1st stored procedure is okay as I can get output in the first table but in the second table I can't get the last inserted id.
First stored procedure
DELIMITER $$
CREATE DEFINER=`kno`#`localhost` PROCEDURE `HotelInsert`(IN `ZIP` BIGINT, IN `Ammn` VARCHAR(255), IN `HotelName` VARCHAR(255), IN `Add1` VARCHAR(255), IN `Add2` VARCHAR(255), IN `Det` VARCHAR(255), IN `ContactPer` VARCHAR(255), IN `Contact` VARCHAR(255), IN `CEmail` VARCHAR(255), IN `Image` VARCHAR(255), IN `StarCateg` TINYINT)
NO SQL
DETERMINISTIC
INSERT INTO Accommodation(
AccommodationId,
AccommodationTypeId,
ZipId,
PackageId,
Amenities,
Name,
AddressOne,
AddressTwo,
AccommodationStatus,
Details,
ContactPerson,
StarCategory,
ImageGallery,
ContactPhone,
ContactEmail
)
VALUES(
NULL,
1,
ZIP,
4,
Ammn,
HotelName,
Add1,
Add2,
1,
Det,
ContactPer,
StarCateg,
Image,
Contact,
CEmail
)$$
DELIMITER ;
Second stored procedure:
DELIMITER $$
CREATE DEFINER=`kno`#`localhost` PROCEDURE `GetAccomodationIdByName`(IN `AccommodationName` VARCHAR(255), OUT `AccId` INT)
NO SQL
DETERMINISTIC
SELECT AccommodationId into AccId from Accommodation where Name=AccommodationName$$
DELIMITER ;
Third stored procedure:
DELIMITER $$
CREATE DEFINER=`kno`#`localhost` PROCEDURE `AvailabilityInsert`(IN `AccId` INT, IN `RTypeId` INT, IN `AvailableRooms` INT, IN `Charges` BIGINT, IN `AvailDate` DATE)
NO SQL
INSERT INTO AccommodationAvailabilty (AvailableId, AccommodationId, RoomTypeId, Available, Price, AvailableDate) VALUES (NULL, AccId, RTypeId, AvailableRooms, Charges, AvailDate)$$
DELIMITER ;
PHP code:
$sql = $db->prepare('CALL HotelInsert(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');
$sql->bind_param('dssssssssss', $ZipId, $Amenities, $Name, $AddressOne, $AddressTwo, $Details, $ContactPerson, $ContactPhone, $ContactEmail , $target_path, $StarCategory);
$sql->execute();
$select = $db->query('SELECT #ZIP,#Ammn, #HotelName, #Add1, #Add2, #Det, #ContactPer,#Contact,#CEmail,#Image, #StarCateg');
$result = $select->fetch_assoc();
$ZipId = $result['#ZIP'];
$Amenities = $result['#Ammn'];
$AccommodationName = $result['#HotelName'];
$AddressOne = $result['#Add1'];
$AddressTwo = $result['#Add2'];
$Details = $result['#Det'];
$ContactPerson = $result['#ContactPer'];
$ContactPhone = $result['#Contact'];
$ContactEmail = $result['#CEmail'];
$target_path = $result['#Image'];
$StarCategory = $result['#StarCateg'];
//Hotel Calling AccommodationId by AccommodationName with GetAccomodationIdByName(); stored procedure.
$sql = $db->prepare('CALL GetAccomodationIdByName(?)');
$sql->bind_param('s', $AccommodationName);
$sql->execute();
$select = $db->query('SELECT #AccId');
$result = $select->fetch_assoc();
$AccommodationId = $result['#AccId'];
//Hotel Insert RoomType by calling AvailabilityInsert(); Store procedure.
$sql = $db->prepare('CALL AvailabilityInsert(?,?,?,?,?)');
$sql->bind_param('iiids', $AccommodationId, $RoomTypeId, $Available, $Price, $AvailableDate);
$sql->execute();
$select = $db->query('SELECT #AccId,#RTypeId, #AvailableRooms, #Charges, #AvailDate');
$result = $select->fetch_assoc();
$AccommodationId = $result['#AccId'];
$RoomTypeId = $result['#RTypeId'];
$Available = $result['#AvailableRooms'];
$Price = $result['#Charges'];
$AvailableDate = $result['#AvailDate'];
header("Location: ../hotel-all.php?id=$Name");
exit();

How to get values from stores and insert into products table?

I am new to statements, so please come slowly on me. I have checked questions asked by others but didnt see a solution to solve my issue.
I am trying to create a userpage with prepared statements so they can add products to their stores.
I would like to get store_id from stores and insert into produtcs on an insert product form.
I have tried several methods but they didnt work.
Here are my attempts:
Connection
$mysqli = new mysqli(host, dbase, username, password);
First method prepare statements: I have tried this method without bind_result too.
if ($stmt = $mysqli->prepare("INSERT INTO products (user_id, cat_id, store_id, item_name, item_code, item_description, item_qtty, item_price, item_seo_url, item_image, item_date) SELECT store_id FROM stores WHERE user_id = ?")) {
$stmt->bind_param("i", $user_id);
$user_id = filterString($_SESSION['id']);
$stmt->execute();
$stmt->bind_result($store_id);
if($stmt->fetch()){
echo " Records created successfully. Redirect to landing page";
header("location: index.php");
exit();
} else{
echo "Something went wrong. Please try again later.";
}
}
$stmt->close();
Second method sql prepare statements: I have tried this too but didnt work:
$sql = "INSERT INTO products (user_id, cat_id, store_id, item_name, item_code, item_description, item_qtty, item_price, item_seo_url, item_image, item_date) SELECT ?, store_id FROM stores WHERE user_id = ?";
if($stmt = $mysqli->prepare($sql)){
$stmt->bind_param("iiisiisiisss", $user_id, $cat_id, $store_id, $item_name, $item_code, $item_description, $item_qtty, $item_price, $item_seo_url, $item_image, $item_date);
$user_id = $_SESSION['id'];
$cat_id = $cat_id;
$store_id = $store_id;
$item_name = $item_name;
$item_code = $item_code;
$item_description = $item_description;
$item_qtty = $item_qtty;
$item_price = $item_price;
$store_seo_url = seo_url($item_name);
$item_image = $vtyol;
$item_date = $date;
if($stmt->execute()){
echo " Records created successfully. Redirect to landing page";
header("location: index.php");
exit();
} else{
echo "Something went wrong. Please try again later.";
}
}
$stmt->close();
Didnt have a chance to get store_id from stores, I echo store ID in page to see if I get it, its empty.
how can I make it work ?
Do I need to declare all values in bind_param in first method ? (I tried and didnt work).
if so, how to add clause $stmt->bind_param("i", $user_id);.
I really dont know what else to try, need your advice and helps.
Gtg to hospital now be back in 1 hour, will answer your questions and answers.
Thank you all
Last example I tried with the code from #Michael Eugene Yuen it keep saying something went wrong, because of cant get $store_id from stores table.
My codes were to long so I shortened them and tried getting same result.
Here is last example not wroking:
$sql = "INSERT INTO products (
user_id, store_id, name, salary
)
SELECT ?, ?, ?, ?,
`store_id` FROM stores WHERE user_id = ?";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("iisii", $user_id, $store_id, $name, $salary, $user_id);
$user_id = $user_id;
$store_id = $store_id;
$name = $name;
$salary = $salary;
if($stmt->execute()){
header("location: index.php");
exit();
} else{
echo "Something went wrong. Please try again later.";
}
$stmt->close();
Database struckter for both tables:
CREATE TABLE IF NOT EXISTS `products` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` varchar(100) NOT NULL,
`store_id` varchar(100) NOT NULL,
`name` varchar(255) NOT NULL,
`salary` int(10) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
CREATE TABLE IF NOT EXISTS `stores` (
`store_id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` varchar(100) NOT NULL,
`name` varchar(255) NOT NULL,
`salary` int(10) NOT NULL,
PRIMARY KEY (`store_id`)
) ENGINE=MyISAM AUTO_INCREMENT=3 DEFAULT CHARSET=latin1;
INSERT INTO `stores` (`store_id`, `user_id`, `name`, `salary`) VALUES
(1, '12', 'aaaaaaaaaaad', 12),
(2, '12', 'sada', 1234656);
Your were trying to insert data into 11 columns but only 1 value was passed into your statements
Your statement should look like this:
$sql = "INSERT INTO products (
user_id, cat_id, item_name, item_code, item_description,
item_qtty, item_price, item_seo_url, item_image, item_date,
store_id
)
SELECT ?, ?, ?, ?, ?,
?, ?, ?, ?, ?,
`store_id` FROM stores WHERE user_id = ?";
$stmt = $mysqli->prepare($sql);
Bind your $user_id twice. The first one is for your first placeholder and the last one is for your sub-select statement (bind_param)
$stmt->bind_param("iisisiisssi", $user_id, $cat_id, $item_name, $item_code, $item_description, $item_qtty, $item_price, $item_seo_url, $item_image, $item_date, $user_id);
$user_id = $_SESSION['id'];
$cat_id = $cat_id;
$item_name = $item_name;
$item_code = $item_code;
$item_description = $item_description;
$item_qtty = $item_qtty;
$item_price = $item_price;
$store_seo_url = seo_url($item_name);
$item_image = $vtyol;
$item_date = $date;
if($stmt->execute()){
echo " Records created successfully. Redirect to landing page";
$stmt->close();
header("location: index.php");
exit();
} else{
echo "Something went wrong. Please try again later.";
}
And based on your newly added Example 2, the number of columns, placeholders mismatch the number of bind_param again. Also, when you look at your stores table, you have two records under the same user_id. So which store_id you expect to insert to your store table?
I have used LIMIT 1 for now but certainly this is not the correct approach.
$sql = "INSERT INTO products (
user_id, name, salary, store_id
)
SELECT ?, ?, ?, `store_id` FROM stores WHERE user_id = ? LIMIT 1";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("isii", $user_id, $name, $salary, $user_id);
$user_id = 12;
$name = 'john';
$salary = 1200;
if($stmt->execute()){
header("location: index.php");
exit();
} else {
echo "Something went wrong. Please try again later.";
}
$stmt->close();
This is an sql statement with hardcoded values:
$sql = "INSERT INTO products (
user_id, name, salary, store_id
)
SELECT 12, 'john', 1200,
`store_id` FROM stores WHERE user_id = 12 LIMIT 1";
This is same statement with variables:
$sql = "INSERT INTO products (
user_id, name, salary, store_id
)
SELECT $user_id, $name, $salary,
`store_id` FROM stores WHERE user_id = $user_id LIMIT 1";
This is same statement with placeholders:
$sql = "INSERT INTO products (
user_id, name, salary, store_id
)
SELECT ?, ?, ?,
`store_id` FROM stores WHERE user_id = ? LIMIT 1";
$stmt->bind_param("isii", $user_id, $name, $salary, $user_id);
$user_id = 12;
$name = 'john';
$salary = 1200;

Database error. You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax

I am getting this error:
An error occured: Database error. You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '#gmail.com, salt = , iteration = 12, method = blowfish, person_id' at line 1
Here is the code:
$data_con = new data_abstraction;
$data_con->execute_query("INSERT into `USER` SET `username` = $user, `password` = $phsh, `email` = $email, `salt` = $salt, `iteration` = $new_iteration, `method` = $new_method, `person_id` = $result2, `role_id` = $result4, `skin_id` = $result5");
Edit:
I already used prepared the query, used parameterized statements and bind the parameters. The error has gone but the details I want to be inserted into the table are not added.
Here is my code:
if(!($sql = $link->prepare("INSERT into `USER` SET
`username` = ?,
`password` = ?,
`email` = ?,
`salt` = ?,
`iteration` = ?,
`method` = ?,
`person_id` = ?,
`role_id` = ?,
`skin_id` = ?"))){
echo "SQL Query Preparation has failed";
}
if(!($sql->bind_param("ssssisiii", $user, $phsh, $email, $new_salt, $new_iteration, $new_method, $result2, $result4, $result5))){
echo "Parameter Binding failed";
}
if(!($sql->execute())){
echo "MySQL Query Execution has failed";
}
All text data must be wrapped in quotes in a concatenated query like this. It is also legal to wrap integers in quotes so its safer to do both like this
$data_con = new data_abstraction;
$data_con->execute_query("INSERT into `USER` SET
`username` = '$user',
`password` = '$phsh',
`email` = '$email',
`salt` = '$salt',
`iteration` = '$new_iteration',
`method` = '$new_method',
`person_id` = '$result2',
`role_id` = '$result4',
`skin_id` = '$result5'");
It would be better to use a parameterised query like this and then bind the values
$sql = "INSERT into `USER` SET
`username` = ?,
`password` = ?,
`email` = ?,
`salt` = ?,
`iteration` = ?,
`method` = ?,
`person_id` = ?,
`role_id` = ?,
`skin_id` = ?");
And then prepare the query and bind the values to the ? using bind_param
This will also protect you from SQL Injection Attack
Have a look at what happened to Little Bobby Tables Even
if you are escaping inputs, its not safe!
Use prepared parameterized statements
$email contains special character so quote email column value email = '$email'
You need to wrap each $variable in single quotes ''. BTW, that is horrible code, unless the execute_query() method sanitizes those input variables. If it doesn't, you seriously need to take a look at parameterizing your queries. I'm assuming you use mysqli? If so, take a look here: http://php.net/manual/en/mysqli.prepare.php

Correct Syntax For Preparing MySQL INSERT INTO ON DUPLICATE KEY UPDATE?

I have been troubleshooting my code, searching stackoverflow to find the correct syntax to do this with PHP. I can't figure out how the ON DUPLICATE KEY UPDATE syntax works with prepared statements:
INSERT INTO placements_by_date (DateVal, PlacementName, PlacementId,
CampaignId, AdName, Format, TagId, Impressions, Clicks, Leads, MediaCost)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON DUPLICATE KEY UPDATE
// HERE COMES THE TRICKY SYNTAX:
DateVal = VALUES(DateVal), PlacementName = VALUES(PlacementName),
PlacementId = VALUES(PlacementId), CampaignId = VALUES(CampaignId),
AdName = VALUES(AdName), Format = VALUES(Format), TagId = VALUES(TagId),
Impressions = ?, Clicks = ?, Leads = ?, MediaCost = ?
I have tried many variations:
...ON DUPLICATE KEY UPDATE
DateVal = VALUES('$DateVal'), PlacementName = VALUES('$PlacementName'),
PlacementId = VALUES('$PlacementId'), CampaignId = VALUES('$CampaignId'),
AdName = VALUES('$AdName'), Format = VALUES('$Format'), TagId = VALUES('$TagId'),
Impressions = VALUES(?), Clicks = VALUES(?), Leads = VALUES(?),
MediaCost = VALUES(?)";
I store this as a string, $sql, and do my usual stuff:
$mysqli = new mysqli(...
...
$stmt = $mysqli -> prepare($sql);
$stmt -> bind_param('sissiiiis', $PlacementName, $PlacementId,
$AdName, $Format, $TagId, $Impressions,
$Clicks, $Leads, $MediaCost);
...
But maybe the parameters should be bound differently??
I enabled tried reading through the feedback but this was too generic with no actionable insights.
$driver = new mysqli_driver();
$driver->report_mode = MYSQLI_REPORT_ALL;
Hoping you have some insight to share?
Thanks!
Why not continue using the VALUES() method?
INSERT INTO placements_by_date(DateVal, PlacementName, PlacementId,
CampaignId, AdName, Format, TagId,
Impressions, Clicks, Leads, MediaCost
)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON DUPLICATE KEY UPDATE
DateVal = VALUES(DateVal), PlacementName = VALUES(PlacementName),
PlacementId = VALUES(PlacementId), CampaignId = VALUES(CampaignId),
AdName = VALUES(AdName), Format = VALUES(Format), TagId = VALUES(TagId),
Impressions = VALUES(Impressions), Clicks = VALUES(Clicks), Leads = VALUES(Leads),
MediaCost = VALUES(MediaCost);
You don't specify what the unique key is. However, you don't need to include those columns in the update statements, because they are already the same.
If, perchance, you want to increment the last four values rather than just assign them, you can do that too:
ON DUPLICATE KEY UPDATE
DateVal = VALUES(DateVal), PlacementName = VALUES(PlacementName),
PlacementId = VALUES(PlacementId), CampaignId = VALUES(CampaignId),
AdName = VALUES(AdName), Format = VALUES(Format), TagId = VALUES(TagId),
Impressions = Impressions + VALUES(Impressions),
Clicks = Clicks + VALUES(Clicks),
Leads = Leads + VALUES(Leads),
MediaCost = MediaCost + VALUES(MediaCost)
EDIT:
The following should work just to update the last four columns:
INSERT INTO placements_by_date(DateVal, PlacementName, PlacementId,
CampaignId, AdName, Format, TagId,
Impressions, Clicks, Leads, MediaCost
)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON DUPLICATE KEY UPDATE
Impressions = VALUES(Impressions), Clicks = VALUES(Clicks), Leads = VALUES(Leads),
MediaCost = VALUES(MediaCost);

MySQL table only submitting first time from EXT js + PHP entry

I am having a problem with my MySQL.
I have everything setup and all is well, but when I submit my form it will only work if the table is completely empty. It will not submit another entry if there is already information stored in the table.
here is the mysql table
CREATE TABLE student
(StudentID int NOT NULL,
StudentFirst varchar(30),
StudentLast varchar(30),
StudentEmail varchar(254),
StudentPhone varchar(12),
StudentDOB date,
DateStarted date,
LessonID int,
StudentAddress varchar(50),
StudentCity varchar(30),
StudentState char(2),
StudentZip varchar(10),
MusicInterest text);
alter table student add constraint StudentPK primary key AUTO_INCREMENT (StudentID);
alter table student add constraint LessonFK foreign key (LessonID) references lesson(LessonID);
This is my PHP
if(isset($_REQUEST['action'])){
switch($_REQUEST['action']){
case 'submit_student':
$first = $_REQUEST['StudentFirst'];
$last = $_REQUEST['StudentLast'];
$email = $_REQUEST['StudentEmail'];
$phone = $_REQUEST['StudentPhone'];
$dob = $_REQUEST['StudentDOB'];
$datestarted = $_REQUEST['DateStarted'];
$lessonid = $_REQUEST['LessonID'];
$address = $_REQUEST['StudentAddress'];
$city = $_REQUEST['StudentCity'];
$state = $_REQUEST['StudentState'];
$zip = $_REQUEST['StudentZip'];
$musicinterest = $_REQUEST['MusicInterest'];
$stmt = $dbh->prepare("insert into student (StudentFirst, StudentLast, StudentEmail, StudentPhone, StudentDOB, DateStarted, LessonID, StudentAddress, StudentCity, StudentState, StudentZip,MusicInterest) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);");
$stmt -> bindParam(1,$first);
$stmt -> bindParam(2,$last);
$stmt -> bindParam(3,$email);
$stmt -> bindParam(4,$phone);
$stmt -> bindParam(5,$dob);
$stmt -> bindParam(6,$datestarted);
$stmt -> bindParam(7,$lessonid);
$stmt -> bindParam(8,$address);
$stmt -> bindParam(9,$city);
$stmt -> bindParam(10,$state);
$stmt -> bindParam(11,$zip);
$stmt -> bindParam(12,$musicinterest);
$stmt -> execute();
break;
and my EXTJs
function addStudent(){
Ext.Ajax.request ({
url: 'inc/template.php',
params: {action: 'submit_student',
StudentFirst:firstNameTextField.getValue(),
StudentLast:lastNameTextField.getValue(),
StudentEmail: emailTextField.getValue(),
StudentPhone:phoneNumberTextField.getValue(),
StudentDOB:Ext.util.Format.date(dateOfBirth.getValue(), 'Y-m-d'),
DateStarted:dateStarted.getValue(),
LessonID:dayTypeCombo.getValue(),
StudentAddress:streetTextField.getValue(),
StudentCity:cityTextField.getValue(),
StudentState:stateTextField.getValue(),
StudentZip:zipTextField.getValue(),
MusicInterest:musicInterest.getValue()
},
method: 'POST',
});
tabPanel.activate(studentGrid);
tabPanel.activate(scheduleGrid);
clearStudentForm();
I have no idea why it only submits one time. It is really baffling. It shows the post in firebug.
any help is much appreciated.
I am not sure about AUTO-INCREMENT statement at
alter table student add constraint StudentPK primary key AUTO_INCREMENT (StudentID);
Also i think, you should use this syntax for multiple columns. for one column use
CREATE TABLE student
(StudentID int NOT NULL PRIMARY KEY,
StudentFirst varchar(30),
...

Categories