I have a table log_Data where i log searched keyword that user enter. I am facing an issue that mysql query is inserting data multiple time. query is super simple INSERT INTO TABLE_NAME (id, keyword, date_adde) ... but if user enter some word... the query will insert it and after some seconds it will insert again and sometimes it insert same record for 4 5 times.
How can i limit and make this insertion more accurate so i can avoid duplication and get better and more accurate search reports.
EDIT
inside my controller i have:
if(isset($this->request->get['search']) && $this->request->get['search'] != ' '){
$search_log = array(
'keyword' => $this->request->get['search'],
'source' => '0', //0 for website and 1 for application
'total_result' => $product_total
);
$this->model_catalog_product->searchLog($search_log);
}
Inside my Model i have:
public function searchLog($data){
$query = $this->db->query("INSERT INTO search_log SET keyword = '" . $this->db->escape($data['keyword']) . "', record = '" . (int)$data['total_result'] . "', customer_id = '" . (int)$this->customer->getId() . "', source = '" . (int)$data['source'] . "', ip = '" . $this->db->escape($this->request->server['REMOTE_ADDR']) . "', date_added = NOW()");
}
attached an image where a customer searched for heel 'highlighted with black' is inserted 7 times with difference in few seconds... the customer originally searched for 1 time only... same as for other words as well...
first, check your code. Secound make a unquiq key:
md5 ( keyword + date + hour )
try to avoid duplicate in any form by adding session protection add hidden input call it doupleprotection it is value come from randomization like rand(1000, 10000000000) or md5(time()) then save this value in session like $_SESSION['doubleprotection']
Afer submit form and before inserting in database compare input value with $_SESSION['doubleprotection'] , if equal do query then give $_SESSION['doubleprotection'] new value from rand(1000, 10000000000)
if input value and $_SESSION['doubleprotection'] not equal stop query
Related
So I'm buidlign a website currently and there is a form connected to a database.
You can put some information in the form and it will send you an email and will put the information into the database.
So... I wanted it also ad a number into the database and auto count the number. This lead me thinking.... If I use max and just do +1 and insert that, Jobs done right!!.... Well no....
The code isn't working for me and I have no idea where to start...
This is al I made and when I do this I only get 1 as an answer.
$sql2 = "SELECT MAX(Nummer) FROM Leerling" ;
$sql3 = $sql2 + 1;
echo $sql3;
The insert statement is
"INSERT INTO Leerling(Nummer, Naam, Klas, Email, Bericht) VALUES ('" . $sql3 . "', '" .$naam. "', '" .$klas. "' , '" .$email. "', '" .$bericht. "');" ;
Which only inserts 0 into the database on the place where it says $sql2. I'm totaly clueless so any help is much needed help.
(Don't mind my English if it's not correct >.< I'm Dutch)
You should use MySQL AUTO_INCREMENT
Your column Nummer will increase its value every time you insert a new row and no need for calculate the MAX value to increase Nummer for the new row
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.
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.