1

I want to save a SQL result in a variable.

<?php
    $sqlhost='localhost';
            $username='user';
            $passwort='passwd';
            $database='...';

    mysql_connect ($sqlhost,$username,$passwort);

mysql_select_db ($database);
    $query= "SELECT * FROM Test";
    $result = mysql_query($query) or die( mysql_error() );

    while($row = mysql_fetch_array($result)){
        echo $row['FB'];
    }
    $varibale = $row['ROW'];
    echo $varibale;
?>

I want to save it in a variable to make another SQL query with WHERE ROW2 = '$varibale'

Rodia
  • 1,407
  • 8
  • 22
  • 29
  • Please do not use mysql_* functions, it deprecated in new 5.6 versions and removed from 7.* – esemve Feb 28 '17 at 16:14
  • hold it right there before you can go on!! Please do not use `mysl_*` function its depreciated and no longer supported, use mysqli or pdo – Masivuye Cokile Feb 28 '17 at 16:15
  • put $varibale = $row['ROW']; inside while – Roy Bogado Feb 28 '17 at 16:31
  • Just to head things off at the pass once you add the `WHERE`: [Little Bobby](http://bobby-tables.com/) says ***[your script is at risk for SQL Injection Attacks.](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php)***. Even [escaping the string](http://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string) is not safe! – Jay Blanchard Feb 28 '17 at 16:32
  • What if there are multiple rows @Roy? The variable will be overwritten each time the loop completes, leaving the variable to be set to only the last value selected. – Jay Blanchard Feb 28 '17 at 16:33
  • Thanks for your help so far – Moritz Wagner Feb 28 '17 at 17:03
  • It works @Roy. Thanks man. You're the best :D – Moritz Wagner Feb 28 '17 at 17:10
  • Your welcome men, good coding! – Roy Bogado Feb 28 '17 at 17:11

1 Answers1

1

In this part of code:

while($row = mysql_fetch_array($result)) {
   echo $row['FB'];
}
$varibale = $row['ROW'];
echo $varibale;

You can access $row only inside while loop, so the simpliest solution is to create array, fill it, and than access. Like this:

$rowArray = [];
while($row = mysql_fetch_array($result)){
   array_push($rowArray, $row['FB']);
}
$varibale = $rowArray['ROW'];
echo $varibale;
Grynets
  • 2,477
  • 1
  • 17
  • 41