0

So i'm still learning PHP, MySQL and a few other languages. While i'm trying to improve and learn i have develpoed a browser game.

Now i'm trying to save a "battle log" from each fight that takes place, that will allow my users to go back and look at their past fights.

To solve this i have tried to store each fight round into a php array. The problem for me now is to save that array into my database, for a user to request and have displayed to them.

I have tried to mess around with PHP's serialize and also with json_encode. But i fail to get them stored in my DB as it will eighter give me a syntax error or a empty row.

Here a example to display what i am trying to achive!

$i = 1;
$battle_log = array();

while( $i <= 10)
{
     $battle_log[] = "Round ".$i."<br>";
     $i++;
}

foreach ($battle_log as $rounds => $round) {
    echo "".$round."";
}

$save_log = json_encode($battle_log);
$sql = "INSERT INTO battle_log_test VALUES fighter1_id='13', fighter2_id='45', battle_log='".$save_log."' ";
$result = mysqli_query($connection, $sql) or die(mysqli_error($connection));

All input to help me solve this problem will be greatly appreciated.

4
  • data type of battle_log ? Commented Apr 13, 2016 at 10:16
  • Data type should be TEXT for 'battle_log' in your table and I think you should try json_encode($battle_log, true) Commented Apr 13, 2016 at 10:18
  • Yeah, it's TEXT in my DB. Commented Apr 13, 2016 at 10:20
  • @hmd what is json_encode($battle_log, true) ? Documentation mentions the 'true' option for json_decode only Commented Apr 13, 2016 at 10:22

3 Answers 3

1

You will have to use:

$query = "INSERT INTO battle_log (fighter1_id,fighter2_id,battle_log) VALUES (13,45,'".$save_log."');";
$sql = $mysqli_query($connection,$query) or die($mysqli_error($connection));
Sign up to request clarification or add additional context in comments.

1 Comment

Tried this and it works like a charm! :) Thanks alot!
0

Your INSERT query is wrong, should be:

$sql = "INSERT INTO battle_log_test 
    (fighter1_id, fighter2_id, battle_log) 
VALUES 
    ('13', '45', '".$save_log."')";

Comments

0

You can use PHP serialize() function insted json_encode()

$i = 1;
$battle_log = array();

while( $i <= 10)
{
 $battle_log[] = "Round ".$i."<br>";
 $i++;
}

foreach ($battle_log as $rounds => $round) {
    echo "".$round."";
}

$save_log = serialize($battle_log);
$sql = "INSERT INTO battle_log_test VALUES fighter1_id='13', fighter2_id='45', battle_log='".$save_log."' ";
$result = mysqli_query($connection, $sql) or  die(mysqli_error($connection));

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.