0

I have an array which contains $player_ids. The array was obtained in a form which the user used to select his team. I then query the database with the $player_ids array. As such:

 if ( isset($_POST['submit']) ) {
    $player_ids = array_map('intval', $_REQUEST['players']);

    var_dump($player_ids);

    $query = 'SELECT `name` 
        FROM `player_info` 
        WHERE `player_id` IN (' . implode(',', $player_ids) . ')';

    $return_names = mysql_query($query) or die(mysql_error());

    while ( $row = mysql_fetch_assoc($return_names) ) {
        $selected[] = $row['name'];
    }

    var_dump($selected);

The above code is working and when I open it in my browser I get this output enter image description here

Now I want to extract the values from array $selected (which contains the names of players selected) and upload it to a database. I try to do this as follows:

foreach ($selected as $player){
    $sql = mysql_query('INSERT INTO `team`(`player_name`) VALUES ("$player")') 
    or die(mysql_error());
    print ($player); 
    echo'<br>';         
`   }

Im suspecting the above code is where the problem comes in. when the above code is executed the database contains only the array name itself and not the actual values of the array. As the following picture shows: enter image description here

If anyone could point me in the right direction, as to why the array name and not its values gets saved in the database it would be greatly appreciated.

Thanks in advance.

3 Answers 3

0

You must put double quotes around your string instead of single quotes. In single quoted strings variables like $player are not replaced by their value interpreted there as text.

Sign up to request clarification or add additional context in comments.

Comments

0

use this:

'INSERT INTO `team`(`player_name`) VALUES ("' . $player . '")'

instead of this:

'INSERT INTO `team`(`player_name`) VALUES ("$player")'

Comments

0

Just replace following code with your ones code and it will work efficiently.

foreach ($selected as $player){
    $sql = mysql_query("INSERT INTO `team`(`player_name`) VALUES ('$player')") 
    or die(mysql_error());
    echo "$player<br />";          
   }

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.