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.

2
  • 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];? Commented Sep 23, 2017 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! Get started with mysqli::prepare() and mysqli_stmt::bind_param(). Commented Sep 23, 2017 at 15:05

2 Answers 2

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
} 
Sign up to request clarification or add additional context in comments.

4 Comments

What about the quotes in the query, any thought on those? ;-)
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 :-)
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?
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.
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];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.