0

I have code like this

$mene   = date('Y-m-d h:i:s', strtotime('+1 days'));
$now    = date('Y-m-d h:i:s');
$qnow   = $this->db->query("SELECT pilihan,COUNT(pilihan) as total FROM votes WHERE date_create BETWEEN '$now' AND '$mene' GROUP BY pilihan");

$someArray = [];
foreach($qnow->result_array() as $row){
    array_push($someArray, [
    $row['pilihan']   => $row['total']
    ]);
}

$someJSON = json_encode($someArray);
echo $someJSON;

And this for result

[
  {
    "1": "213"
  },
  {
    "2": "444"
  }
]

How to make this result to single array, so result will be

[
  {
    "1": "213",
    "2": "444"
  }
]

Please help to resolve that, Thank you.

9
  • WARNING: This code has some SQL injection bugs because user data is not escaped before being used in the query. Read up on how to use query bindings with placeholder values so that data can be properly encoded before being used in the query. Even if the values used here seem harmless, they could be replaced at a later time with those that aren't, creating a hidden, exploitable hole. Commented Nov 10, 2017 at 17:13
  • Okay, thank you @tadman , I will check that Commented Nov 10, 2017 at 17:15
  • @tadman - I don't see any unescaped user input in his query. Commented Nov 10, 2017 at 22:18
  • @shaggy $now is interpolated, and although in this contrived example it's not user data, all it takes is switching that with $now = $_GET['date'] and you're in deep trouble. Sometimes these variables are defined in distant parts of the system and passed in so it's never obvious what is or isn't safe. That's why using placeholder values for everything, regardless of origin, is important. Commented Nov 13, 2017 at 0:19
  • @tadman - yes and if you switch echo $someJSON; to echo $config['db']['password']; you get in trouble too. So there are no SQL injection bugs. There might be, if he change the code. Commented Nov 13, 2017 at 9:17

1 Answer 1

1

Inside foreach loop try replacing the below code:

array_push($someArray, [$row['pilihan']   => $row['total']]);

to:

$someArray[$row['pilihan']] = $row['total'];
Sign up to request clarification or add additional context in comments.

1 Comment

How to work with multiple data? like this $someArray[$row['pilihan']] = $row['total'],[$row['ex1']] = $row['ex2'];

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.