-1

Is there any way to use a function in sql like this:

$title = clean_title($title);
"SELECT * FROM article WHERE title = $title"

to

$title = clean_title($title);
"SELECT * FROM article WHERE clean_title(title) = $title"

is ther any way?

user3932710
  • 125
  • 5
  • 1
    Yes http://dev.mysql.com/doc/refman/5.0/en/create-function.html but you might find processing in php simpler – Steve Sep 26 '14 at 12:34
  • No, you can't use a PHP function in a SQL statement. You can however create SQL Functions. – Daan Sep 26 '14 at 12:35
  • Can you say an exampe? thanks – user3932710 Sep 26 '14 at 12:35
  • 1
    please also be careful of sqli! (http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php?rq=1) –  Sep 26 '14 at 12:38
  • Can you say Google @user3932710? There are dozens upon dozens of examples of database function tutorials along with stored procedures tutorials available on the interwebs. ¯\_(ツ)_/¯ Where possible you should always have the database do the heavy lifting. – Jay Blanchard Sep 26 '14 at 12:58

2 Answers2

2

No.

Much in the same way that server-side code and client-side code are evaluated by entirely different platforms at entirely different times, the same is true with database code.

In this case, think of the database as the server and the PHP engine as the client.

Your PHP code is building SQL code which will later be evaluated by the database. In your PHP code you can invoke PHP functions to drive the creation of that SQL code. But once that SQL code gets to the database, PHP is no longer involved. The database engine can only evaluate SQL code, not PHP code.

There is a significant amount of logic that can be expressed in SQL code, including built-in functions or custom functions/procedures you can define (depending very much on the SQL engine being used). But that logic needs to be defined in SQL, not in PHP.

David
  • 208,112
  • 36
  • 198
  • 279
-2

Because you add the PHP tag, i assume it's an option to use PHP as well. In PHP you can use something like this:

$SQL = "SELECT * FROM article WHERE ".clean_title($title)." = $title"
S.Pols
  • 3,414
  • 2
  • 21
  • 42