PHP/MySQL - Update array if variable does not exist - php

I have an array with different IDs which I get from my database.
$fotos_temp_list=explode(",",$fotos_temp["fa_id"][0]);
Result: fa_id => 15,16,17,18
Now I want to update all rows inside another table with the IDs 15,16,17,18 and insert a specific '$id' into a column called 'fa_ev_id'.
In this example I set:
$id=1;
Now my foreach-loop looks like this:
foreach ($fotos_temp_list as $key) {
UPDATE images SET fa_ev_id = Concat(fa_ev_id , ',' ,'".$id."') where fa_id='".$key."' ";
}
This part is working too.
Every row with my IDs (in my example: 15,16,17,18) gets updated.
Problem:
When I run the foreach-loop again, the '$id' will be saved again inside the row. See here:
Question:
How is it possible, that I can check if '$id' is already inside the row and if so, it gets skipped? Here is what I tried to do:
foreach ($fotos_temp_list as $key) {
if (!in_array($id,$key)===true) {
UPDATE fotoalbum SET fa_ev_id = Concat(fa_ev_id , ',' ,'".$id."') where fa_id='".$key."'
}
}
I think the in_array function checks if '$id' id already inside '$key' and if it is true, the UPDATE statement is done. Therefore I added '!in_array' but it doesn´t seems to work. Does anyone has an idea what I am doing wrong? I just want to check if the '$id' is already inside my database row and if so, it should not insert the '$id' again.
I appreciate any advice.

The in_array() function in php accepts an array as its second parameter, in (!in_array($id,$key)===true), https://www.w3schools.com/php/func_array_in_array.asp. The second parameter $key, passed in here isn't an array.
You could save the datatype of fa_ev_id as json, and retrieve and json_decode the value when you are about performing an update the field to know if that $id already exists using in_array() or you could retrieve the values, expolode them to form an array and then check if it exists with in_array().

Related

Retrieving the data from an sql statement

I have written this code which in theory i want to loop round an array and for every value use in a select statement to retrieve the applicable information. Then map a particular value id as a key and the value from the sql statement as its associated value. Though i cant seem to figure out how to add it as a value into my array im sure im a word out.
heres my code
/*
* Loop through the hasNewModelIdInYear and retrieve the exterior media paths
* with a mapped id as a key.
*/
$mediapatharray = array();
foreach ($hasNewModelIdInYear as $key => $value) {
$selectMediaPathFromValue = "SELECT `name` FROM `media` WHERE `id`='".$value['img1_media_id']."'";
$res = $mysqli->query($selectMediaPathFromValue);
$mediapatharray[$value['model_id']] = $res;
}
All that array returns is an array full of keys but no values.. With the variable $res do i then have to ->fetch_value? as im not sure on the syntax needed in order to access the data from the query?
regards mike
it is not good writing whan you have query inside loop. you should search based on array of img1_media_id
you can do follwing
$selectMediaPathFromValue = "SELECT `name` FROM `media`
WHERE `id` IN = '$hasNewModelIdInYear'";
array should be following format
$hasNewModelIdInYear = "12,21,22,65";
The result will return false on failure or the results on success. Mysqli result will be returned the first set of array that consist of the array index. You will need to fetch the values and store it in array. Try adding this code.
while($row = $res->fetch_assoc()){
$mediapatharray[$value['model_id']] = $row['name'];
}
Thanks for your responses i was trying to make it more complicated than it needed to be. I done it by putting the whole media table in a multidimension array then looping through them both and comparing values and if mathcing id map the name.
simple connection and sql query to populate the array, then map the id to a key and name as its value. heres my code.
mediaarray is an array with the media table contents populated in it
$mediaIdPAthFromOld = array();
foreach ($hasNewModelIdInYear as $hnkey => $hsvalue) {
foreach ($mediaarray as $mpavalue) {
if ($hsvalue['img1_media_id'] == $mpavalue['id']) {
$mediaIdPAthFromOld[$hsvalue['model_id']] = $mpavalue['name'];
}
}
}
though this has done what i wanted i assume there is a more effient way to do this.
regards mike

PDO getting only one value

I am querying a database for the latest row entered and get the id column only, so I am sure I will get one value. However, I am unable to print the variable unless it is in a foreach loop, not even accessing the 0th element is giving me any output.
I use this line of code for querying the latest row's id added: $id = $db->query("SELECT MAX(id) FROM FM;");
When I use the foreach loop, I get the following output:
Loop:
foreach ($id as $i)
print_r($i);
Output:
Array ( [MAX(id)] => 20 [0] => 20 )
However, when I use print $id[0]; or print $id["MAX(id)"]; I get the HTTP Error 500.
How can I get the single value id and put it in a variable, the id itself that is?
Thanks
I looked up in the PDOStatement reference which is returned fromt the query function, and found the fetchAll() method which returns an array of rows, and got the latest id by the following line of code: $id->fetchAll()[0][0];
Instead of selecting max(id) you have to use lastInsertId() method
$id = $db->lastInsertId();
right after calling insert query

How to select by condition on JSON column in MySQL?

How to write query for selecting data by where condition on column having JSON array?
i.e.
Suppose I have added user_name, user_role in ci_sessions. and user_data is JSON array.
SELECT *
FROM `ci_sessions` where user_data[user_role]='admin';
*********************/\***************
This where condition is needs to be designed. I require data with having user_role "admin".
Update: To check user_role "admin" is main objective of where condition.
Is there any way to add where condition as user_data[user_role] or user_data->user_role?
Update: This is possible in PostgresSQL DB.
Don't know what you're doing there, but you just call $this->session->userdata('user_role') and CI's automatically chooses how to retrieve that value. If you set (and I think you did) to use a database, the query will be performed automatically.
I don't understand how you actually saved your session variable, if you json_encoded() by yourself or you are referring to the encoding performed by CI.
In the latter, you just:
if($this->session->userdata('user_role') == 'admin')
{
// do stuff
}
Otherwise, $role = json_decode($this->session->userdata('user_role')); and the examine the array but I can't help you much here since you didn't provide clear information
I was keep on waiting for this type of query but I failed to do so. That's why I had made combination of sql and php.
I have got results from all ci_sessions table.
Then I checked in result by decoding field of JSON arraY. aND it's working fine.
SELECT * FROM `ci_sessions`;
foreach ($result as $row) {
$user_data=$row->user_data;
foreach (unserialize($user_data) as $k => $v) {
$final[] = array('key' => $k, 'value' => $v);
if($k=='user_role' && $v='admin') {
//make array of admin information required to show
}
}
}

Using PHP with a MySQL db, how can I select everything from a row if i dont know what the columns are?

I have a table but I dont know what the columns are except for 1 column. There is only 1 permanent data value for each row, the rest of the columns are added and removed elsewhere. This isnt a problem for the query, i just do:
SELECT * FROM table
but for the php function bind_result() i need to give it variables for each column, which i do not know.
I think that once I have the columns in an array, I can do anther query and use call_user_func_array to bind the result to the array.
This seems like it would come up a lot so im wondering is there a standard way of doing this?
Couldn't you just do:
$result = mysql_query("SELECT * FROM table");
while ($row = mysql_fetch_assoc($result))
{
foreach ($row as $field => $value)
{
...
}
}
You could do
show columns from table;
And then parse that string to grab your column names.
You can also try the describe command, which is used to list all of the fields in a table and the data format of each field. Usage:
describe TableName;
you can use
$metadata = $prep_statement->result_metadata()
after you executed the statement and then loop through all result fields using something like
while( $field = $metadata->fetch_field() ) { }
the properties of $field are documented here: http://www.php.net/manual/en/mysqli-result.fetch-field.php

unserialize problem

I have another problem with my scripy now I have made it more advance, first off the count function doesnt work properly and it gives this error.
Warning: array_push() [function.array-push]: First argument should be an array in C:\wamp\www\social\add.php on line 42
Here is my script:
$query = mysql_query("SELECT friends FROM users WHERE id='$myid'");
$friends = mysql_fetch_array($query);
$friends2 = unserialize($friends['friends']);
if (count($friends2) == 0) {
//option 1
$friends2 = array($id);
$friendsUpdated = serialize($friends2);
mysql_query("UPDATE users SET friends='$friendsUpdated' WHERE id='$myid'");
}else{
//option 2
array_push($friends2, $id);
$friendsUpdated = serialize($friends2);
mysql_query("UPDATE users SET friends='$friendsUpdated' WHERE id='$myid'");
It seems that $friends2 is not an array. Use the var_dump($friends2) function to see its value.
If you run this code right after having created the database but before putting any data in there, "unserialize($friends['friends']);" returns something other than an array. Probably an empty string. So in option 2, you may want to do something like this before array_push:
if (!is_array($friends2)) {
$friends2 = array();
}
This way, if the person has no friends by this point (sad.. but you'll fix it by pushing a new friend to them), an empty friends list gets initialized.
Plus, any time you see two identical lines of code in different parts of the "if" condition...
$friendsUpdated = serialize($friends2);
mysql_query("UPDATE users SET friends='$friendsUpdated' WHERE id='$myid'");
That's a signal that you should restructure your code so that you'd only have one copy of these lines.
This may not sound helpful, but your database design is quite stange.
Why is $friends2 not an array? Try to print_r () $friends after fetching an array to see if you actually get what you want from database in the first place.
Also, your count check is redundant. To add to an array, just go $friens2[] = $id; If $friends2 were empty, it will just make a new array of 1 element ($id), otherwise it will add it.
Your question contains the answer: unserialize($friends['friends']) seem to return non-array and count($friends2) is not zero - this can happen, for example, if number passed. Have you tried to examine the $friends['friends'] data? Simplest way would be to make additional check is_array($friends2)

Categories