SQL result to a php variable

Discussion in 'PHP' started by simstar, Jul 9, 2008.

  1. #1
    I have created a query which selects UserRating and Uservotes(the number of people who voted). I want to get the average rating for all users. So this will be UserRating Divided by UserVotes.

    I cannot work out how I can change the SQL results into php variables which I can then calculate this with.

    
    $UR = .$rows['UserRating'].;
    $UV = .$rows['UserVotes'].;
    $Overall = $UR/$UV;
    
    PHP:
    This is my attempt but it doesnt work, I simply dont know the code to say $phpvariable = field-found-in-SQL-query

    thanks in advance.
     
    simstar, Jul 9, 2008 IP
  2. Danltn

    Danltn Well-Known Member

    Messages:
    679
    Likes Received:
    36
    Best Answers:
    0
    Trophy Points:
    120
    #2
    I'm not sure how the rest of the code is structured, this would surely result in a parse error.

    
    $ur = $rows['UserRating'];
    $uv = $rows['UserVotes'];
    $overall = $ur/$uv;
    
    PHP:
    P.s. try var_dump()ing the result to see what it is made of!
     
    Danltn, Jul 9, 2008 IP
  3. simstar

    simstar Peon

    Messages:
    467
    Likes Received:
    4
    Best Answers:
    0
    Trophy Points:
    0
    #3
    It does result in a parse error. I was showing the code to represent what I was attempting.

    Basically what I was asking is how do you save a SQL result to a PHP variable.
     
    simstar, Jul 9, 2008 IP
  4. Danltn

    Danltn Well-Known Member

    Messages:
    679
    Likes Received:
    36
    Best Answers:
    0
    Trophy Points:
    120
    #4
    // $connection should equal a MySQL connection resource generated via mysql_connect or similar.
    // $query should be your SQL query
    
    if ( !($result = mysql_query($query, $connection)) ) throw new Exception( mysql_error($connection), mysql_errno($connection) );
    while ( $rows = mysql_fetch_assoc($result) )
    {
    	$overall = $rows['UserRating'] / $rows['UserVotes'];
    	// Do something with overall here, add to an array maybe? I don't know. It's your script.
    }
    PHP:
     
    Danltn, Jul 9, 2008 IP
  5. simstar

    simstar Peon

    Messages:
    467
    Likes Received:
    4
    Best Answers:
    0
    Trophy Points:
    0
    #5
    Cheers man you helped me out there!
     
    simstar, Jul 9, 2008 IP