Comparing values in two PHP arrays, problem adding more values to one of the arrays - php

I'm comparing values in two arrays, one created from a local database ($dbArray) while loop, and the other fetched from a API ($tmdbArray). This is working. But now I want to add another value (id) from the local database ($dbArray), and I can't get that to work.
This is working:
<?php
// database names
$dbArray = array();
while($rowMatch = mysqli_fetch_array($sqlTitlePerson)){
$dbArray[] = trim(preg_replace("/\([^)]*\)/", '', $rowMatch['name']));
}
// tmdb names
$tmdbArray = array();
foreach($credits['cast'] as $credit){
if(!in_array($credit['name'], $dbArray)){
$tmdbArray[] = $credit['name'];
}
}
foreach ($tmdbArray as $castArray){
echo $castArray.'<br>';
}
?>
Now I want to add a id from the local database, which is in $rowMatch['id'].
How can I add $rowMatch['id'] to the $dbArray[]?
$dbArray[] = $rowMatch['id'];
I have tested several solutions, but none works for me, and I don't know why.
Thanks,

Related

Insert Json object to database in php

I am working on an android app which uses APIs made with php. Here, i am dynamically creating columns and their values.
I am verifying the API via postman and a strange thing happens every time, While looping through the Json Object what i am doing is first creating column and then inserting its values.
The problem is only the 1st iteration saves the element and rest of them only creates the column but does not insert the values. I don't know if i am doing anything wrong, below is my php code.
<?php
include("connection.php");
$data = file_get_contents('php://input');
$json_data = json_decode($data);
foreach($json_data as $key => $val) {
$column_name = $key ;
$c_column_name = preg_replace('/[^a-zA-Z]+/', '', $column_name);
$column_value = $val ;
$table_name = "test2";
$email = "ht#t.com";
$result = mysqli_query($conn,"SHOW COLUMNS FROM $table_name LIKE '$c_column_name'");
$exists = (mysqli_num_rows($result))?TRUE:FALSE;
if($exists) {
$query1 = "INSERT INTO $table_name($c_column_name)VALUES('$column_value') ";
$data0=mysqli_query($conn,$query);
if($data0)
{
echo json_encode(array("success"=>"true - insertion","message"=>"Column existed, Successfully data sent."));
}
else{
echo json_encode(array("success"=>"false - insertion","message"=>"Column existed, data not inserted."));
}
}
else{
$query2="ALTER TABLE $table_name ADD COLUMN `$c_column_name` varchar(50) NOT NULL";
$data1=mysqli_query($conn,$query2);
if($data1){
$query3="INSERT INTO $table_name($c_column_name)VALUES('$column_value')";
$data2=mysqli_query($conn,$query3);
if($data2)
{
echo json_encode(array("success"=>"true - insertion","message"=>"Successfully data sent."));
}
else{
echo json_encode(array("success"=>"false - insertion","message"=>"Column created but data not inserted."));
}
}
else
{
echo json_encode(array("success"=>"false - column creation","message"=>"Failed to create column.'$column_name', '$table_name', '$conn'"));
}
}
}
?>
Here is the Json Object through postman.
{"Shape":"rewq","Trans.No.":"yuuiop","Color":"qwert"}
Please help me with this, any help or suggestions are highly appreciated.
The second column name is Trans.No. which contains a dot, this is why it fails, probably you have an error as a result which prevents further columns from being created.
I think it would be much better to have a table with this structure:
attributes(id, key, value)
and whenever a key-value pair is received, you just insert/update it, depending on the logic you need to be executed. Your current model will create a separate row for each attribute, which is probably not what you want to achieve.
EDIT
Based on the information received in the comment section I reached the following conclusion:
You could create the missing columns first and then generate the insert statement with all the columns, having a single insert.
But it would be better to not create a separate column for each value, as the number of columns could quickly get out of hand. Instead you could have a table:
myentity(id, name)
for storing the entities represented by the JSON and
attributes(id, myentity_id, key, value)
for storing its attributes. This would be a neat schema with all the dinamicity you could want.

PHP/MySQL - how to push additional elements into array in the "while" loop?

I'm pulling the information from an mySQL database, but I need to add additional fields that are not in the database.
The code below works fine, until one of the commented options is enabled:
$sth = mysqli_query($db_connect,$sql);
while($r3 = mysqli_fetch_assoc($sth)) {
//array_push($r3, 'str_close'=>$est_close_time);
//$r3['str_close']=>$est_close_time;
$row_v3_data[]=$r3;
}
Once enabled, the php shows "Error 500"
The simplest way would be to add the other data to $r3 before adding it to the array
$sth = mysqli_query($db_connect,$sql);
while($r3 = mysqli_fetch_assoc($sth)) {
$r3['str_close'] = $est_close_time;
$row_v3_data[] = $r3;
}
This assumes $est_close_time actually exists before using it
you can add a key and an element to an associative array at the same time. the format is just:
$r3['str_close'] = $est_close_time;
no need for an explicit push

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

php mysql issue with check if record exist before insert

I'm having a little problem with the codes given below. When I'm using the name="staff_number[]" then it insert the record with everything ok even if it is already in the database table and when i use name="staff_number" it does check the record and also give me alert box but when insert the record if it is not in the database it stores only the first number of the staff number like the staff no is 12345 it stores only 1. can anyone help in this record i think there is only a minor issue what I'm not able to sort out.
PHP Code:
<select placeholder='Select' style="width:912px;" name="staff_number[]" multiple />
<?php
$query="SELECT * FROM staff";
$resulti=mysql_query($query);
while ($row=mysql_fetch_array($result)) { ?>
<option value="<?php echo $row['staff_no']?>"><?php echo $row['staff_name']?></option>
<?php } ?>
</select>
Mysql Code:
$prtCheck = $_POST['staff_number'];
$resultsa = mysql_query("SELECT * FROM staff where staff_no ='$prtCheck' ");
$num_rows = mysql_num_rows($resultsa);
if ($num_rows > 0) {
echo "<script>alert('Staff No $prtCheck Has Already Been Declared As CDP');</script>";
$msg=urlencode("Selected Staff ".$_POST['st_nona']." Already Been Declared As CDP");
echo'<script>location.href = "cdp_staff.php?msg='.$msg.'";</script>';
}
Insert Query
$st_nonas = $_POST['st_nona'];
$t_result = $_POST['st_date'];
$p_result = $_POST['remarks'];
$arrayResult = explode(',', $t_result[0]);
$prrayResult = explode(',', $p_result[0]); $arrayStnona = $st_nonas;
$countStnona = count($arrayStnona);
for ($i = 0; $i < $countStnona; $i++) {
$_stnona = $arrayStnona[$i];
$_result = $arrayResult[$i];
$_presult = $prrayResult[$i];
mysql_query("INSERT INTO staff(st_no,date,remarks)
VALUES ('".$_stnona."', '".$_result."', '".$_presult."')");
$msg=urlencode("CDP Staff Has Been Added Successfully");
echo'<script>location.href = "cdp_staff.php?msg='.$msg.'";</script>';
}
Your $_POST['staff_number'] is actually an array.
So you have to access it like $_POST['staff_number'][0] here, 0 is a index number.
If the name of select is staff_number[] then $prtCheck will be a array so your check query must be in a loop to make sure your check condition.
if the name is staff_number then the below code is fine.
The answer of amit is right but I will complete it.
Your HTML form give to your PHP an array due to the use of staff_number[] with [] that it seems legit with the "multiple" attribute.
So you have to loop on the given values, you do it with a for and a lot of useless variables without really checking it. From a long time, we have the FOREACH loop structure.
I could help you more if i know what is the 'st_nona', st_date' and 'remarks' values.
According to your question you are getting difficulty in storing the data. This question is related to $_POST array.
Like your question we have selected following ids from the select : 1,2,3,4
It is only storing 1.
This is due to you have not used the loop when inserting the data.
Like below:
<?php
foreach($_POST['staffnumber'] as $staffnumber){
$query=mysql_query("select * from staff where staff_number =".$staffnumber);
if(mysql_num_rows($query)>0){
//action you want to perform
}else{
//action you want to perform like entering records etc. as your wish
}
}
?>
And I would like to suggest you that use the unique keys in database for field and use PHP PDO for database, as it is secure and best for OOPs.
Let me know if you have any queries.

Lots of 'If statement', or a redundant mysql query?

$url = mysql_real_escape_string($_POST['url']);
$shoutcast_url = mysql_real_escape_string($_POST['shoutcast_url']);
$site_name = mysql_real_escape_string($_POST['site_name']);
$site_subtitle = mysql_real_escape_string($_POST['site_subtitle']);
$email_suffix = mysql_real_escape_string($_POST['email_suffix']);
$logo_name = mysql_real_escape_string($_POST['logo_name']);
$twitter_username = mysql_real_escape_string($_POST['twitter_username']);
with all those options in a form, they are pre-filled in (by the database), however users can choose to change them, which updates the original database. Would it be better for me to update all the columns despite the chance that some of the rows have not been updated, or just do an if ($original_db_entry = $possible_new_entry) on each (which would be a query in itself)?
Thanks
I'd say it doesn't really matter either way - the size of the query you send to the server is hardly relevant here, and there is no "last updated" information for columns that would be updated unjustly, so...
By the way, what I like to do when working with such loads of data is create a temporary array.
$fields = array("url", "shoutcast_url", "site_name", "site_subtitle" , ....);
foreach ($fields as $field)
$$field = mysql_real_escape_string($_POST[$field]);
the only thing to be aware of here is that you have to be careful not to put variable names into $fields that would overwrite existing variables.
Update: Col. Shrapnel makes the correct and valid point that using variable variables is not a good practice. While I think it is perfectly acceptable to use variable variables within the scope of a function, it is indeed better not use them at all. The better way to sanitize all incoming fields and have them in a usable form would be:
$sanitized_data = array();
$fields = array("url", "shoutcast_url", "site_name", "site_subtitle" , ....);
foreach ($fields as $field)
$sanizited_data[$field] = mysql_real_escape_string($_POST[$field]);
this will leave you with an array you can work with:
$sanitized_data["url"] = ....
$sanitized_data["shoutcast_url"] = ....
Just run a single query that updates all columns:
UPDATE table SET col1='a', col2='b', col3='c' WHERE id = '5'
I would recommend that you execute the UPDATE with all column values. It'd be less costly than trying to confirm that the value is different than what's currently in the database. And that confirmation would be irrelevant anyway, because the values in the database could change instantly after you check them if someone else updates them.
If you issue an UPDATE against MySQL and the values are identical to values already in the database, the UPDATE will be a no-op. That is, MySQL reports zero rows affected.
MySQL knows not to do unnecessary work during an UPDATE.
If only one column changes, MySQL does need to do work. It only changes the columns that are different, but it still creates a new row version (assuming you're using InnoDB).
And of course there's some small amount of work necessary to actually send the UPDATE statement to the MySQL server so it can compare against the existing row. But typically this takes only hundredths of a millisecond on a modern server.
Yes, it's ok to update every field.
A simple function to produce SET statement:
function dbSet($fields) {
$set='';
foreach ($fields as $field) {
if (isset($_POST[$field])) {
$set.="`$field`='".mysql_real_escape_string($_POST[$field])."', ";
}
}
return substr($set, 0, -2);
}
and usage:
$fields = explode(" ","name surname lastname address zip fax phone");
$query = "UPDATE $table SET ".dbSet($fields)." WHERE id=$id";

Categories