-2

I have multiple columns withing my mysql data base however I need data from 1 of 2 of them. There is either data in column1 or column2 there is no insane where data is available in both.

I have tried the below with no luck. I have also looked around and can't seem to find an easy way of dealing with this.

<?php
$query = "SELECT `column1`,`column2` FROM `table` WHERE `name` LIKE 'Jack'";
$columcheck = $query['column1'];
if ($columcheck == null) {    
   $columcheck = $query['column2'];
}
echo $columcheck;
?>

I basically just want to echo the column that is not empty.

Thanks in advance. Lucas.

1 Answers1

0

First off you need to fetch the data as well as actually read it. I put together a little function for you that you can use. You should improve upon it though. Use prepared statements, if you need more than the first result store it in an array and loop through, etc etc.

Also note I set up this function assuming the use of php 7.1+. If that's not the case remove the type hints.

function collectData(\mysqli $connection): ?string {
    if ($connection->connect_error) {
        return null;
    }

    $result = $connection->query("SELECT `column1`,`column2` FROM `table` WHERE `name` LIKE 'Jack'");

    if ($result->num_rows > 0) {
        while($row = $result->fetch_assoc()) {
            if($result['column1'])
                return $result['column1'];
            return $result['column2'];
        }
    }
}
Lulceltech
  • 1,662
  • 11
  • 22
  • Not really sure why you would return from inside while loop – RiggsFolly Apr 30 '19 at 13:50
  • look at his sample, he's not looping through anything. Which leads me to believe he only wants 1 result. Read my notes at the top, I covered this already lol. – Lulceltech Apr 30 '19 at 13:53