1

I am trying to convert data from selected cell in SQL table to string so I can check if it's value is NULL. This is how my code looks now:

$columnname="cоntact";
$columnnumber=1;
$column=$columnname . $columnnumber;
$selectcell = mysqli_query($link, "SELECT '{$column}' FROM contacts WHERE id='{$userid}'");
$result = mysqli_fetch_assoc($selectcell);
$cell=(string)$result;

if (is_null($cell)) {
    // do something
} 

And this is the error I get:

Notice: Array to string conversion

I am sorry if my mistake is obvious, I am pretty new to php.

Qirel
  • 25,449
  • 7
  • 45
  • 62
Skibidy
  • 11
  • 1
  • 1
    Two things to notice right away: `'{$column}'` wrong quotes, and `$result` is an array, you can't just convert it to a string. You might want `$cell=(string)$result[$column];`? – Qirel Sep 23 '17 at 15:00
  • You're already using an API that supports **prepared statements** with bounded variable input, you should utilize parameterized queries with placeholders (prepared statements) to protect your database against [SQL-injection](http://stackoverflow.com/q/60174/)! Get started with [`mysqli::prepare()`](http://php.net/mysqli.prepare) and [`mysqli_stmt::bind_param()`](http://php.net/mysqli-stmt.bind-param). – Qirel Sep 23 '17 at 15:05

2 Answers2

1

Simple one really, you're using the resulting MySQL array in your is_null function. You need to access the column specifically as so:

$columnname="cоntact";
$columnnumber=1;
$column=$columnname . $columnnumber;
$selectcell = mysqli_query($link, "SELECT `{$column}` FROM contacts WHERE 
id='{$userid}'");
$result = mysqli_fetch_assoc($selectcell);
$cell=(string)$result[$column]; //note accessing the [$column] value of the $result array

if (is_null($cell)) {
    // do something
} 
Jordan
  • 1,390
  • 2
  • 9
  • 24
  • 1
    What about the quotes in the query, any thought on those? ;-) – Qirel Sep 23 '17 at 15:01
  • Eeverything returned from MySQL is a string, it doesn't care about the type of column. So the typecasting to string is redundant (its nothing wrong by doing it either), but still, you addressed both issues, +1 :-) – Qirel Sep 23 '17 at 15:09
  • Maybe I didn't describe well what I try to do. The code you edited above is giving me the name of the column (column1). I am trying to get the content of specific cell in the table. Edit: Do I even need to convert it to string? Is there a way to check if it's Null without converting? – Skibidy Sep 23 '17 at 15:21
  • The original code gives you the column, because you select a string (look at the quotes). But no, you don't need to convert it to string. – Qirel Sep 23 '17 at 15:55
0

The easiest approach, IMHO, would be to fetch the data as a non-associative array and take the first field:

$result = mysqli_fetch_row($selectcell);
$cell = $result[0];
Mureinik
  • 297,002
  • 52
  • 306
  • 350