AlanPHP
AlanPHP

Reputation: 188

Use a PHP function on MySql Column

I have 4 columns in my database. Atk,Str,Dex,and Con. Each being INT and then I have a PHP function get_level that takes those 4 columns and determines the correct level for them. I'm trying to select all users in a given range based on these "levels". The get_combat function takes those 4 values and finds the users combat level. This is what I have, which doesn't work.

<?PHP 
$query = "SELECT get_level(attack) as atk,
    get_level(strength) as str,
    get_level(dexterity) as dex,
    get_level(constitution) as con,
    get_combat(atk,str,dex,con) as level 
    FROM `users` 
    WHERE level > 5 AND level < 10"; 
?>

Is there a way to do this?

Upvotes: 1

Views: 205

Answers (2)

Wouter J
Wouter J

Reputation: 41934

I think you can't do something like this in SQL. After executing the query you can use the functions. Assuming you are using the old mysql_* functions:

<?php
$result = mysql_query($query);
$newResults = array();
$i = 0;

while( $row = mysql_fetch_assoc($result) ) {
  $newResults[$i]['atk'] = get_level($row['attack']);
  $newResults[$i]['strength'] = get_level($row['strength']);
  /** ect. **/
  $newResults[$i]['level'] = get_combat($newResults['atk'],$newResults['str'],$newResults['dex'],$newResults['con']);
}

Upvotes: 1

ThiefMaster
ThiefMaster

Reputation: 318498

What you are trying to do is impossible. MySQL doesn't even know what PHP is or which language is talking to it.

Why not fetch the values and call your function on in in the loop where you iterate over the results?

Depending on how complex the function is you could also create a stored procedure in your database. You cannot write PHP code in that function though.

Upvotes: 3

Related Questions