user2995689
user2995689

Reputation: 13

Storing Value from a Query PHP MYSQL

I am working on a PHP MYSQL Project. I want to store result from a query into variable so that i can use it in my code. The Query is written below.

$result=mysqli_query($con,"SELECT Age FROM Employee where EmpID = '$_POST[empid]'"); 

This Query will output the following

Age
27

Kindly tell me how to store this value 27 in a variable lets say $Num.

Thanks in advance.

Upvotes: 0

Views: 110

Answers (6)

gedq
gedq

Reputation: 610

$result will return a mysql dataset. You'll need to pull the value you need out of that dataset. I'm a PDO man but if memory serves

$Num = mysqli_fetch_assoc('Age');

will get you what you need.

I advise against beginning variables with a capital letter - it breaks most coding standards and could be confused with class names. And you really, really shouldn't send unsanitised POST variables to the database.

Upvotes: 1

user7789076
user7789076

Reputation: 798

After this line

$result=mysqli_query($con,"SELECT Age FROM Employee where EmpID = '$_POST[empid]'"); 

ADD

$row=mysqli_fetch_array($result);
 $Num=$row['Age'];

Thanks

Upvotes: 0

R R
R R

Reputation: 2956

try

$result=mysqli_result(mysqli_query($con,"SELECT Age FROM Employee where EmpID = '$_POST[empid]'"),0); 
$num=$result;

echo $num;

Upvotes: 0

eXaminator
eXaminator

Reputation: 353

This should work:

$row = mysqli_fetch_assoc($result));
$age = $row['Age'];

To expand on this: If your query would return multiple rows you could iterate over them:

while($row = mysqli_fetch_assoc($result)) {
    echo $row['Age'];
}

Upvotes: 1

BuysDB
BuysDB

Reputation: 143

Beware: never use POST variables directly without proper cleaning in your queries; it is very unsafe. At least use real escape string

Upvotes: 1

Albzi
Albzi

Reputation: 15609

$num = $result; Although you're better off just using $result

Or long winded (but handy if there is more than 1 value you're trying to get)

foreach ($result as $r):
    $Num = $r['Age'];
endoforeach;

Upvotes: 0

Related Questions