I'm trying to insert multiple different words into a database if they are not already in the database. I'm getting the text from a textfield where the user inputs multiple categories. I want to split the text being passed from this textfield by comma and insert it individually into the database if it's not already in it. Currently nothing is being input into the database. Thanks in advance for your help!
Here is my code to split the textfield data and insert into the database:
$category = trim($_POST['category']);
$cat2 = explode(',', $category);
foreach ($cat2 as $new_interest)
{
$insert_user_interests = sprintf("INSERT INTO interests IF NOT EXISTS name = '". $new_interest . "'" .
"(name) " .
"VALUES ('%s');",
mysql_real_escape_string($new_interest));
mysql_query($insert_user_interests);
}
This is your insert statement:
INSERT INTO interests IF NOT EXISTS name = '". $new_interest . "'" .
"(name) " .
"VALUES ('%s')
As far as I'm aware, this is not valid insert syntax. (The documentation is here.) I think you are confusing it with the create table syntax. Instead, use ignore and something like:
INSERT IGNORE INTO interests(name) VALUES(". $new_interest . "')"
EDIT:
Right, if you don't want to insert duplicates, then create a unique index on name:
create index unique interests_name on interests(name);
Then the above query will do what you want.
Related
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.
Hi there i am trying to insert an array of information into fields in a database through the selection of checkboxes i have that sorted and inserting fine but i am able to insert duplicates which is no good i am using the following to insert the items
$list = $_POST['sub'];
// for each loop to insert each value into the database with the selected users informtion
foreach ($list as $value) {
// The query to run
$listQuery='INSERT INTO tbl_list (`userId`, `subId`) VALUES (\'' . $id . '\', \'' . $value . '\')';
// Run the query
$objects->query($listQuery);
}
You should add a unique key for (userId, subId):
ALTER TABLE tbl_list ADD UNIQUE(`userId`, `subId`)
Then, you should use either INSERT IGNORE or REPLACE INTO to avoid errors during insert.
You can use Insert Ignore instead of Insert in mysql query
For stop duplicate entries into database you have do this thing.follow step by step
> 1.set a unique key on the table
after Complete create unique key you have to decide what you want to do when there's a duplicate
> 2. ignore it
> 3.Overwrite the previously entered record
> Update some counter
You need to do two things
first make your userId primary key and then try this query
$listQuery='INSERT INTO tbl_list (userId, subId) VALUES (\'' . $id . '\', \'' . $value . '\') on duplicate key update userId = LAST_INSERT_ID()';
How could i do a query with php and mysqli, to remove an entire table and then add new I have a form where data is received, but before adding the new data, I want to remove all data from table.
$oConni is my connection string
$cSQLt = "TRUNCATE TABLE approved";
$cSQLi = "INSERT INTO approved (ID_STUDENT, YEAR, APPROVED)
VALUES (
'" . $_POST['NSTUDENT'] . "',
'" . $_POST['YEAR'] . "',
'YES'
)";
$oConni->query($cSQLt);
$oConni->query($cSQLi);
You can remove everything from a table with MySQL by issuing a TRUNCATE statement:
TRUNCATE TABLE approved;
.. which usually is the same as
DELETE FROM approved;
.. but there are a few small differences, which you can read about in the documentation.
In the code you've pasted, please use prepared statements to avoid a sql injection attack. Never use unfiltered POST-data directly in a query!
If you want to do this as a trigger, we'll need to know a bit more about your data handling. Issuing a TRUNCATE before a INSERT will usually lead to only one row being available in the table, which seems like a weird use case for actually using a table.
You could use TRUNCATE TABLE and then your next query:
$cSQLt = "TRUNCATE TABLE CALIFICA_APTO";
$cSQLi = "INSERT INTO approved (ID_STUDENT, YEAR, APPROVED)
VALUES (
'" . $_POST['NSTUDENT'] . "',
'" . $_POST['YEAR'] . "',
'YES'
)";
$Connect->query($cSQLt);
$Connect->query($cSQLi);
If your looking to remove all of the data from a table you should use TRUNCATE:
TRUNCATE TABLE approved
Then you can do your SQL statement.
NOTE: This will delete all data from the table, so be careful! Also, your database user must have the ability to truncate tables.
I am using PHPMaker. It has the ability to do custom things with it's code.... This is from the documentation: "This event will be called after updating a record. The arguments of the event are the arrays of the old and new record updated. Note: This event is a table class member."
This is the code to be edited for this event:
// Row Updated event
function Row_Updated($rsold, &$rsnew) {
//echo "Row Updated";
}
When I edit a record I want the old data to be inserted into another table for historical purposes. The "historical" table will have the same fields plus an ID field that will auto increment and will be the primary key. So I'll have a full history of changes available.
Table layout is like this;
(Information)
ip (primary key), status, hostname, last_scanned, mac, ManualHost, Reservation
They have some sample code to insert a record but I'm no guru and don't know the MySQL/PHP lingo to get data out of the $rsold array.
// Insert record
// NOTE: Modify your SQL here, replace the table name, field name and field values
$sInsertSql = "INSERT INTO MyTable (Field1, Field2, Field3) VALUES (Value1, Value2, Value3)";
$GLOBALS["conn"]->Execute($sInsertSql);
Can someone help/get me in the right direction?
Assuming they are returning the row you can simply fetch the fields as if it's an array. Just use the variable and mention the field between square brackets, e.g.: $row['field'].
$sInsertSql = "INSERT INTO information (status, hostname, last_scanned, mac, ManualHost, Reservation)
VALUES ('" . $rsold['status'] . "', '" . $rsold['hostname'] . "', '" . $rsold['last_scanned'] . "', '" . $rsold['mac'] . "',
'" . $rsold['ManualHost'] . "',
'". $rsold['Reservation'] . "')";
$GLOBALS["conn"]->Execute($sInsertSql);
As for your question about "all the spacing and periods" I do this to keep my variables separated from the String. A good (bad) example to show you a possible reason is the following:
$juice = "apple";
echo "He drank some $juice juice.";
//Now imagine I want to write "He drank some juice made of apples
echo "He drank some juice made of $juices.";
//^^^ Is invalid. "s" is a valid character for a variable name, but the variable is $juice.
//So it'd be better to
echo "He drank some juice made of " . $juice . "s.";
I have a form which to insert data into a database. This form takes the content of the fields, and then displays the result page showing the entered information in context. There is a link on this page to edit the user info, which go back to the previous form. Obviously, I do not want duplicate records inserted. Is there an easy way to use an update statement if a record already exists? I am doing this with ajax and php.
Take a look at:
INSERT ... ON DUPLICATE: http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
REPLACE INTO: http://dev.mysql.com/doc/refman/5.0/en/replace.html
INSERT ... ON DUPLICATE will allow you to issue an UPDATE query when a UNIQUE INDEX or PRIMARY KEY is matched.
REPLACE works exactly the same, but if the row is found, the old row is deleted prior to inserting a new one. When using cascading deletes, this is especially something to take into account!
MySQL supports the addition of ON DUPLICATE KEY UPDATE to an INSERT statement, which should do what you want.
Assuming you have a field like 'username' or 'email', you could make use of that field to check if a record already exists, if it does, update it.
$res = mysql_query("SELECT primary_key FROM my_table WHERE `email` = '" . mysql_real_escape_string($email) . "'");
if($row = mysql_fetch_array($res))
{
// Record exists, update it
$q = "UPDATE my_table SET `username` = '" . mysql_real_escap_string($username) . "' WHERE primary_key = " . (int) $row['primary_key'];
}
else
{
// Record doesn't exist, insert
$q = "INSERT INTO my_table(username, email) VALUES('" . mysql_real_escape_string($username) . "', '" . mysql_real_escape_string($email) . "');";
}
In the above example I assume you have a primary key field that's an integer (primary_key).
You should consider using an ORM like http://www.ezpdo.net/blog/?p=2
Plain SQL in web applications should only be used if absolutely neccessary, alone for security reason, but also to avoid problems like yours.