lacyeex
lacyeex

Reputation: 175

PHP error : Array to string conversion

I have a PHP file named with Set of HTML codes, this code is to show several ID of location to be selected for the next process (Form is GET).

$sqloc = mysql_query("SELECT loc_id FROM location");
while ($row = mysql_fetch_array($sqloc)){

echo "<tr><td>
    <label><input type=\"checkbox\" name=\"chk_loc[]\" value=". $row['loc_id'] ." />
</td><td>" . $row['loc_id'] . "</td></tr></label>"; }

Then in other PHP file i use this code to select data based on selected ID using checkbox before.

$cbarray = array();
if (isset($_GET['submit_location'])) {
  $cbarray = $_GET['chk_loc']; }

for ($i=0; $i<count($cbarray); $i++) {
  $sqlcb = mysql_query("SELECT * FROM location WHERE loc_id = '$cbarray'");
      while($ccb= mysql_fetch_row($sqlcb)) {
                print_r($ccb); }
}

But when i run it, it appear the notice :

Array to string conversion in .... on line 62

On line 62 which is on ($sqlcb = mysql_query) part. I already use var_dump to check the array, and it print the array like this :

array(4) { [0]=> string(5) "LO001" [1]=> string(5) "LO003" [2]=> string(5) "LO004" [3]=> string(5) "LO005" } 

Is there anyway to solve this problem? thank you.

Upvotes: 1

Views: 6514

Answers (2)

Rajdeep Paul
Rajdeep Paul

Reputation: 16963

The problem is because of this statement,

$sqlcb = mysql_query("SELECT * FROM location WHERE loc_id = '$cbarray'");
                                                                 ^ see here

$cbarray is actually an array, not a string. You can see it's structure using var_dump($cbarray);.

So the solution is:

Use implode() function to join the array elements with a string and use it in your query, like this:

$cbarray = array();
if (isset($_GET['submit_location'])) {
    $cbarray = $_GET['chk_loc'];

    $query = "SELECT * FROM location WHERE loc_id IN ('" . implode("','", array_map('mysql_real_escape_string', $cbarray)) . "')";
    $sqlcb = mysql_query($query);
    while($ccb= mysql_fetch_row($sqlcb)) {
        print_r($ccb); 
    }
}

Sidenote: Don't use mysql_* functions, they are deprecated as of PHP 5.5 and are removed altogether in PHP 7.0. Use mysqli or pdo instead. And this is why you shouldn't use mysql_* functions.

Upvotes: 2

Naresh Kumar
Naresh Kumar

Reputation: 561

The Checkbox in php is processed as a array. Here in the code the checkbox with id chk_loc is stored in $cbarray as a array. $sqlcb = mysql_query("SELECT * FROM location WHERE loc_id = '$cbarray'"); in this code the where clause accept a string and you are providing a array.

And use PDO to prevent sql injection PDO PHP

Upvotes: 3

Related Questions