Get `Warning: mysqli_real_escape_string()` after update database - php

I try to make my custom code to update data to my custom database table
after I send the data I get:
Warning: mysqli_real_escape_string() expects parameter 2 to be string,
array given in .../wp-includes/wp-db.php on line 1156
My table structure is:
table name: wp_wlm_user_options
column names: ID, user_id, option_name, option_value
My code is:
if (isset($_POST['submit'])) {
$user_id = $_POST['user_id'];
$table = 'wp_wlm_user_options';
$meta = array();
foreach ($wlm_user_info as $key => $value) {
$get_meta = $value['option_name'];
array_push($meta, $get_meta);
}
//var_dump($meta);
$value = array(
'custom_firstname' => $_POST['first_name'],
'custom_lastname' => $_POST['last_name'],
'custom_text_dateofbirth' => $_POST['text_dateofbirth'],
'custom_radio_gender' => $_POST['radio_gender'],
'custom_landlinephone' => $_POST['landlinephone'],
'custom_GoogleHangoutsId' => $_POST['GoogleHangoutsId']
);
$format = array(
'%s',
'%s'
);
//print_r($meta,$value);
$data = array(
'user_id' => $user_id,
'option_name' => $meta,
'option_value' => maybe_serialize($value)
);
$format = array('%d','%s','%s');
$where = array(
'user_id' => $user_id,
'option_name' => $meta
);
$x = $wpdb->update($table, $data, $where, $format);
//$x = $wpdb->update($table, $data, $where);
if($x){
echo '<h1>data has been save</h1>' ;
}
Can anyone tell me what is wrong with this?

Due to your poor information we can only guess.
You might want something like this:
if (isset($_POST['submit']))
{
$user_id = $_POST['user_id'];
$table = 'wp_wlm_user_options';
$values = array(
'custom_firstname' => $_POST['first_name' ],
'custom_lastname' => $_POST['last_name' ],
'custom_text_dateofbirth' => $_POST['text_dateofbirth'],
'custom_radio_gender' => $_POST['radio_gender' ],
'custom_landlinephone' => $_POST['landlinephone' ],
'custom_GoogleHangoutsId' => $_POST['GoogleHangoutsId']
);
$format = array('%s');
$whereformat = array('%d','%s');
foreach($values as $key => $val)
{
$data = array(
'option_value' => maybe_serialize($val)
);
$where = array(
'user_id' => $user_id,
'option_name' => $key
);
$num_rows = $wpdb->update($table, $data, $where, $format, $whereformat);
if($num_rows !== false){
echo "<h1>$key has been saved</h1>" ;
}
}
};
The code above does multiple updates mapping the data to option_name and option_value for each update() invocation. You don't need to update fields of the WHERE clause with unchanged values.
You can find the official documentation on wordpress.org

Related

How do I pass the mysql NOW() function from an array into a sanitized value

I'm making an update database method and everything works as it should except when I try to add 'updated' => NOW() to $updateArray(). Obviously PDO sanitizes the mysql function leaving 0000-00-00 in the database.
public function update( $table, $id, $updateArray ) {
$valuesArray = array_values( $updateArray );
$valuesArray[] = $id;
foreach ( $updateArray as $col => $value ) {
$values .= "$col = ?, ";
}
$values = substr( $vals, 0, -2 );
$query = $this->handle->prepare("UPDATE $table SET $values WHERE id = ?");
return $query->execute( $valuesArray );
}
$updateArray = ['title' => $_POST["title"], 'label' => $_POST["label"], 'body' => $_POST["body"], 'updated' => 'NOW()'];
$db->update( 'pages', $_POST["id"], $updateArray );
What ia the best way to get arround this ? all my ideas are very hacky.
Give this a try. The Database looks fine.
Change the query to this.
$query = $this->handle->prepare("UPDATE $table SET $values, updated=now() WHERE id = ?");
Update this
$updateArray = ['title' => $_POST["title"], 'label' => $_POST["label"], 'body' => $_POST["body"]];
I don't think there will be any harm to put the data like this. Comment below your result or any issue.
EDIT 1:
Change datatype of updated to DATE TIME in your database.
$date = date("Y-m-d H:i:s", time());
$updateArray = ['title' => $_POST["title"], 'label' => $_POST["label"], 'body' => $_POST["body"], 'updated' => '$date'];
I've put together a now() function, i'm not sure which function is best but they both work.
function now() {
$date = new DateTime();
$date->setTimezone(new DateTimeZone( 'Europe/London' ) );
return $date->format( 'Y-m-d H:i:s' );
}
function now() {
date_default_timezone_set( 'Europe/London' );
return date( 'Y-m-d H:i:s' );
}
$updateArray = ['title' => $_POST["title"], 'label' => $_POST["label"], 'body' => $_POST["body"], 'updated' => now()];

Saving PHP variable to MySQL INT is always 0

I am having a problem passing a variable to be saved as INT in MySQL. The closest thing I could find to my issue is this question but I have already verified that I am not using single and double quotes. When I print_r($this->session->userdata('subdomain')) I see the correct subdomain id on my screen (in this case 10), but when I try passing this using $params it always save subdomain_id as 0 and I can not figure out why.
Here is Project_assignees_model:
function add_prefix_project_assignees($params)
{
$this->db->insert('prefix_project_assignees',$params);
return $this->db->insert_id();
}
Here is my Project controller (Specifically it is the $assignees array):
function edit($entry_id)
{
$this->load->library('form_validation');
$this->form_validation->set_rules('client_id','Client Id','required|integer');
$this->form_validation->set_rules('title','Project Title','required|max_length[255]');
$this->form_validation->set_rules('project_status','Project Status','required');
$this->form_validation->set_rules('project_details','Project Details','required');
$this->form_validation->set_rules('project_estimated_hours','Project Estimated Hours','required|max_length[255]');
$this->form_validation->set_rules('end','Project Deadline','required');
if($this->form_validation->run())
{
date_default_timezone_set("America/New_York");
$date = date("Y-m-d h:i:sa");
$params = array(
'subdomain_id' => $this->session->userdata('subdomain'),
'client_id' => $this->input->post('client_id'),
'title' => $this->input->post('title'),
'project_status' => $this->input->post('project_status'),
'project_details' => $this->input->post('project_details'),
'project_last_updated' => $date,
'project_estimated_hours' => $this->input->post('project_estimated_hours'),
'start' => $this->input->post('start'),
'end' => $this->input->post('end'),
'owner_id' => get_current_user_id(),
);
$prefix_projects_id = $this->Project_model->update_prefix_projects($entry_id,$params);
$assignees = array(
'subdomain_id' => $this->session->userdata('subdomain'),
'project_id' => $entry_id,
'user_id' => $this->input->post('assignee'),
);
$this->load->model('Project_assignee_model');
$insertAssignees = array();
for ($i = 0; $i < count($assignees['user_id']); $i++)
{
//Get user_id from ID
$userID = $assignees['user_id'][$i];
$insertAssignees[$i] = array('project_id' => $entry_id, 'user_id' => $assignees['user_id'][$i]); // $insert is ready for insert_batch
$prefix_assignees = $this->Project_assignee_model->add_prefix_project_assignees($insertAssignees[$i]);
}
//redirect('project/index');
}
else
{
$this->load->model('Client_model');
$data['prefix_clients'] = $this->Client_model->get_all_prefix_clients();
$data['prefix_projects'] = $this->Project_model->get_prefix_projects($entry_id);
$data['prefix_users'] = $this->aauth->list_users();
$this->load->model('Project_assignee_model');
$data['prefix_assignees'] = $this->Project_assignee_model->get_prefix_project_assignees($entry_id);
$this->load->view('project/edit',$data);
}
}
Why does print_r show the correct subdomain_id but when it is saved to database it saves as 0?
*******UPDATE*******
Just for reference, this works:
$assignees = array(
'subdomain_id' => 10,
'project_id' => $entry_id,
'user_id' => $this->input->post('assignee'),
);
But this does not (Even though printing the userdata for subdomain gives me 10):
$assignees = array(
'subdomain_id' => $this->session->userdata('subdomain'),
'project_id' => $entry_id,
'user_id' => $this->input->post('assignee'),
);
Sometimes I guess it just takes writing it out for others before I realize my problem. When I loop through each assignee to add them to the table I realized I was not passing the subdomain_id with it.
I had this:
$insertAssignees[$i] = array('project_id' => $entry_id, 'user_id' => $assignees['user_id'][$i]); // $insert is ready for insert_batch
Needed to be changed to have subdomain_id included
$insertAssignees[$i] = array('subdomain_id' => $this->session->userdata('subdomain'), 'project_id' => $entry_id, 'user_id' => $assignees['user_id'][$i]); // $insert is ready for insert_batch

Looping through results of a sql query

I have a query that returns multiple rows. I can't seem to find a way to store the rows in the $params array. Is there a way to loop throw and store each row in the $params variable
$aResult = $db->exec_sql($sql);
$params = array(
// where $aResult[o]'' would be row 1 [1] row 2 etc. //
'store_id' => $aResult[]['iStoreID'],
'user_id' => $aResult[]['iUserID'],
'store_name' => $aResult[]['cStoreName'],
'store_url' => $aResult[]['cStoreURL'],
'rid' => $aResult[]['cRID'],
'affiliate_id' => $aResult[]['iAffiliateID'],
'team_id' => $aResult[]['iTeamID'],
'bizOP' => $aResult[]['cDefaultBizOpp'],
'showBizOPp' => $aResult[]['iShowBizOppDropdown'],
'boPosting' => $aResult[]['iEnableBOPosting'],
'brandinglevel' => $aResult[]['iBrandingLevel']
);
thank you for your help
As simple as that:
$params = array();
foreach($aResult as $row) {
$params[] = array(
'store_id' => $row['iStoreID'],
'user_id' => $row['iUserID'],
'store_name' => $row['cStoreName'],
'store_url' => $row['cStoreURL'],
'rid' => $row['cRID'],
'affiliate_id' => $row['iAffiliateID'],
'team_id' => $row['iTeamID'],
'bizOP' => $row['cDefaultBizOpp'],
'showBizOPp' => $row['iShowBizOppDropdown'],
'boPosting' => $row['iEnableBOPosting'],
'brandinglevel' => $row['iBrandingLevel']
);
}
Without knowing the exact structure of the result array i guess you need something like this:
<?php
$params = array();
$mapping = array(
'store_id' => 'iStoredID',
'user_id' => 'iUserID',
// and so on...
);
foreach ($aResult as $row) {
$tempRow = array();
foreach ($row as $key => $value) {
$paramKey = isset($mapping[$key]) ? $mapping[$key] : $key;
$tempRow[$paramKey] = $value;
}
$params[] = $tempRow;
}
I use it like this
$aResult = mysql_query($sql);
while($data = mysql_fetch_array($result)) {
'store_id' = $aResult['iStoreID'];
}
At least that is the idea

If array is empty how do I exclude it from json_encode? (PHP)

I'm building json sub-array structure (from CSV) using the following PHP:
$tracks = array();
foreach ($result['tracks'] as $trackdata) {
$songId = $trackdata['songId'];
$title = $trackdata['title'];
$ISRC = $trackdata['ISRC'];
$name1 = $trackdata['artists:name[1]'];
$name2 = $trackdata['artists:name[2]'];
$main1 = $trackdata['artists:main[1]'];
$main2 = $trackdata['artists:main[2]'];
$tracks['tracks'][] = array(
'songId' => $songId,
'title' => $title,
'ISRC' => $ISRC,
'artists' => array(
0 => array(
'name' => $name1,
'main' => (boolean) $main1
),
1 => array(
'name' => $name2,
'main' => (boolean) $main2
)
)
);
}
Currently, if the CSV contains empty values the json (correctly) displays the value as NULL.
What would I need to add to my PHP to stop a particular object from being part of the json if its value is empty / blank?
I'm specifically looking to not print artists:name[2] and artists:main[2] if a second artists doesn't exist in the CSV data.
Here is an example of the CSV code:
"trk-04","track 4","USAM18490006","John Smith",true,,
I've researched (and attempted to implement) if (empty... but I'm not sure where that would come in this code.
Any pointers would be great.
Thanks in advance!
You will want to avoid adding the second artist to the intermediate array that you subsequently json-encode.
$tracks = array();
foreach ($result['tracks'] as $trackdata) {
$songId = $trackdata['songId'];
$title = $trackdata['title'];
$ISRC = $trackdata['ISRC'];
$name1 = $trackdata['artists:name[1]'];
$name2 = $trackdata['artists:name[2]'];
$main1 = $trackdata['artists:main[1]'];
$main2 = $trackdata['artists:main[2]'];
$artists = array();
// First artist always exists
$artists[] = array('name' => $name1, 'main' => (boolean) $main1);
// Add second artist only if one exists with a non-null name
if(!is_null($name2)) {
$artists[] = array('name' => $name2, 'main' => (boolean) $main2);
}
$tracks['tracks'][] = array(
'songId' => $songId,
'title' => $title,
'ISRC' => $ISRC,
'artists' => $artists
);
}
You can use the empty function instead of is_null if you wish. It will consider names such as empty strings and the number 0 as not existing. is_null will only catch those which are strictly === null.
like this :
if (!empty($songId))
{
$tracks['tracks']['songId'] = $songId;
}
if (!empty($title))
{
$tracks['tracks']['title'] = $title;
}
and so on ...
$artists[0] = array(
'name' => $name1,
'main' => (boolean) $main1
);
if (!empty($name2)&&!empty($main2))
$artists[1] = array(
'name' => $name2,
'main' => (boolean) $main2
);
$tracks['tracks'][] = array(
'songId' => $songId,
'title' => $title,
'ISRC' => $ISRC,
'artists' => $artists
);
use array_filter to filter out unset date from an array
// assuming $artist is an array you want to scrub
$artist = array_filter($artist);
$track["artists"][] = $artist;
if ( ( ! isset( artists:name[2] ))
|| ( empty( artists:name[2] ))
) {
unset( $tracks['tracks'][ 'artists' ][ 1 ] );
}
Better
$n = 0;
while( ! empty( $trackdata[ 'artists:name[' . $n+1 . ']' ] )) {
$tracks['tracks'][ 'artists' ][ $n ][ 'name' ]
= $trackdata[ 'artists:name[' . $n+1 . ']' ];
$tracks['tracks'][ 'artists' ][ $n ][ 'main' ]
= $trackdata[ 'artists:main[' . $n+1 . ']' ];
$n++;
}

Simple question on foreach loop question with array with 2 variables. (with code)

How can I edit this foreach loop so that I will be able to use strpos to look if q is found in the label ?
The result array will contain those values.
$q may be anna or ann or reas john
<?php
$q = $_GET["q"];
if (!$q) return;
$data = Array(
Array(
'label' => 'anna c13',
'category' => 'Products'
),
Array(
'label' => 'anders andersson',
'category' => 'People'
),
Array(
'label' => 'andreas johnson',
'category' => 'People'
)
);
$result = array();
foreach ($data as $value) {
array_push($result, array(
"label" => $value["label"],
"category" => $value["category"]
));
}
$json = json_encode($result);
echo $json;
?>
This will output every array in $data where $q is somewhere in 'label'.
<?php
if( !isset( $_GET["q"] )) return;
$q = $_GET["q"];
$data = Array(
Array(
'label' => 'anna c13',
'category' => 'Products'
),
Array(
'label' => 'anders andersson',
'category' => 'People'
),
Array(
'label' => 'andreas johnson',
'category' => 'People'
)
);
$result = array();
foreach ($data as $value) {
if( strpos( $value['label'], $q ) !== false ) {
$result[] = $value;
}
}
$json = json_encode($result);
echo $json;
?>
You haven't defined keys for your $data array - so it automatically take the form of:
array(
0=>array(...),
1=>array(...),
2=>array(...)
)
This means that you're using strtolower on an int - so that's probably why it's failing.
foreach ($data as $value) {
if(strpos($value['label'], $q) !== false){
$result[] = $value;
}
}

Categories