Adding multiple rows to table with auto_increment column - php

Im trying to insert Data into a table named team. The table holds 4 colums. selection_id(primary key), player_name, position, and fixture id.
The selection_id has a value of auto_increment. Im adding the player names and position to the table. However the problem is, for each value it extracts out of the arrays, $playnames and $positions, the selection_id updates. Like this:
This is not what I want. 5 names should be stored (thus storing the team selected) in the table before the selection_id updates. OR for each new row, where a new team selection is made, the selection_id must be the same.
Im not sure how to get around this problem. I thought about doing another query after the data has been inserted to overwrite the selection_id and making all the rows (in this case) equal to 117. But im sure this is not the most effecient way to do it.
If anyone can give me a couple of pointers it would be greatly appreciated.
Code follows:
if ( isset($_POST['submit']) ) {
$player_ids = array_map('intval', $_REQUEST['players']);
var_dump($player_ids);
$query = 'SELECT `name`, `position`
FROM `player_info`
WHERE `player_id` IN (' . implode(',', $player_ids) . ')';
$return_names = mysql_query($query) or die(mysql_error());
while ( $row = mysql_fetch_assoc($return_names) ) {
$selected[] = $row['name'];
$position[] = $row['position'];
}
for ($i=0; sizeof($selected) > $i; $i++){
$sql = mysql_query("INSERT INTO `team`(`selection_id`,`player_position`,`player_name`) VALUES ('selection_id\"\"','$position[$i]','$selected[$i]')")
or die(mysql_error());
echo $selected[$i];
echo $position[$i];
echo'<br>';
}
var_dump($selected);
}

Related

Insert operation based on conditions in mysql php

I am stuck at a position where I need to do an insert operation for 'n' number of chapters on one submit button and through one insert query basically in a loop.
Now my question is if a user has passed exam for chapter number 3, then I don't want to insert record for chapter 3. Is this achievable? I've tried to solve this myself but couldn't find a way.
Here is my code:
for($i = 1; $i=5; $i++) {
$sql="INSERT INTO tbl_user_reattempt (ID,user_id,chapter_id,days_for _start,days_for_end,created) VALUES ('','$user_id','$chapter_id','$days_for_start','$days_for_end','$created')";
$result = mysql_query($sql);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
}
What modifications has to be done?
Create unique index for 2 fields: user_id and chapter_id.
Use ON DUPLICATE KEY UPDATE ID = ID in the end of your INSERT query.

how to work with array updates

I am looking for some inspiration from someone wiser than me with PHP/MySQL.
In have a database application, and in this instance there are two primary tables and one child table.
Primary Table 1 - Documents
Primary Table 2 - JobDesriptions
Child Table - LnkDocuments_JobDescriptions, which as the title suggests is a one to many relational table between the Document and Job Description Table. In my Documents Table I have a field which is a lookup of JobDescriptions and presents options as a checkbox, this field is called 'AppliesTo', because of the way the application works, the field stores the results as a string, eg "1,2,3,4,5) I have used the explode function to turn this into an array and then insert each record into the child table, as I prefer 1-2-many relationships. This is the code that I have, and it works.
$jdarray = explode(',',$values['AppliesTo']);
foreach($jdarray as $item)
{
$sql2 = "INSERT INTO LnkDocuments_JobDescriptions (DocumentFk, JobDescriptionFk)
values ('".$keys["DocumentPk"]."', '$item')"; CustomQuery($sql2);
}
The problem I now have is that if that table gets updated, I need to also update the child table, i have tried this code (but quickly realised that it is wrong):
$jdarray = explode(',',$values['AppliesTo']);
foreach($jdarray as $item)
{
$sql = "SELECT * FROM LnkDocuments_JobDescriptions WHERE DocumentFk='".$keys["DocumentPk"]."' AND JobDescriptionFk='$item'"; ;
$num_rows = mysql_num_rows(CustomQuery($sql));
if ($num_rows > 0) //Delete Record
{
$sql2 = "DELETE FROM LnkDocuments_JobDescriptions WHERE DocumentFk='".$keys["DocumentPk"]."' AND JobDescriptionFk='$item'"; CustomQuery($sql2);
echo "JD FK : ".$item." deleted";
}
else //Insert Record
{
$sql3 = "INSERT INTO LnkDocuments_JobDescriptions (DocumentFk, JobDescriptionFk)
values ('".$keys["DocumentPk"]."', '$item')"; CustomQuery($sql3);
echo "JD FK : ".$item." added";
}
}
It occured to me that I need to compare differences in the arrays, but havent got a clue how to do this, but this is what I need:
If I can get $oldarray and $new array to compare, for example
if in old array there were values 1,2,3,4 and in $newarray there were values 1,2,3,5, I want the code to loop through each value to determine if there is a change, e.g. if value exists in old and new array then do nothing, if value exists in old array but not new then delete, if value exists in new array but not old then insert.
I have also thought about just deleting all associated records and adding again, but think this is bad practice and will result in high number primary key, also it is worth noting that in my example there are only 5 options, this is just for testing, in reality there could be dozens.
Thanks in advance
If you are trying to optimize things I'm not sure that reading the values already present in the table and then deleting only those are not in the new version while inserting the missing records is the best way to go. In my opinion it would be much faster to just delete everything in one query, then insert all records in one query. Try something like this:
$item_list = implode( ',' , $jdarray );
$delete_query = "DELETE FROM LnkDocuments_JobDescriptions WHERE DocumentFk='".$keys["DocumentPk"]."' AND JobDescriptionFk IN ( $item_list )";
CustomQuery($delete_query);
$document_key = "'" . $keys["DocumentPk"] . "'";
$item_list_to_insert = "($document_key, " . implode( "), ($document_key, ", $jdarray ) . ")";
$insert_query = "INSERT INTO LnkDocuments_JobDescriptions (DocumentFk, JobDescriptionFk) VALUES " . $item_list_to_insert;
CustomQuery($insert_query);
Note: I didn't test this, there might some debugging needed.

Auto-increment in mysql query

I need to populate several columns of MYSQL table with data from arrays. So one column corresponds to one array. I have used the following code to fill just one column with data:
function addSystemDataTanks ($db, $tankNamesArray, $tankVolumesArray) {
$myArray = array();
$myString = implode ("'), ('",$myArray);
$statement = "replace into myTable (ID, NAME)";
$statement .= "values (' ";
$statement .= $myString;
$statement .= "')";
$result = mysqli_query($db, $statement);
if ($result) {
return true;
}
}
I need the ID field to be populated by auto-generated incremented numbers. But I need these rows to be replaced with new values next time this form is submitted. For the "replace" to work the ID has to be the same as previously used, otherwise it will just create new entries.
Also, is there a better way to input arrays as columns in MYSQL table, other than one by one, cause I need all row values to match to each other and the ID should be unique and start from 0 or 1 next time the form is submitted.
Thanks for any help.
If you just want the row ID to be incremental you're making life hard for yourself! When you create the table in MySQL, use AUTO_INCREMENT on the ID, then you can just enter a NULL value for the ID in your code:
CREATE TABLE blah (ID INT NOT NULL AUTO_INCREMENT, name VARCHAR(50), PRIMARY KEY(ID));
$sql = "INSERT INTO blah VALUES(NULL, 'Adam')";
"Adam" will now have an ID of 1 :)

How do i insert arrays into mysql using PHP?

I have a complex form that has 11 columns. As for rows they will vary from about 20 to 50 depending on number of students. I am capturing data via a php script as arrays. Each column produces an array. Example, from the form I have fname[], lname[], exam_no[] etc so when the form is submitted with say, 10 rows, I end up with 11 arrays each with 10 entries, which I pass through some php function to remove empty elements. The arrays are being generated with no issues.
I want to insert data from these arrays into mysql using a loop. Basically, lname array will have all first_name for the first name column, lname array will feed the last_name column of the db and so on.
I am just unable to even start constructing the MySQL query to insert the data, I am well conversant with the 'ordinary' insert where you have columns and values and you already know how many rows will insert, mostly one row per insert.
Is is even possible to populate a MySQL Database Table with an insert using a PHP loop and with this many number of columns and making it flexible to insert any number of rows as that will vary each time a user enters student data?
UPDATE
This is what I came up with. It works but NOT as desired!
Arrays are coming like $fname[], lname[] etc
Then I built the master array to be $master_array=array['$fname, $lname];
$sql = "INSERT INTO testing (date, fname, lname) VALUES ";
foreach($master_array as $subarray) {
$sql .= "(NOW( )";
echo 'A nested array: '.$subarray.'<br />';
foreach($subarray as $value) {
$sql .= ", '$value'";
echo 'A Name: '.$value.'<br />';
}
$sql.= "), ";
}
$sql = substr($sql,0,-2); //removes extraneous , at end.
echo $sql;
$result=mysqli_query($dbc, $sql)
or die('Query Failed!');
?>
Since my query involves conactinating small pieces of code, I was printing it after its built to see what is to be inserted. It looked like so;
INSERT INTO table (date, fname, lname) VALUES (NOW( ), 'Andrew', 'Alex'), (NOW( ), 'Peterson', 'Marlon')
As I suspected, it inserts all first names in the first row, and all last names in the second row. The desired result is to insert first names in the first-name column and second names in the second name column. So now I need a way to insert all elements of one array into a single column and then move to the second array and insert it in the next column. That sounds complex, and I wonder if it's doable! Let me be educated by the masters of the php language as I am an intermediate or may be brand new newbie!
Isn't it better to group the information by student?
Example:
<form...>
<? foreach ($students as $id => $info) : ?>
<input type="text" name="fname;<=$id;?>" value="<?=$info['fname'];?>" />
<input type="text" name="lname;<=$id;?>" value="<?=$info['lname'];?>" />
etc
<? endforeach ?>
</form>
(I'm using PHP short tags here)
Then, when you process the form:
$update = array();
foreach ($_POST as $key => $value) {
// key will look like: fname;1, fname;2, etc
// so, split it on the ; sign to separate the field name from the student's id
$data = explode(';',$key);
// result:
// $data[0] = fname, lname, etc
// $data[1] = 1, 2, etc
// you can add some checks to make sure that this field is valid
// and that the id is in fact a valid id (number, > 0, etc)
// sanitize data (however you want, just an example)
$value = mysql_real_escape_string(trim($value));
// now add it to the update array, grouped by student id
$update[$data[1]][$data[0]] = $value;
// result:
// $update[1]['fname'] = 'First name student 1';
// $update[1]['lname'] = 'Last name student 1';
// $update[2]['fname'] = 'First name student 2';
// $update[2]['lname'] = 'Last name student 2';
// etc
}
After that, go through the update array:
foreach ($update as $id => $info) {
$sql = "UPDATE students
SET fname = '".$info['fname']."', lname = '".$info['lname']."'
WHERE id = $id";
mysql_query($sql);
}

How do I get all the ids of the row created by one multiple row insert statement

I'm new to php. So, please forgive me if this seems like a dumb question.
Say i have a MySQL insert statement insert into table (a,b) values (1,2),(3,4),(5,6). table 'table' has a auto increment field called 'id'.
how can I retrieve all the ids created by the insert statement above?
It will be great if i get an example that uses mysqli.
You can't. I would suggest that you maintain your own ids (using guid or your own auto-increment table) and use it when you insert into the table.
But it's possible to get the auto-increment value for the last inserted using LAST_INSERT_ID():
http://dev.mysql.com/doc/refman/5.0/en/getting-unique-id.html
AngeDeLaMort's answer is almost right. Certainly, the most appropriate way to deal with the problem is to insert one row at a time and poll the insert_id or generate the sequence elsewhere (which has additional benefits in terms of scalability).
I'd advise strongly against trying to determine the last insert_id and comparing this the most recent insert_id after the insert - there's just too may ways this will fail.
But...an alternative approach would be:
....
"INSERT INTO destn (id, data, other, trans_ref)
SELECT id, data, other, connection_id() FROM source";
....
"SELECT id FROM destn WHERE trans_ref=connection_id()";
....
"UPDATE destn SET trans_ref=NULL where trans_ref=connection_id()";
The second query will return the ids generated (note that this assumes that you use the same connection for all 3 queries). The third query is necessary because connection ids to go back into the pool when you disconnect (i.e. are reused).
C.
In some cases, if you have another identifier of sort such as a UserID, you could filter your query by UniqueID's greater than or equal to mysql_insert_id(), limit by the number of affected rows and only display those by the user. This would really only work inside of a transaction.
$SQL = "INSERT INTO Table
(UserID, Data)
VALUES
(1,'Foo'),
(1,'Bar'),
(1,'FooBar')";
$Result = mysql_query($SQL);
$LastID = mysql_insert_id();
$RowsAffected = mysql_affected_rows();
$IDSQL = "SELECT RecordID
FROM Table
WHERE UserID = 1
AND RecordID >= '$LastID'
LIMIT '$RowsAffected'";
$IDResult = mysql_query($IDSQL);
as a follow up to AngeDeLaMort:
You could seperate your inserts and do it something like this:
$data = array (
array(1,2),
array(3,4),
array(5,6)
);
$ids = array();
foreach ($data as $item) {
$sql = 'insert into table (a,b) values ('.$item[0].','.$item[1].')';
mysql_query ($sql);
$id[] = mysql_insert_id();
}
Now all your new id's are in the $id array.
Maybe I can do this
$insert = "insert into table (a,b) values (1,2),(3,4),(5,6)";
$mysqli->query($insert);
$rows_to_be_inserted=3;
$inserted_id = $mysqli->insert_id // gives me the id of the first row in my list
$last_row_id = ($inserted_id+$rows_to_be_inserted)-1;
$mysql->query("select * from table where id between $inserted_id and $last_row_id");
what to you guys say?

Categories