SQL call IF EXISTS - php

SOS! I am trying to build a simple search feature that either creates a new row with the search content or increments the amount of times that particular content has been searched if the row already exists. I tried doing a similar SQL call straight inside of phpMyAdmin but it gave me a #1064 error? ($_POST['search'] is the search content)
<?php
$con=mysqli_connect(...);
$result = mysqli_query($con,"IF EXISTS (SELECT * FROM search WHERE text='" . $_POST['search'] . "')
UPDATE search SET searches=searches+1 WHERE text='" . $_POST['search'] . "'
ELSE
INSERT INTO search (text, searches) VALUES ('" . $_POST['search'] . "', '1')");
echo $result;
?>

Make the "text" column of the "search" table a "unique key". Then you can use this query:
INSERT INTO search (text,searches) VALUES ({$searched_text},1)
ON DUPLICATE KEY UPDATE searches=searches+1;

At first you are doing very wrong thing in your sql.
Please for your sake and sake of application, never never let unfiltered input into your sql query. This can lead to SQL Injection and someone can easily highjack your db.
So, lets fix this first:
$search = mysql_real_escape_string($_POST['search']);
Now when we have fixed it, lets try to do something with it.
I dont know if you have set a key for that table, but i suppose you do, so to escape your conditional try to simply do next thing:
insert into search (searches) values($search) on duplicate key update searches=searches+1
Please let me know how its going.
Kind regards
Vlad

Related

Where does SQL output values when OUTPUT clause is used in PHP string variable?

I am trying to retrieve an auto-incremented value that is created upon insertion. This ID value will be used in a SELECT statement later, so it would be nice to know what it is when I insert instead of writing another query. The problem is that I don't know where OUTPUT clause outputs it. The query is in the form of a PHP string variable.
I'm new to SQL and PHP, so I'm not really sure what to try. I just need some help understanding.
$query = "INSERT INTO Table1 (orderNumber, revisionNumber, creationDate...)"
. " OUTPUT Inserted.ID"
. " VALUES (blah, blah, blah...)";
execute_query($query);

Problems composing php sql query for postgresql table using LIKE

I am trying to retrieve data from a postgresql table therefore I have written a code. Now I am trying to compose the sql query but it isn't working. With my query I am trying to search in the table genes_searchterms and find all geneID matching where in the column types the value is equal to Pathway and where in the column searchterm the word aging is present.
Bellow the code to compose my query:
$sqlquery = "SELECT DISTINCT \"gene_id\" FROM \"" . \"genes_searchterms\" .
"\" WHERE ". "(\"types\" LIKE '". \"Pathway\" . "'
AND \"searchterm\" LIKE '" . \"%aging%\" ."') ";
Is there something wrong in the composition of my query? I use drupal and I don't get any errors when executing the code. I can't figure out where I got it wrong.
I use PostgreSQL 9.2.23.
In the fiddle is a part displayed of my table
https://www.db-fiddle.com/f/t7ThJ7Aen9XYzv2EtepinP/0
I've tried to get your Query up and running in db-fiddle. I also got no result, so I rechecked your condition and tried them separately. The error was in the "searchterm" condition.
You're using the ~* operator wich matches, according to the documentation, a Regex case insensitive. Since % isn't a pattern in Regex it matches "%aging%" literally. Only if you use LIKE in the query. % will be used as a wild card.
You could ether use a correct Regex or switch to LIKE.

PHP SQL UPDATE using variables

I currently have a script to upload photos, at the moment it uploads multiple images adding a new row to the mySQL database each time a new one is created. However I want the user to only be able to upload 1 image maximum.
I have therefore changed the register script to insert a row straight in to the database with a default image for each new user that registers.
The image upload script once logged in currently uses the below line to put the data in to the database
$sql2= "INSERT INTO `profile_photo` (`profile_id`,`title`,`size`,`type`,`reference`)
VALUES ('".$_SESSION['id']."','$title','$size','$type','$pic'); ";
However this is not how I want this to work; I believe the resolve would be to change this to an UPDATE row.
This is causing an issue when I change the line, I believe I have not quite grasped the concept of updating rows in mySQL.
Please can you advise?
$sql2=
"INSERT INTO `profile_photo` (`profile_id`,`title`,`size`,`type`,`reference`)
VALUES ('".$_SESSION['id']."','$title','$size','$type','$pic')
ON DUPLICATE KEY UPDATE title = VALUES(title), size = VALUES(size), type = VALUES(type), reference = VALUES(reference)";
Would solve this if the profile_id column got the index unique.
Behavior
This will INSERT all the data in a new row if the profile_id isn't already added. If it is, it will run an UPDATE instead.
However your code is pretty much begging for mysql injections. Do read up on this before it ruins your site.
Bobby tables, for your consideration.
Read up on DUPLICATE KEY here.
Assuming that profile_id is your unique key:
$sql2= "
INSERT INTO
`profile_photo` (`profile_id`,`title`,`size`,`type`,`reference`)
VALUES ('".$_SESSION['id']."','$title','$size','$type','$pic')
on duplicate key update set title='$title', size='$size', type='$type', reference='$reference'; ";
You can also use the replace into:
$sql2= "
Replace into
`profile_photo` (`profile_id`,`title`,`size`,`type`,`reference`)
VALUES ('".$_SESSION['id']."','$title','$size','$type','$pic')";
I think this question misses some information.
You might want to look into the REPLACE INTO statement
Or look up the MySQL UPDATE reference manual page
What you need is to execute the UPDATE sql statement:
$sql3= "UPDATE `profile_photo` SET `title`='" . mysql_real_escale_string($title) .
"', `size`='" . mysql_real_escape_string($size) .
"', `type`='" . mysql_real_escape_string($type) .
"', `reference`='" . mysql_real_escape_string($pic) .
"' WHERE `profile_id`=" . $_SESSION['id'];
Maybe the solution is Replace?

mysql query does not work on different files -php

i might be doing some idiot mistake, but i could not figure that out. i have some values coming from html and wanna insert into mysql db. problem is, the very same query does not work in regular php file (that includes other queries), but when i try on an independent php file, it does. here is a sample of the code:
$sql15="insert into body
(Article_ID, Article_Title)
values
('$article_id', '".$_POST['Article_Title']."') ";
mysql_query($sql15);
as i mentioned, the very same code works when i just copy this snippet to a new php file, and it works smoothly.. as you see, there are 20+ insert with the same php, because there are 25+ tables, but data is not much. first 14 query and following 7 queries do work by the way.
do you have any ideas?
There are some things to check and do.
Sanitize user input:
"('$article_id', '".mysql_real_escape_string($_POST['Article_Title'])."')";
You might also want to check if the value is what you expect.
Is your $article_id correct for column Article_ID?
Are your table and column names correct?
Check for errors:
$res = mysql_query($sql15);
if (!$res)
echo mysql_errno($link) . ": " . mysql_error($link);
Show us you complete query:
echo $sql15;
First of all i would suggest you to write your insert query like below
$sql15="insert into body SET Article_ID = '$article_id', Article_Title = '".$_POST['Article_Title']."'";
echo $sql15;
mysql_query($sql15);
so that each time when you add new column to database it would be easy for u to change insert query. echo your query and see it in browser. in it seems to o.k then copy it and paste it in SQL section under your phpmyadmin (see you are choosing proper database) and run it. if one row inserted successfully then your query is alright.
I hope this would help you a little.
$sql15="insert into body
(Article_ID, Article_Title)
values
('$article_id', '".$_POST['Article_Title']."') ";
mysql_query($sql15) or die(mysql_error());
use like this u will be get the error. then u will be find the issue
I think using mysql_real_escape_string may solve your problem.I also recommend you to store your form data in a string.
$article_title= mysql_real_escape_string($_POST['Article_Title']);
$sql15="insert into body
(Article_ID, Article_Title)
values
('$article_id', '$article_title') ";
mysql_query($sql15) or die(mysql_error());

Help me debug my SQL INSERT, please?

I am pulling back some data from the twitter query API, and parsing it through PHP like so:
$i =0;
foreach ($tweetArray->results as $tweet) {
$timeStamp = strtotime($tweet->created_at);
$tweetDateTime = date('m-d-Y H:m:s', $timeStamp);
if($i > 0){
$SQL .= ',';
}
$SQL .= "(". $tweet->id .",'" . $tweet->from_user ."','". addslashes($tweet->profile_image_url) . "','". addslashes($tweet->text). "','" . $tweetDateTime ."')";
$i++;
}
$SQL .= " ON DUPLICATE KEY UPDATE 1=1";
This leaves me with a SQL statement looking like this:
INSERT
INTO
tblTwitterSubmit (tweetId, twitterAuthor, authorAvatar, tweetText, tweetDateTime)
VALUES
(111,'name','http://url.com','a string of text','03-04-2011 13:03:09'),
(222,'anothername','http://url.com','another tweet','03-04-2011 12:03:51')
ON DUPLICATE KEY UPDATE 1=1;
I am unfortunately getting the following error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '1=1' at line 1.
Edit:
The 1=1 is supposed to not do anything. The tweets don't change, and so if I pull the same one back twice for any reason, nothing will happen, but it also won't throw a duplicate key error.
Re-edit:
The problem appears to have something to do with the key field I was using, which was the id of tweet as assigned by twitter.
I re-factored the code anyway, since it seemed pretty evident that what I had read in articles as a "really-good-idea" wasn't. I now included a PDO submit inside the for loop so I just make a bunch of submissions instead of one long sql string.
Hopefully this is better practice.
Leaving this open for a couple minutes hoping for some feedback if this is the way to do it or not.
The ON DUPLICATE KEY UPDATE requires a column name, something like this, assuming tweetId is the key column that's getting duplicates.
ON DUPLICATE KEY UPDATE tweetId=tweetId+1
Your 1=1 doesn't actually do anything.
Are you sure you're using the right syntax for on duplicate key update ?
Judging from it's manual's page, it seems you have to specify a column name, and not 1=1.
From what I understand, if you want to indicate "use the value from the values() clause when there's a duplicate", you should use something like this :
on duplicate key update your_col=values(your_col)
Quoting the relevant part :
You can use the VALUES(col_name)
function in the UPDATE clause to
refer to column values from the
INSERT portion of the INSERT ... ON
DUPLICATE KEY UPDATE statement.
In other words,
VALUES(col_name) in the ON
DUPLICATE KEY UPDATE clause refers to
the value of col_name that would be
inserted, had no duplicate-key
conflict occurred. This
function is especially useful in
multiple-row inserts.
Then, as a sidenote, you must escape your strings using the function that matches your API -- probably mysql_real_escape_string -- and not the generic addslashes, which doesn't know about the specificities of your database engine.
The problem appears to have something to do with the key field I was using, which was the id of tweet as assigned by twitter.
I re-factored the code anyway, since it seemed pretty evident that what I had read in articles as a "really-good-idea" wasn't. I now included a PDO submit inside the for loop so I just

Categories