I have this current SQLite table:
CREATE TABLE Goal (
id INTEGER PRIMARY KEY,
Name CHAR(32) NOT NULL,
Image CHAR(256),
Target INTEGER NOT NULL,
Priority CHAR(32) NOT NULL
);
And am trying to create an integer id via PHP as follows:
$query = 'INSERT OR IGNORE INTO Goal (Name, Image, Target, Priority) VALUES'; // Query to insert goal-related info into Goal table
$query .= "('" . $name . "', '" . $image . "', '" . $target . "', '" . $priority . "');";
$addGoalDB -> makeQuery( $query );
$query = 'SELECT last_insert_rowid()';
$result = $addGoalDB -> makeQuery( $query );
$id = $result -> fetchArray(SQLITE3_ASSOC);
$id = $id['id'];
$query = 'INSERT OR IGNORE INTO Users_Goal (Email, id) VALUES';
$query .= "('" . $_SESSION['username'] . "', '" . $id . "');";
$addGoalDB -> makeQuery( $query );
But keep getting an undefined index error with
$id = $id['id'];
I am assuming the query is wrong but cannot find where my problem is. This link: http://alvinalexander.com/android/sqlite-autoincrement-insert-value-primary-key makes it look straightforward but does not work with my code. I would greatly appreciate any help with this.
You are trying to read a column named "id". But columns are named after what you have written in the SELECT clause, so the actual column name is something like last_insert_rowid().
Give the column a proper name:
$query = 'SELECT last_insert_rowid() AS id';
Related
I must to send an INSERT query to MySQL database, assuming all the variables are correctly setted, I'm using this code:
$check_alrd_sent = $mysqli -> query("SELECT * FROM reviews WHERE id_prod =" . $id_prod . " AND id_user = " . $current_usr . " LIMIT 1");
$check = mysqli_fetch_all($check_alrd_sent);
if ($check != NULL) {
$check_err = 1;
} else {
$ins_rev = $mysqli -> query("INSERT INTO `reviews` (`ID` ,`ID_prod` ,`ID_user` ,`review` ,`stars`) VALUES (NULL , " . $id_prod .", " . $current_usr . ", " . $review . ", " . $rating . ");");
$ins_result = 1;
}
mysqli_free_result($check_alrd_sent);
The $ins_result variable is correcly set as result, as I can see using var_dump() but now rows are insert in database.
The strange thing is that if I call the MySQL error log can clearly see that the insert is sent to the database correctly as:
42 Query INSERT INTO `reviews` (`ID` ,`ID_prod` ,`ID_user` ,`review` ,`stars`) VALUES (NULL , 11, 1, asd, 4)
But it doesn't appear in the table.
Any suggestions? Thanks
You have two issues in your INSERT Statement:
Value of review column is a string so you need to use quotes around review VALUE.
I think ID is an AUTO INCREMENT NOT NULL field. So no need to use in INSERT Query.
Modified query:
INSERT INTO `reviews`
( `ID_prod`, `ID_user` ,`review` ,`stars`)
VALUES (11, 1, "asd", 4)
varchar fields must be in 2 quota, so review field must be in 2 ':
$ins_rev = $mysqli -> query("INSERT INTO `reviews` (`ID` ,`ID_prod` ,`ID_user`
,`review` ,`stars`) VALUES (NULL , '" . $id_prod ."', ' " . $current_usr . "', '" .
$review . "', '" . $rating . "');");
In your output, "asd" is not in single quotes. That would be invalid SQL. Should also think about converting to non-deprecated SQL functions such as PDO.
I am developing a classroom website.
There is a form to insert student profile/data into the database table student.
This site has 5 class groups, IDs as id= 1, 2, 3, 4, 5.
Inserting data to database table succeeds.
But I have a question: Each student must be under classroom 1 and 2, so when we insert data I need the database to automatically create two database results for each times, both results all field are same data except classgroup_id, i mean one result must classgroup_id=1 and second result must be classgroup_id=2, i need mysql automatically generated this for when add each student... any idea.?
this is my table structure
student_id (int) AI
name
email
classgroup_id (default value=1)
user_id
this is my php code for insert data to table
$this->db->query("INSERT INTO " . DB_PREFIX . "student SET user_id = '" . (int)$this->user->getId() . "', name = '" . $this->db->escape($data['name']) . "', email = '" . $this->db->escape($data['email']) . "'");
thanks... i have only a medium level php knowledge
ClassGroups are in table or just static numbers?
If they are just static numbers, then i think simpliest way is to do another insert with duplicated data. For example for both rows should be:
$this->db->query("INSERT INTO " . DB_PREFIX . "student SET user_id = '" . (int)$this->user->getId() . "', name = '" . $this->db->escape($data['name']) . "', email = '" . $this->db->escape($data['email']) . "'");
$this->db->query("INSERT INTO " . DB_PREFIX . "student SET user_id = '" . (int)$this->user->getId() . "', name = '" . $this->db->escape($data['name']) . "', email = '" . $this->db->escape($data['email']) . "', classgroup_id =2");
If they are in some table, then you can do insert with one insert(code will be shorter) but with different insert syntax then yours. For example your ClassGroup table is just ClassGroups:
$this->db->query("INSERT INTO " . DB_PREFIX . "student (user_id, name, email, ClassGroup_id)
select " . (int)$this->user->getId() . ", '" . $this->db->escape($data['name']) . "', '" . $this->db->escape($data['email']) . "',ClassGroup_id from ClassGroups where ClassGroup_id=1 or ClassGroup_id=2");
But i think it should be best if you do for each data(student, ClassGroup) different table and do relation table for them, it will not duplicate data and table student will be faster if you gather data from it by primary AI key and not by varchar type column name.
You don't need PHP to do this... Pure SQL pseudosolution:
INSERT INTO student (student_id name, email) SELECT name, email from student where classgroup_id = ?
If you construct a fiddle and leave a comment as to where to find said fiddle, I'd be happy to tweak the query for your specific needs.
In order to avoid duplicate entries for students, you can make another table in which you link the students to their classes.
For example:
Students
student_id (primary key)
name
email
user_id (if still needed...)
Classgroups
classgroup_id (primary key)
classgroup_name
StudentsPerClassgroup
student_id (foreign key)
classgroup_id (foreign key)
You have to keep the record in temporary table first and then do the operations .. try it
//get last insertId
$last_insert_id = $this->db->insert_id();
$new_id = $last_insert_id +1;
$query = "CREATE TEMPORARY TABLE tmp SELECT * FROM yourtable WHERE your_primary_key = $last_insert_id;
UPDATE tmp SET your_primary_key= $new_id,classgroup_id = 2 WHERE your_primary_key = $last_insert_id;
INSERT INTO yourTable SELECT * FROM tmp WHERE your_primary_key = new_id";
$this->db->query($query);
Hope you get some idea
I need to perform multiple queries on a database table, basically my PHP script has to:
insert into the table a new user storing his id, name, email;
get the id of the newly created user using his email;
associate the id with a key and a timestamp.
I am pretty new to PDO and my problem is I can't figure out a smart way to get that one id without using a foreach, so basically my code is:
$query = "INSERT INTO users(name, surname, email) VALUES('" . $name . "', '" . $surname . "', '" . $email . "')";
$this->dbconn->query($query);
$query = "SELECT id FROM users WHERE email='" . $email . "'";
$data = $this->dbconn->query($query);
$id = $data['id'];
$query = "INSERT INTO users(name, surname, email) VALUES('" . $name . "', '" . $surname . "', '" . $email . "')";
$this->dbconn->query($query);
$id = $this->dbconn->lastInsertId();
I have part of the code below:
while($array = $result->fetch_assoc() ){
$second_query = "INSERT INTO".TBL_USERSDONTPAY."VALUES ($array[\"username\"], $array[\"password\"], '0',$array[\"userid|\"], )";
$second_result = $database->query($second_query);
}
The query doesn't seem to work. Any clues? I think it's a problem with the quotes or something. How can actually pass array elements?
here is my whole code i want to move one row to another table
$q = "SELECT * FROM ".TBL_USERS." WHERE username = '$subuser'";
$result = $database->query($q);
if($result && $result->num_rows == 1){
while($array = $result->fetch_assoc() ){
$second_query = "INSERT INTO" . TBL_USERSDONTPAY . "VALUES ('" . $array['username'] . "', '" . $array['password'] . "', '0', '" . $array['userid'] ."')";
$second_result = $database->query($second_query);
if($second_result){
// it worked!
$q = "DELETE FROM ".TBL_USERS." WHERE username = '$subuser'";
$database->query($q);
}
}
}
You need to clean that query up and remove the final comma.
$second_query = "INSERT INTO " . TBL_USERSDONTPAY . " VALUES ('" . $array['username'] . "', '" . $array['password'] . "', '0', '" . $array['userid'] . "')";
I see several issues with your query code
escaping of the array indexes in your string:
you can either end the string and concatenate the parts together:
$second_query = "INSERT INTO " . TBL_USERSDONTPAY .
" VALUES ('" . $array['username'] . "', '" . $array['password'] . "', '0', '" . $array['userid'] . "')";
or use the {$var} syntax:
$second_query = "INSERT INTO " . TBL_USERSDONTPAY .
" VALUES ('{$array['username']}', '{$array['password']}', '0', '{$array['userid']}')";
missing spaces (see example code above .. you were missing the spaces before and after the table name)
missing field names. your query may work without if you specify all fields in the right order, but will fail misteriously when you alter the table later (e.g. add a field to the table)
$second_query = "INSERT INTO " . TBL_USERSDONTPAY .
" (username, password, foo, user_id)".
" VALUES ('{$array['username']}', '{$array['password']}', '0', '{$array['userid']}')";
please note you should actually insert the correct field names in the second line of my example above. You can find more information on this in the MySQL docs for INSERT
My part_no column has the following format: 000-00000-00 for all records.
I need to extract the five middle characters from part_no and place it in the core column when I create the record.
I can't get my script to work.
I'm not getting any errors. Just not working.
$order = "INSERT INTO cartons_added (add_time, type, part_no, add_type, add_qty, add_ref, add_by, add_notes)
VALUES
('$date',
'$_POST[type]',
'$_POST[part_no]',
'$_POST[add_type]',
'$_POST[add_qty]',
'$_POST[add_ref]',
'$_POST[add_by]',
'$_POST[add_notes]')";
$result = mysql_query($order);
$query2 = "select part_no from cartons_current";
$sel = mysql_query($query2);
$res = mysql_result($sel);
while($row = mysql_fetch_row($res)) {
$core_digits = split('-',$row[0]);
$core =$core_digits[1];
$query3 = "insert into cartons_current(core) values($core)";
$sel2 = mysql_query($query3);
}
You can update your cartons_current table based on your cartons_added table with something like:
INSERT INTO cartons_current(core)
SELECT SUBSTR(part_no, 5, 5) FROM cartons_added
You will probably want to limit that with a WHERE clause or maybe deal with what happens when this value is already in cartons_current (use either INSERT IGNORE or ON DUPLICATE KEY UPDATE)
You are right, the script has no error.
I think the problem is on your SQL that made you can't insert a new row, specifically on the table structure. Maybe you defined a PRIMARY KEY without AUTO_INCREMENT, defined a INDEX or UNIQUE key that is not the core key or there have some other key that did not have default value. Remember that you can't insert a row without defining all required field.
You script is selecting all part_no and for every part_no you are inserting a new row in the same table, so maybe there is the problem.
I think what you want is update every result to add they core value, you can do that with UPDATE as this code:
function getValue($value) {
return "'" . trim(mysql_real_escape_string($value)) . "'";
}
mysql_query('INSERT INTO `cartons_added` (`add_time`, `type`, `part_no`, `add_type`, `add_qty`, `add_ref`, `add_by`, `add_notes`)
VALUES (' .
getValue($date) . ', ' .
getValue($_POST[type]) . ', ' .
getValue($_POST[part_no]) . ', ' .
getValue($_POST[add_type]) . ', ' .
getValue($_POST[add_qty]) . ', ' .
getValue($_POST[add_ref]) . ', ' .
getValue($_POST[add_by]) . ', ' .
getValue($_POST[add_notes]) .
')');
$partNoQuery = mysql_query('SELECT `part_no` FROM `cartons_current`');
while($partNoResult = mysql_fetch_assoc($partNoQuery)) {
list($prefix, $core, $suffix) = explode('-', $partNoResult['part_no']);
mysql_query('UPDATE cartons_current SET `core` = \'' . $core . '\' WHERE `part_no` = \'' . $partNoResult['part_no'] . '\'');
}
I added getValue function to escape posted data to prevent SQL injection.
Try removing this
$res = mysql_result($sel);
And change your while to reference the main query resource
while($row = mysql_fetch_row($sel)) {
I don't understand your logic with your tables though. You're inserting data into the cartons_added table but then you're selecting from cartons_current?
Also, split is deprecated as of PHP 5.3.0
You said five middle "characters", so I'd add quotes around your variable like so:
$query3 = "insert into cartons_current(core) values('$core')";
(Also, there's only about a gazillion answers on SO about SQL injection, and using pdo)
INSERT INTO cartons_current(core)
SELECT
substr(part_no,position('-' IN part_no)+1,position('-' IN substr(part_no,position('-' IN part_no)+1))-1)
FROM cartons_added;