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();
Related
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;
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!
I have a weird issue that's driving me crazy.
The first time I insert data into a mysql table, it works. It fails silently after that.
This is the table:
$students =
'CREATE TABLE IF NOT EXISTS students (
student_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
nombre VARCHAR(255) NOT NULL,
apellido VARCHAR(255) NOT NULL,
natalicio INT NOT NULL,
cuil INT UNIQUE NOT NULL,
trabajador_teatro TINYINT NOT NULL,
ocupacion VARCHAR(255),
derivado_ministerio TINYINT NOT NULL,
ex_alumno TINYINT NOT NULL,
intereses VARCHAR(255),
matricula VARCHAR(255) NOT NULL,
estudios_formales VARCHAR(255),
domicilio VARCHAR(255),
mail VARCHAR(255) NOT NULL,
mail_confirmation_key VARCHAR(255) ,
created INT,
tel INT NOT NULL,
active TINYINT NOT NULL
)';
This is the method that inserts the data, remember, first insert works well:
/
/Insert user data
public function insertStudent($options, $db_object) {
$sql='INSERT INTO students (nombre, apellido, natalicio, cuil, trabajador_teatro, ocupacion,
derivado_ministerio, ex_alumno, intereses, matricula, estudios_formales, domicilio, mail, mail_confirmation_key,
created, tel, active)
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)';
if (is_array($options) ) {
$nombre = $options['nombre'];
$apellido = $options['apellido'];
$natalicio = $options['natalicio'];
$cuil = $options['cuil'];
$trabajador_teatro = $options['trabajador_teatro'];
$ocupacion = $options['ocupacion'];
$derivado_ministerio = $options['derivado_ministerio'];
$ex_alumno = $options['ex_alumno'];
$intereses = $options['intereses'];
$estudios_formales = $options['estudios_formales'];
$domicilio = $options['address'];
$mail = $options['mail'];
$tel = $options['tel'];
}//End if
$mail_confirmation_key = $this->mailConfKey();
$date = new DateTime();
$created = $date->getTimestamp();
$active = 0;
$matricula = 'TAE'."-".ceil((substr($cuil, 4)+$created)/5);
/* Prepare statement */
$stmt = $db_object->prepare($sql);
if($stmt === false) {
trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $db_object->error, E_USER_ERROR);
}//End if
/* Bind parameters. TYpes: s = string, i = integer, d = double, b = blob */
$stmt->bind_param('ssiiisiissssssiii',$nombre, $apellido, $natalicio, $cuil, $trabajador_teatro, $ocupacion, $derivado_ministerio,
$ex_alumno, $intereses, $matricula, $estudios_formales, $domicilio, $mail, $mail_confirmation_key, $created, $tel, $active);
/* Execute statement */
$stmt->execute();
echo $stmt->insert_id;
echo $stmt->affected_rows;
$stmt->close();
}//End insertStudent
There are no apache2 log errors. These are mysql logs, the first query that works, and the subsequent one that does not work.
First Query
61 Prepare INSERT INTO students (nombre, apellido, natalicio, cuil, trabajador_teatro, ocupacion,
derivado_ministerio, ex_alumno, intereses, matricula, estudios_formales, domicilio, mail, mail_confirmation_key,
created, tel, active)
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
61 Execute INSERT INTO students (nombre, apellido, natalicio, cuil, trabajador_teatro, ocupacion,
derivado_ministerio, ex_alumno, intereses, matricula, estudios_formales, domicilio, mail, mail_confirmation_key,
created, tel, active)
VALUES ('Diego','Lopez',1395975600,20218976543,1,'Surfer',1,0,'Volar','TAE-280617849','primario','20 1122','test#test.com','jtvSRLYfU8uyiHVh6gPp',1394$
61 Close stmt
Second query
72 Prepare INSERT INTO students (nombre, apellido, natalicio, cuil, trabajador_teatro, ocupacion,
derivado_ministerio, ex_alumno, intereses, matricula, estudios_formales, domicilio, mail, mail_confirmation_key,
created, tel, active)
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
72 Close stmt
72 Quit
I fetch data from $_POST and use it. It's just a beta, I know it's not properly sanitized.
$nombre = stripcslashes($_POST['nombre']);
$apellido = stripcslashes($_POST['apellido']);
$natalicio = $core->formatTimeToUs($_POST['birthday']);
$mail = $_POST['mail'];
$address = stripcslashes($_POST['address']);
$tel = stripcslashes($_POST['tel']);
$cuil = stripcslashes($_POST['cuil']);
$curso = stripcslashes($_POST['curso']);
$niv_educ = stripcslashes($_POST['niv_educ']);
$trabajador_teatro = stripcslashes($_POST['trabajador_teatro']);
$ocupacion = stripcslashes($_POST['ocupacion']);
$derivado_ministerio = stripcslashes($_POST['derivado_ministerio']);
$ex_alumno = stripcslashes($_POST['ex_alumno']);
$intereses = stripcslashes($_POST['intereses']);
$estudios_formales = stripcslashes($_POST['niv_educ']);
$student = new student();
$student_user_array = array('nombre'=>$nombre, 'apellido'=>$apellido , 'natalicio' => $natalicio, 'cuil'=>$cuil, 'mail' => $mail, 'address' => $address, 'tel' => $tel,
'curso'=>$curso, 'niv_educ'=>$niv_educ, 'trabajador_teatro' => $trabajador_teatro, 'ocupacion' => $ocupacion,
'ex_alumno' => $ex_alumno, 'intereses'=>$intereses, 'estudios_formales'=> $estudios_formales, 'derivado_ministerio'=>$derivado_ministerio);
$student->insertStudent($student_user_array, $conn);
Hope someone can point me in the right direction.
Thanks in advance.
Sebastian
I try to insert some data with php and a stored procedure. The stored procedure works fine but only for the first row.
PHP:
$sql = "SELECT * FROM [importliste_TCSv3]";
$stmt = sqlsrv_query($conn, $sql);
if ($stmt === false ) {
die (print_r(sqlsrv_errors(), true));
}
while ($row = sqlsrv_fetch_array($stmt)) {
// print works fine without call proc
$query = "{call difInport(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)}";
$params = array("0gtp", $row["Kostenstelle"], $row["Vorname"], $row["Nachname"], $row["CI-Nummer"], $row["cmo_mon"], $row["Raum"], $row["Gebaeude"], $row["Bemerkung"], $row["Hardware"], $row["fmo_mon"], $row["Zubehoer"]);
$stmt = sqlsrv_query($conn, $query, $params);
if ($stmt === false) {
die (print_r(sqlsrv_errors(), true));
}
}
Stored Procedure:
ALTER proc [dbo].[difInport]
#mandant_id varchar(50),
#kostenstelle varchar(50),
#vorname varchar(50),
#nachname varchar(50),
#ci_nummer int,
#anzahl_monitore_old int,
#raum varchar(50),
#gebäude varchar(50),
#bemerkung text,
#hardware_typ varchar(50),
#anzahl_monitore_new varchar(50),
#zubehör text
as
BEGIN
SET NOCOUNT ON;
DECLARE
#latestPersonID int,
#latestCmoID int,
#latestFmoID int
INSERT INTO [RC.Persons] (kostenstelle, vorname, nachname) VALUES (#kostenstelle, #vorname, #nachname);
SET #latestPersonID = (SELECT SCOPE_IDENTITY())
INSERT INTO [RC.CMO] (ci_nummer, anzahl_monitore, raum, gebäude, bemerkung) values (#ci_nummer, #anzahl_monitore_old, #raum, #gebäude, #bemerkung);
SET #latestCmoID = (SELECT SCOPE_IDENTITY())
INSERT INTO [RC.FMO] (hardware_typ, anzahl_monitore, zubehör) values (#hardware_typ, #anzahl_monitore_new, #zubehör);
SET #latestFmoID = (SELECT SCOPE_IDENTITY())
INSERT INTO [RC.Persons_RC.CMO] (cmo_id, person_id) VALUES (#latestCmoID, #latestPersonID);
INSERT INTO [RC.Persons_RC.FMO] (fmo_id, person_id) VALUES (#latestFmoID, #latestPersonID);
INSERT INTO [RC.Persons_RC.Mandant] (person_id, mandant_id) VALUES (#latestPersonID, #mandant_id);
END
I read this question: Call mysql PROCEDURE inside while loop works only first time
but I dont give any result set or is the set declaration with a select the result problem?
You are overwriting your $stmt variable. Change the name of the variable you use in the while loop:
while ($row = sqlsrv_fetch_array($stmt)) {
// print works fine without call proc
$query = "{call difInport(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)}";
$params = array("0gtp", $row["Kostenstelle"], $row["Vorname"], $row["Nachname"], $row["CI-Nummer"], $row["cmo_mon"], $row["Raum"], $row["Gebaeude"], $row["Bemerkung"], $row["Hardware"], $row["fmo_mon"], $row["Zubehoer"]);
$stmt_proc = sqlsrv_query($conn, $query, $params);
if ($stmt_proc === false) {
die (print_r(sqlsrv_errors(), true));
}
}
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),
...