I have a PHP script search script that logs every query made in a MySQL database. Currently, if the same terms are searched more than once, a duplicate of the query will be added to the database. How can I make it so when a term is already in the database +1 is added to a column titled value?
My PHP code is:
<?php
$database=mysql_connect("localhost","username","password");
mysql_select_db("database",$database);
$query=$_GET['q'];
logQuery($query);
function logQuery($query){
$query="insert into queries (query) values ('$query')";
mysql_query($query);
}
?>
First, create a unique index on the
queryfield using:Then, alter your
INSERTquery to update thevaluefield when a duplicatequeryis found (it will hit thequery_idxindex):Take a look at the documentation for
INSERT ... ON DUPLICATE KEY UPDATEfor more details about this.Also, don’t forget to use
mysql_real_escape_string($query)instead of simply using$query, because if you don’t escape the string and the$queryvariable contains, for example,'characters, it will corrupt yourINSERTquery.