I have three arrays example: $array1,$array2,$array3.
I want to insert the array2 and array3 in two different columns in the same table.
can i do that?
here is the code below that i am trying but it does not work for me i am doing in codeigniter:
controller:
$athletes_id = $this->input->post('athletes'); // array 1
$fields_id = $this->input->post('fields_id'); // array 2
$athlete_score = $this->input->post('athlete_score'); // array 3
$id = array();
foreach($athlete_score as $row){
$additional_data = array(
'test_reports_id' => $test_report_id,
'score' => $row,
);
$id[] = $this->test_model->save_test_reports_details($additional_data);
}
for($j=0;$j<count($fields_id);$j++){
$data2 = array('fields_id' => $fields_id[$j]);
$this->test_model->update_test_reports_details($id,$data2);
}
Model :
public function update_test_reports_details($id,$data2){
$this->db->where_in('id',$id);
$this->db->update('test_reports_details',$data2);
}
Just serialize the arrays.
$data2 = serialize($array2); // or whatever array you want to store
Then to retrieve with unserialize
$array2 = unserialize($data2);//or the row index
To store array in database you have to serialize it.
Try :
public function update_test_reports_details($id,$data2){
$this->db->where_in('id',$id);
$this->db->update('test_reports_details',serialize($data2));
}
To unserialize it when you get it from the database you have to use unserialize()
You can serialize as suggested in other answers, however I personally prefer to json_encode the array.
$data = json_encode($array);
And when you are reading in the model you should decode the data:
$array = json_decode($data, true); // set second argument to true to get an associative array
Using JSON has the advantage of better readability while still in the DB. This might not seem like much, but it can really help in some cases.
Related
I have this array:
$users = array();
// Finally, loop over the results
foreach( $select as $email => $ip )
{
$users[$email] = $ip;
}
Now i want to pass this array to ajax and print in another script:
$html="<center>Check users for spam</center>";
mcheck.php
echo $_POST['users'];
This code does not work. How can i do this?
As Sergiu Costas pointer out, the best way is to JSON encode it and then decode, but you can also try:
$html="<center>Check users for spam</center>";
If your $users array is:
$users = array( array('email' => 'a#email.com'), array('email' => 'b#email.com')));
then http_build_query('users' => $users) will generate:
users%5B0%5D%5Bemail%5D=a%40email.com&users%5B1%5D%5Bemail%5D=b%40email.com
which is the url-encoded version of:
users[0][email]=a#email.com&users[1][email]=b#email.com
which will be decoded back to array in mcheck.php
The Best way is to encode array into JSON format.
In PHP:
$users_json = json_encode($users);
// To decode in javascript
var obj = JSON.parse(json_str);
if u want to pass php array to js you can json_encode the array to do that.
$html="<center>Check users for spam</center>";
I store array structure in database table.
example
table name - example
id=1
data= array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43")
I want to get that array structure from table and assign data column to an array.
Example
while($row=mysqli_fetch_array($result))
{
$table=$row['data'];
}
I did this way.. but it's not working.
It results in:
$table[0]=>array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43")
You can save array data to database field in multiple ways.
I suggest two ways:
1) Serialized array:
you can save data using serialize() function.
e.g. $arr = array('234' => 'asfdads', 'asdf' => 'asdf2');
$toDb = addslashes(serialize($arr));
And then you can unserialize() them to get it back like:
$toDb = unserialize(stripslashes($fromDb));
2) Using json_encode() and json_decode();
e.g. $arr = array('234' => 'asfdads', 'asdf' => 'asdf2');
$toDb = json_encode($arr);
And then you can json_decode() them to get it back like:
$toDb = json_decode($fromDb)
Hello I have decoded a json string that I sent to my server and Im trying to get the values from him.
My problem is that I cant get the values from the inner arrays.
This is my code:
<?php
$post = file_get_contents('php://input');
$arrayBig = json_decode($post, true);
foreach ($arrayBig as $array)
{
$exercise = $array['exercise'];
$response["exercise"] = $exercise;
$response["array"] = $array;
echo json_encode($response);
}
?>
When I get the answer from my $response I get this values:
{"exercise":null,"array":[{"exercise":"foo","reps":"foo"}]}
Why is $array['exercise'] null if I can see that is not null in the array
Thanks.
From looking at the result of $response['array'], it looks like $array is actually this
[['exercise' => 'foo', 'reps' => 'foo']]
that is, an associative array nested within a numeric one. You should probably do some value checking before blindly assigning values but in the interest of brevity...
$exercise = $array[0]['exercise'];
Because of the [{...}] you are getting an array in an array when you decode your array key.
So:
$exercise = $array['exercise'];
Should be:
$exercise = $array[0]['exercise'];
See the example here.
How can I get the INDEXED array result?
$qry1 = DB::select('name')->from('people')->execute();
$assoc_array = $qry1->as_array();
$object = $qry1->as_object();
// $indexed_array = [...]
Only for learning purposes, thanks.
It's like:
$indexed_result[0]; // Name
// $indexed_result[1];
// $indexed_result[2];
Do you want to get an array of names like array(0 => 'John', 1 => 'Sam')?
You should call $names = $gry1->as_array(NULL, 'name');
http://kohanaframework.org/3.3/guide/database/results#select-asobject-and-asassoc
The method as_assoc() will remove the object name and return the
results set back to an associative array. Since this is the default,
this method is seldom required.
So just do your execution.
But if you want only one row take a look at the current() method.
I want to store short arrays in a field. (I realize there are reasons to break the array up into items and store separately, but I'm opting for a simple storage option at the expense of less capability.)
My code to create the array is as follows:
$str = "one,two,three,four";
$array = explode (",",$str)
I then store into a text field in mysql using an insert statement It seems to store fine. In PhPAdmin, it shows ARRAY in the field and if I just echo $array, it prints "ARRAY".
The problem is occurring when I try to retrieve data.
I am retrieving using
while($row = mysql_fetch_array($res)) {
$array = $row['list']; //that's the field it is stored in
echo $array; // echoes "ARRAY"
//so far so good. However, when I then try to print out the contents of the array, I get error messages. I have tried using implode and also for each.
$text = implode(",", $array);//yields error message improper argument in implode function
foreach($array as $val) {
echo $val;
} //yields error message improper argument for for each statement
}
Could my entry in the dbase not be a proper array? What could the problem be? Thanks for any suggestions.
The usual approach to storing an array in this way is to serialize the data before input, and unserialize it upon retrieval.
$array = array('one', 'two', 'three', 'four');
$stringToStore = serialize($array);
Later:
while($row = mysql_fetch_array($res)) {
$array = unserialize($row['list']);
var_dump($array);
}
What you're inserting is not an array, just what PHP has evaluated your array as being in string form. To store an array in MySQL without properly normalizing your data you'll need to serialize it. Basically you'd want to do something like:
$serialized = implode(',', $arrayToStore);
and then store that in MySQL. On its way out then you'll do:
$unserialized = explode(',', $arrayFromMySQL);
I think you can use serialize and also (if you don't use serialize) if your array string is as follows
$str = "one,two,three,four";
then why you are making it an array before inserting it into your database, I think you can insert the string directly and when you need to use your string as an array then you can simply retrieve the string from database and make it an array using explode like
while($row = mysql_fetch_array($res)) {
$array = explode(",", $row['list']); // "one,two,three,four"
echo $array[0]; // one