I have a problem using sqlite_last_insert_rowid in PHP.
CODE:
$database = new SQLiteDatabase('example.db');
$sql_1 = "INSERT INTO ex1(test1, test2) VALUES ('$test1','$test2')";
$database->queryExec($sql_1);
$ex1_ID = sqlite_last_insert_rowid($database);
$sql_2 = "INSERT INTO ex2 (ex1_ID, fname, lname) values ('$ex1_ID','$fname','$lname');";
$database->queryExec($sql);
I want to store ID from ex1 table to table ex2 in ex1_ID
CREATE TABLE ex1 (
ID INTEGER PRIMARY KEY,
test1 LONGTEXT,
test2 LONGTEXT
);
CREATE TABLE ex2 (
ID INTEGER PRIMARY KEY,
ex1_ID INTEGER,
fname LONGTEXT,
lname LONGTEXT,
FOREIGN KEY ( ex1_ID ) REFERENCES ex1 ( ID )
);
COMPLETE CODE:
$database = new SQLiteDatabase('example.db');
for ($i = 0; $i < 10; $i++) {
$test1 = "";
$test2 = "";
$lenght = rand(300, 400);
for ($x = 0; $x < $lenght; $x++) {
$test1 .= rand(0, 9);
$test2 .= rand(0, 9);
}
$sql_1 = "INSERT INTO ex1 (test1,test2) VALUES ('$test1','$test2')";
$database->queryExec($sql_1);
$ex1_ID = sqlite_last_insert_rowid($database);
for ($j = 0; $j < 3; $j++) {
for ($x = 0; $x < $lenght; $x++) {
$test1 .= rand(0, 9);
$test2 .= rand(0, 9);
}
$sql_2 = "INSERT INTO ex2 (ex1_ID, fname, lname) values ('$ex1_ID','$test1','$test2');";
$database->queryExec($sql_2);
}
}
I cant get the last ID from a ex1 table.
Please help!
UPDATED now that we have more information.
Since you use an object-model way to query your DB, did you try
$lastid = $database->lastInsertRowid();
?
Related
I'm currently making a graduation website for my school where grads are supposed to submit a comment as well as submit votes for a poll.
The database has 4 tables, one for the student information, one for questions, one for comments which has a foreign key referencing snum from students and one for the poll(called survey) which has 2 foreign keys, one referencing snum again and one referencing the question id.
This is the code my seniors left for me. What it's supposed to do is create blank rows in the comments and survey tables to be updated later. However what it actually does is send everything in the comment table twice (so if there were 300 students, I would end up with 600 rows in the comments table and 0 in the survey table)
I'm still quite new to MySQL and PHP and only learned it about a month ago. If anyone can help or suggest a better way of approaching this, it would be much appreciated.
$sql_query = "SELECT snum FROM students;";
$result = mysqli_query($link,$sql_query);
while ($list = mysqli_fetch_array($result)) {
$snum[] = $list['snum'];
}
$sql_query = "SELECT qid FROM questions WHERE want = 1;";
$result = mysqli_query($link,$sql_query);
while ($question_list = mysqli_fetch_array($result)) {
$qid[] = $list['qid'];
}
for ($i = 0; $i < count($snum); $i++)
{
$sql_query = "INSERT INTO comments (snum, comment) VALUES ('{$snum[$i]}' , NULL);";
$result = mysqli_query($link,$sql_query);
for ($a = 0; $a < count($qid); $a++) {
$sql_query = "INSERT INTO survey (snum, qid, male, female) VALUES ('{$snum[$i]}', {$qid[$a]}, NULL, NULL);";
$result = mysqli_query($link,$sql_query);
}
}
UPDATE 1:I think I found what the problem is. When I try to output $qid[$a], I get a null value. In the table, qid is a smallint unsigned, not null, auto_increment and is the primary key.
Try this code
<?php
$sql_query = "SELECT snum FROM students";
$result = mysql_query($link,$sql_query);
while ($list = mysql_fetch_array($result)) {
$snum[] = $list['snum'];
}
$sql_query = "SELECT qid FROM questions WHERE want = '1' ";
$result = mysql_query($link,$sql_query);
while ($question_list = mysql_fetch_array($result)) {
$qid[] = $list['qid'];
}
for ($i = 0; $i < count($snum); $i++){
$sql_query = "INSERT INTO comments (snum, comment) VALUES ('".$snum[$i]."' , '');";
$result = mysql_query($link,$sql_query);
for ($a = 0; $a < count($qid); $a++) {
$sql_query = "INSERT INTO survey (snum, qid, male, female) VALUES ('".$snum[$i]."','".$qid[$a]."', '', '');";
$result = mysql_query($link,$sql_query);
}
}
?>
This was solved by using mysqli_free_result($result) between the two select queries
$sql_query = "SELECT snum FROM students;";
$result = mysqli_query($link,$sql_query);
while ($list = mysqli_fetch_assoc($result))
{
$snum[] = $list['snum'];
}
mysqli_free_result($result);
$sql_query = "SELECT qid FROM questions WHERE want = 1;";
$result = mysqli_query($link,$sql_query);
while ($question_list = mysqli_fetch_assoc($result))
{
$qid[] = $list['qid'];
}
I have read many answers on stackoverflow, but I haven't find anything related my issue.
This is my table:
`id` char(11) NOT NULL,
`element` varchar(32) NOT NULL,
I need to use an autoincremented unique string id of 11 chars ( case sensitive if possible ) and numbers as youtube does:
youtube.com/watch?v=j5syKhDd64s
youtube.com/watch?v=YVkUvTmDf3Y
youtube.com/watch?v=8BcDeoKLsaY
...
How could I do this with mysql/php ?
You probably want something like hashids. Their page also links to alternative solutions.
If that doesn't fit the bill, please describe your problem in more detail.
one way to do it is to use this function
function generateRandomString($length = 11) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
and then pass $randomString result to your query to add in DB.
EDIT :
if OP is looking for the string like he mentioned (aaaaaaaaaaa, aaaaaaaaaab, aaaaaaaaaac, aaaaaaaaaad) i recommend you to check out Theory of Computation .
This is my code which I Autoincremented my unique id string field.
case "Add":
$itemno = $_POST['itemno'];
$qty = $_POST['qty'];
$unitprc = $_POST['unitprc'];
$amt = $_POST['amt'];
$coopmemid = $_SESSION['kiosk']['is_coopmemID_kiosk'];
$totamt = 0;
$totitm = count($itemno);
$a_empgroid = array();
for($x=0; $x<$totitm; $x++) {
$Addquery = "INSERT INTO tb_empgrocery (coopmemID , date_ordered, item_no, qty_ordered, unit_price, amount)
VALUES ('$coopmemid',(NOW()),'$itemno[$x]','$qty[$x]','$unitprc[$x]','$amt[$x]')";
$atecCoop->query($Addquery);
$totamt+=$amt[$x];
$inserted_id = $atecCoop->insert_id;
array_push($a_empgroid,$inserted_id);
}
$Savequery = "INSERT INTO tb_empgroc_master (order_status, date_ordered, total_items, total_amount) VALUES ('Pending', (NOW()), '$totitm', '$totamt')";
$atecCoop->query($Savequery);
$empgrocmstid = $atecCoop->insert_id;
$orderno = date('y-m-').str_pad($empgrocmstid, 10, "0", STR_PAD_LEFT);
$sql = "UPDATE tb_empgroc_master SET order_no='$orderno' WHERE empgrocmstID='$empgrocmstid'";
$atecCoop->query($sql);
foreach($a_empgroid as $empgrocid) {
$sql = "UPDATE tb_empgrocery SET order_no='$orderno' WHERE empgrocID='$empgrocid'";
$atecCoop->query($sql);
}
break;
As you can see the field oder_no is a unique id (varchar 25)
Hope this helps :)
I have a small problem with the request to the base of the PDO.
I want to insert or update fields in one request. I want insert a few records to DB, but if there are already 'file_name' fields with the selected name then just to update the other fields. Below paste my php code.
For example: I adding 5 records id_product (eg. 1) and various other fields.
Example fields recived from the $_post:
(id_product, alt, file_name, main_photo)
1, xxx, 1_1, 0;
1, xxx, 1_2, 0;
1, xxx, 1_3, 1;
my PHP code:
$query = "INSERT INTO product_image (id_product, alt, file_name, main_photo) VALUES ";
$part = array_fill(0, count($_POST['file_name']), "(?, ?, ?, ?)");
$query .= implode(",", $part);
$query .= " ON DUPLICATE KEY UPDATE alt=VALUES(alt), main_photo=VALUES(main_photo)";
$stmt = $this->_db->prepare($query);
$j = 1;
$im_null = 0;
for ($i = 0; $i < count($_POST['file_name']); $i++) {
$stmt->bindParam($j++, $_POST['id_product'], \PDO::PARAM_INT);
$stmt->bindParam($j++, $_POST['alt'][$i], \PDO::PARAM_STR);
$stmt->bindParam($j++, $profile->base64_to_jpeg($_POST['file_name'][$i], APP_ROOT . '/uploads/products/' . $_POST['id_product'] . '_' . $_POST['file_nr'][$i]), \PDO::PARAM_STR);
($_POST['main_photo'][$i] == 1) ? $stmt->bindParam($j++, $_POST['main_photo'][$i], \PDO::PARAM_INT) : $stmt->bindParam($j++, $im_null);
}
$stmt->execute();
In this query inserts works good, but doesn't update, which is the second part of the request.
Move $j = 1; inside loop as it is you keep on incrementing $j.
$im_null = 0;
for ($i = 0; $i < count($_POST['file_name']); $i++) {
$j = 1;
i have code like
$quota = 100;
$quotaperclass = 25;
for ($x = 0; $x <= $quota/$quotaperclass ; $x++) {
$sql = "INSERT INTO classroom (name) VALUES ('A')";
for ($y = 0; $y <= 25 ; $x++) {
$sql = "INSERT INTO classroomstudent (studen_id, class_id) VALUES ('', 'A')";
}
}
I want if quota per class 25, total quota div quota per class. in my case result is 4 and then automated create 4 class like A, B, C, D and then add every student to the class.
my question is.
how to change value name automated like
loop 1 is A
loop 2 is B
loop 3 is C
etc
and how to add every student into class automatically.
thanks
$range = range('A', 'Z');
$quota = 100;
$quotaperclass = 25;
for ($x = 0; $x <= $quota/$quotaperclass ; $x++) {
$sql = "INSERT INTO classroom (id, name) VALUES ('', '".$range[$x]."')";
}
Try this
$c = 'A';
for ($x = 0; $x <= $quota/$quotaperclass ; $x++) {
$sql = "INSERT INTO classroom (id, name) VALUES ('', '$c')";
$c++;
}
I have four arrays:
$qtys = $_POST['qty'];
$colours = $_POST['colour'];
$sizes = $_POST['size'];
$names = $_POST['name'];
I want these to go into a mysql table like so:
qty | colour | size | name
-------------------------------------------
$qtys[0] | $colour[0] | $size[0] | $name[0]
$qtys[1] | $colour[1] | $size[1] | $name[1]
I've tried various things, including this:
foreach($qtys as $value) {
$i = 0;
mysql_query("INSERT INTO table (qty,colour,size,name) VALUES ('$qtys[$i]','$colours[$i]','$sizes[$i]','$names[$i]')");
$i++;
}
...but to no avail. Can anyone suggest a different INSERT statement that will get the data in the table? Do I need to iterate in the loop? I'm sure $qtys as $value is incorrect but have tried so many things with no luck.
First of all, you are resetting the counter each iteration, put $i = 0 outside of the loop if you want to do it this way.
$i = 0;
foreach($qtys as $value) {
mysql_query("INSERT INTO table (qty,colour,size,name) VALUES ('$qtys[$i]','$colours[$i]','$sizes[$i]','$names[$i]')");
$i++;
}
A better (cleaner) way would be something like:
for ($i = 0; $i < $qtys.count(); $i++) {
mysql_query("INSERT INTO table (qty,colour,size,name) VALUES ('$qtys[$i]','$colours[$i]','$sizes[$i]','$names[$i]')");
}
Also, are you sure that the arrays are always the same length? Otherwise you risk getting a index out of bounds problem..
Simply use for loop will be ok, AND REMEMBER ESCAPE USER INPUT.
for($i =0, $count = count($qtys); $i < $count; $i++) {
mysql_query("INSERT INTO table (qty,colour,size,name) VALUES ('$qtys[$i]','$colours[$i]','$sizes[$i]','$names[$i]')");
}
$sql = "INSERT INTO table (qty,colour,size,name) VALUES ";
$inserts = array();
for($i=0 ; $i < count($qtys); $i++) {
$inserts[] = "('$qtys[$i]','$colours[$i]','$sizes[$i]','$names[$i]')";
}
$sql .= implode(',', $inserts);
mysql_query($sql);
No need to run query again and again.