0

I have this PHP code to insert into mysql.

require_once("../form/corefile/functions.php");
$fn = new Functions();
$offers = $_REQUEST;
$offer=$_REQUEST['offer'];
$website =$_REQUEST['website'];
$keyword =$_REQUEST['keyword'];


$count_offer = count($_REQUEST['offer']);
var_dump($offer);exit;

for($i=0;$i<$count_offer ;$i++){
    $_offer  = ($offer[$i]);       
    $_website  = ($website[$i]);
    $_keyword  = ($offer[$i]);

    $query = $fn->InsertQuery("INSERT INTO offers (offer, website, keyword) VALUES ('$_offer','$_website','$_keyword')");
    //var_dump($query);exit;
    if($query)
{
$msg="Data Successfully Saved";
}

}

The array with var_dump($offer) looks like this;

array (size=2)
  0 => 
    array (size=1)
      'name' => string 'offer1' (length=6)
  1 => 
    array (size=1)
      'name' => string 'offer2' (length=6)

I am getting the error: Notice: Array to string conversion in repeat.php on line 19 where line 19 is the $query = $fn->insertQuery

Looks like I am making some mistake in pulling the correct data from the array.

Joshi
  • 2,730
  • 5
  • 36
  • 62
  • `$_offer` is an array. What you probably need is `$_offer['name']`. – Paul Spiegel Mar 20 '17 at 18:18
  • @PaulSpiegel - You are spot on. But can you give me some idea how I should build the sql query with like `$_offer['name']` will that be correct. As doing this I am still getting the error - `Array to string conversion` – Joshi Mar 20 '17 at 18:32
  • 1
    `{$_offer['name']}` should work. Or you assign `$_offer = $offer[$i]['name']`. But best way would be to use prepared statements with parameter binding. Your code is open to sql injections. – Paul Spiegel Mar 20 '17 at 18:36
  • http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php – Paul Spiegel Mar 20 '17 at 18:37
  • @PaulSpiegel - I will escape that with `mysqli_escape_string` or `addslashes`. I have not mentioned it compact the question. Thank you for pointing out though. I should have included that in the question. – Joshi Mar 20 '17 at 18:42
  • 1
    Don't use `addslashes()`! `mysqli_real_escape_string()` is the minimum you should do. And you could still forget to sanitize numerics. Using prepared statements you would have less to worry about. – Paul Spiegel Mar 20 '17 at 18:49
  • @PaulSpiegel - Thanks for your suggestion and help. Now the query is working perfectly. – Joshi Mar 20 '17 at 19:00

1 Answers1

0

The array $offer is an array of associative arrays.$offer[0] would return an array of singular key value pair which ofcourse is not a String hence the error.

Aditya Chauhan
  • 104
  • 1
  • 6