I try to make a function to insert more fields in database.
I find an example, but maybe more parameters is deprecated...or i have an error.
Here is my code:
private function _setUserPersonalDetails($blog_id, $personal_data, $operation = 'insert') {
global $wpdb;
// Strip any html tags from the about and address fields.
$tmp = array();
foreach ($personal_data as $key => $val) {
if (($key === 'about') || ($key === 'address')) {
$tmp[$key] = strip_tags($val);
}
else {
$tmp[$key] = $val;
}
}
$personal_data = $tmp;
if ($operation == 'insert') {
// Save personal data
$encoded_data = json_encode($personal_data);
$type = 'personal_data';
$q = $wpdb->prepare('INSERT INTO wp0_users_conta_data (blog_id, type, data) VALUES (%d, %s, %s)', $blog_id, $type, $encoded_data);
$wpdb->query($q);
}
if ($operation == 'update') {
// Update personal data
$encoded_data = json_encode($personal_data);
$type = 'personal_data';
$q = $wpdb->prepare('UPDATE wp0_users_conta_data set data=%s where blog_id=%d and type=%s', $encoded_data, $blog_id, $type);
$wpdb->query($q);
}
}
}
I spent more one week to solve the problem, but i don't find any solutions. I appreciate any helps. Thank you!
Related
i am working on my own restfull api. I have read many article about, but i come out more confused that before.
fist question:
in PUT request is correct to use question mark (?) ex:
http://myapi.me/testApi/v5/create/places?address=Five&building=old
or i must to use
http://myapi.me/testApi/v5/create/places/address=Five&building=old
if the second is the correct way, how i can explode the query string for create my insert statement? my code work well with (?). But curl command does not want to enter the record. So i need to modify the script to reflect the correct way with(/) instead of (?).
Please help...
my code:
$body = file_get_contents("php://input");
$content_type = false;
if(isset($_SERVER['CONTENT_TYPE'])) {
$content_type = $_SERVER['CONTENT_TYPE'];
// echo $content_type;
}
switch($content_type) {
//other case...
case "application/x-www-form-urlencoded":
parse_str($body, $postvars);
foreach($postvars as $field => $value) {
$parameters[$field] = $value;
}
$this->format = "html";
break;
default:
// we could parse other supported formats here
break;
}
$this->parameters = $parameters;
private function createRecord(){
if($this->get_request_method() != "PUT"){
$this->response('',406);
}
$table = strtolower(trim(str_replace("/", "", $_REQUEST['rquest'])));
/*
$Q = explode("/", $_SERVER["rquest"]);
print_r(array_values($Q));
echo "\n";
*/
$uri = $this->parameters;
if($uri){
array_shift($uri);
foreach( $uri as $k => $v )
{
$aKeyPholder[]= $k;
$aKey[]= ':'.$k;
}
$aKeyPholder= implode(',', $aKeyPholder);
$aKey= implode(',', $aKey);
$insert = "INSERT INTO '$table' ($aKeyPholder) VALUES ($aKey)";
// echo "insert=$insert\n";
$stmt = $this->db->prepare($insert);
foreach($uri as $k => &$v){
$stmt->bindParam(':'.$k, $v, PDO::PARAM_STR);
}
//$stmt->execute();
if ($stmt->execute()) { echo "Record succesfully created!";}
$this->response($this->json($success),200);
}
else{
$this->response('',204); // If no records "No Content" status
}
}
I am using Codeigniter with cloudflare and getting 520 error while storing user value in session during login.
Here is login function:
function check_login_submit($post_data) {
if ($post_data) {
$mob = trim($post_data['mob']);
$password = trim($post_data['password']);
$sql = "Select * from table where phone='$mob' and password='$password'";
$query = $this->db->query($sql);
$user = $query->row();
if ($query->num_rows() == 1) {
if ($user->status == 1)
{
$this->session->set_userdata('mem_id', $user->id);
$this->session->set_userdata('mem_last_login_date', $user->last_login_date);
$this->session->set_userdata('mem_created_on', $user->created_on);
//-- Update last login of successfull Login
$sql = "update table set last_login_date = NOW() where id=$user->id";
$query = $this->db->query($sql);
return TRUE;
}
}
else {
return FALSE;
}
}
}
If i will stop the storing value into session user data than it will working fine however with session cloudflare give me 502 error page.
Please advise
Thanks in advance for your time and support.
If anyone else runs into this problem, I came up with a solution that involves extending the core Session library that ultimately reduces the number of calls to sess_write() and by extension, _set_cookie().
MY_Session.php:
class MY_Session extends CI_Session {
function set_userdata($newdata = array(), $newval = '', $write_session = true)
{
if (is_string($newdata))
{
$newdata = array($newdata => $newval);
}
if (count($newdata) > 0)
{
foreach ($newdata as $key => $val)
{
$this->userdata[$key] = $val;
}
}
// Do not write the session (set the cookies) unless explicitly specified
if ($write_session) {
$this->sess_write();
}
}
function set_flashdata($newdata = array(), $newval = '')
{
if (is_string($newdata))
{
$newdata = array($newdata => $newval);
}
if (count($newdata) > 0)
{
foreach ($newdata as $key => $val)
{
$flashdata_key = $this->flashdata_key.':new:'.$key;
$this->set_userdata($flashdata_key, $val, false); // Do not update the cookie in the foreach
}
}
// Save the cookie now that all userdata has been set
$this->sess_write();
}
function _flashdata_mark()
{
$userdata = $this->all_userdata();
$newUserData = array();
$userDataToUnset = array();
foreach ($userdata as $name => $value)
{
$parts = explode(':new:', $name);
if (is_array($parts) && count($parts) === 2)
{
$new_name = $this->flashdata_key.':old:'.$parts[1];
$newUserData[$new_name] = $value;
$userDataToUnset[$name] = '';
// Cookies were originally set in this loop. Moved to the end of the function
}
}
// Save all changes outside of the loop
if (count($newUserData) > 0) {
$this->set_userdata($newUserData);
$this->unset_userdata($userDataToUnset);
}
}
}
A 520 error generally indicates that there are large cookies or headers being returned that hit proxy buffer limits on our end. A HAR file send to our support team will help us figure out what the issue is.
Thank you StackOverflow experts for looking at my question.
First, It is possible this question has been asked before but my situation is a bit unique. So, please hear me out.
When our users want to edit an existing record, they would also like to have the ability to delete an existing pdf file if one exists before adding a new one.
To display an existing file, I use this code.
<td class="td_input_form">
<?php
// if the BidIDFile is empty,
if(empty($result["BidIDFile"]))
{
//then show file upload field for Bid File
echo '<input type="file" name="BidIDFile[]" size="50">';
}
else
{
// Bid file already upload, show checkbox to delete it.
echo '<input type="checkbox" name="delete[]" value="'.$result["BidIDFile"].'"> (delete)
'.$result["BidIDFile"].'';
}
</td>
Then to delete this file, I use the following code:
// Connect to SQL Server database
include("connections/Connect.php");
// Connect to SQL Server database
include("connections/Connect.php");
$strsID = isset($_GET["Id"]) ? $_GET["Id"] : null;
if(isset($_POST['delete']))
{
// whilelisted table columns
$fileColumnsInTable = array( 'BidIDFile', 'TabSheet', 'SignInSheet', 'XConnect',
'Addend1', 'Addend2','Addend3','Addend4','Addend5', 'Addend6');
$fileColumns = array();
foreach ($_POST['delete'] as $fileColumn)
{
if(in_array($fileColumn, $fileColumnsInTable))
$fileColumns[] = $fileColumn;
}
// get the file paths for each file to be deleted
$stmts = "SELECT " . implode(', ', $fileColumns) . " FROM bids WHERE ID = ? ";
$querys = sqlsrv_query( $conn, $stmts, array($strsID));
$files = sqlsrv_fetch_array($querys,SQLSRV_FETCH_ROW);
// loop over the files returned by the query
foreach ($files as $file )
{
//delete file
unlink($file);
}
// now remove the values from the table
$stmts = "UPDATE bids SET " . impload(' = '', ', $fields) . " WHERE ID = ? ";
$querys = sqlsrv_query( $conn, $stmts, array($strsID));
This works fine. However, the edit file points to an existing file with an INSERT and UPDATE operation in this one file (great thanks to rasclatt) and I am having problem integrating the two together.
Can someone please help with integrating the two files into one?
Thanks in advance for your assistance.
Here is the INSERT and UPDATE file:
<?php
error_reporting(E_ALL);
class ProcessBid
{
public $data;
public $statement;
public $where_vals;
protected $keyname;
protected $conn;
public function __construct($conn = false)
{
$this->conn = $conn;
}
public function SaveData($request = array(),$skip = false,$keyname = 'post')
{
$this->keyname = $keyname;
$this->data[$this->keyname] = $this->FilterRequest($request,$skip);
return $this;
}
public function FilterRequest($request = array(), $skip = false)
{
// See how many post variables are being sent
if(count($request) > 0) {
// Loop through post
foreach($request as $key => $value) {
// Use the skip
if($skip == false || (is_array($skip) && !in_array($key,$skip))) {
// Create insert values
$vals['vals'][] = "'".ms_escape_string($value)."'";
// Create insert columns
$vals['cols'][] = "".str_replace("txt","",$key)."";
// For good measure, create an update string
$vals['update'][] = "".str_replace("txt","",$key)."".' = '."'".ms_escape_string($value)."'";
// For modern day binding, you can use this array
$vals['bind']['cols'][] = "".$key."";
$vals['bind']['cols_bind'][] = ":".$key;
$vals['bind']['vals'][":".$key] = $value;
$vals['bind']['update'][] = "".$key.' = :'.$key;
}
}
}
return (isset($vals))? $vals:false;
}
public function AddFiles($name = 'item')
{
// If the files array has been set
if(isset($_FILES[$name]['name']) && !empty($_FILES[$name]['name'])) {
// Remove empties
$_FILES[$name]['name'] = array_filter($_FILES[$name]['name']);
$_FILES[$name]['type'] = array_filter($_FILES[$name]['type']);
$_FILES[$name]['size'] = array_filter($_FILES[$name]['size']);
$_FILES[$name]['tmp_name'] = array_filter($_FILES[$name]['tmp_name']);
// we need to differentiate our type array names
$use_name = ($name == 'item')? 'Addend':$name;
// To start at Addendum1, create an $a value of 1
$a = 1;
if(!empty($_FILES[$name]['tmp_name'])) {
foreach($_FILES[$name]['name'] as $i => $value ) {
$file_name = ms_escape_string($_FILES[$name]['name'][$i]);
$file_size = $_FILES[$name]['size'][$i];
$file_tmp = $_FILES[$name]['tmp_name'][$i];
$file_type = $_FILES[$name]['type'][$i];
if(move_uploaded_file($_FILES[$name]['tmp_name'][$i], $this->target.$file_name)) {
// Format the key values for addendum
if($name == 'item')
$arr[$use_name.$a] = $file_name;
// Format the key values for others
else
$arr[$use_name] = $file_name;
$sql = $this->FilterRequest($arr);
// Auto increment the $a value
$a++;
}
}
}
}
if(isset($sql) && (isset($i) && $i == (count($_FILES[$name]['tmp_name'])-1)))
$this->data[$name] = $sql;
return $this;
}
public function SaveFolder($target = '../uploads/')
{
$this->target = $target;
// Makes the folder if not already made.
if(!is_dir($this->target))
mkdir($this->target,0755,true);
return $this;
}
public function where($array = array())
{
$this->where_vals = NULL;
if(is_array($array) && !empty($array)) {
foreach($array as $key => $value) {
$this->where_vals[] = $key." = '".ms_escape_string($value)."'";
}
}
return $this;
}
public function UpdateQuery()
{
$this->data = array_filter($this->data);
if(empty($this->data)) {
$this->statement = false;
return $this;
}
if(isset($this->data) && !empty($this->data)) {
foreach($this->data as $name => $arr) {
$update[] = implode(",",$arr['update']);
}
}
$vars = (isset($update) && is_array($update))? implode(",",$update):"";
// Check that both columns and values are set
$this->statement = (isset($update) && !empty($update))? "update bids set ".implode(",",$update):false;
if(isset($this->where_vals) && !empty($this->where_vals)) {
$this->statement .= " where ".implode(" and ",$this->where_vals);
}
return $this;
}
public function SelectQuery($select = "*",$table = 'bids')
{
$stmt = (is_array($select) && !empty($select))? implode(",",$select):$select;
$this->statement = "select ".$stmt." from ".$table;
return $this;
}
public function InsertQuery($table = 'bids')
{
$this->data = array_filter($this->data);
if(empty($this->data)) {
$this->statement = false;
return $this;
}
$this->statement = "insert into ".$table;
if(isset($this->data) && !empty($this->data)) {
foreach($this->data as $name => $arr) {
$insert['cols'][] = implode(",",$arr['cols']);
$insert['vals'][] = implode(",",$arr['vals']);
}
}
$this->statement .= '(';
$this->statement .= (isset($insert['cols']) && is_array($insert['cols']))? implode(",",$insert['cols']):"";
$this->statement .= ") VALUES (";
$this->statement .= (isset($insert['vals']) && is_array($insert['vals']))? implode(",",$insert['vals']):"";
$this->statement .= ")";
return $this;
}
}
include("../Connections/Connect.php");
function render_error($settings = array("title"=>"Failed","body"=>"Sorry, your submission failed. Please go back and fill out all required information."))
{ ?>
<h2><?php echo (isset($settings['title']))? $settings['title']:"Error"; ?></h2>
<p><?php echo (isset($settings['body']))? $settings['body']:"An unknown error occurred."; ?></p>
<?php
}
// this function is used to sanitize code against sql injection attack.
function ms_escape_string($data)
{
if(!isset($data) || empty($data))
return "";
if(is_numeric($data))
return $data;
$non_displayables[] = '/%0[0-8bcef]/'; // url encoded 00-08, 11, 12, 14, 15
$non_displayables[] = '/%1[0-9a-f]/'; // url encoded 16-31
$non_displayables[] = '/[\x00-\x08]/'; // 00-08
$non_displayables[] = '/\x0b/'; // 11
$non_displayables[] = '/\x0c/'; // 12
$non_displayables[] = '/[\x0e-\x1f]/'; // 14-31
foreach($non_displayables as $regex)
$data = preg_replace($regex,'',$data);
$data = str_replace("'","''",$data);
return $data;
}
// New bid save engine is required for both sql statement generations
$BidSet = new ProcessBid($conn);
$strId = null;
if(isset($_POST["Id"]))
{
$strId = $_POST["Id"];
//echo $strId;
}
If ($strId == "") {
//echo "This is an insert statement";
// This will generate an insert query
$insert = $BidSet->SaveData($_POST)
->SaveFolder('../uploads/')
->AddFiles('BidIDFile')
->AddFiles('item')
->AddFiles('SignInSheet')
->AddFiles('TabSheet')
->AddFiles('Xcontract')
->InsertQuery()
->statement;
// Check that statement is not empty
if($insert != false) {
sqlsrv_query($conn,$insert);
render_error(array("title"=>"Bid Successfully Saved!","body"=>'Go back to Solicitation screen'));
$err = false;
}
//echo '<pre>';
//print_r($insert);
// echo '</pre>';
}
else
{
//echo "This is an update statement";
// This will generate an update query
$update = $BidSet->SaveData($_POST,array("Id"))
->SaveFolder('../uploads/')
->AddFiles('BidIDFile')
->AddFiles('item')
->AddFiles('SignInSheet')
->AddFiles('TabSheet')
->AddFiles('Xcontract')
->where(array("Id"=>$_POST["Id"]))
->UpdateQuery()
->statement;
//echo '<pre>';
//print_r($update);
//echo '</pre>';
// Check that statement is not empty
if($update != false) {
sqlsrv_query($conn,$update);
render_error(array("title"=>"Bid Successfully Saved!","body"=>'Go back to admin screen'));
$err = false;
}
}
// This will post an error if the query fails
if((isset($err) && $err == true) || !isset($err))
render_error(); ?>
I'm sending information from an html form into a php page where I am checking the information against a mysql database.
Right now there are 5 checkboxes plus other variables in the form*(searchbar, radiobuttons, etc)*.
Is there a way to write the conditions without having to have a specific if statement for each path? Otherwise I have to write each specific path, and thats a lot of typing :/
Right now it would look something like:
if($orderBy == "price")
{
if($searchBy == "begin")
{
if($_POST["gameType"] == "RTS")
{
$sql = "select * from gametbl where gme_title like '$title%' and where gme_type = 'RTS' ORDER BY gme_price DESC";
}
}
and for all the conditions, thats going to take way to long. Is there a better way of doing this?
This is essentially what I mean by doing a method chain. You can specify within each method what to do if a specific variable is fed into it. It would dynamically write a statement based on single values. This a series of guesses based on your only bit of code:
<?php
class SQLBuilder
{
protected $order;
protected $sql;
public $statement;
public function Select($columns = false)
{
$this->sql[] = "select";
if(is_array($columns))
$this->sql[] = implode(",",$columns);
else
$this->sql[] = ($columns != false)? $columns:"*";
return $this;
}
public function Where($array = false,$like = false)
{
if($array == false)
return $this;
if(in_array("where", $this->sql))
$this->sql[] = "and";
$this->sql[] = "where";
if(is_array($array)) {
foreach($array as $key => $value)
$where[] = ($like != false)? "`$key` like '%".$value."$'":"`$key` = '".$value."'";
if(isset($where))
$this->sql[] = implode("and",$where);
}
else
$this->sql[] = $array;
return $this;
}
public function From($table = 'gametbl')
{
$this->sql[] = "from";
$this->sql[] = "`$table`";
return $this;
}
public function OrderBy($value = false,$order = false)
{
if($value != false) {
// I am guessing this is order
$heiarchy = ($order == 'begin')? " DESC":" ASC";
if($value == 'price')
$order = "`gme_price`".$heiarchy;
}
if(isset($order))
$this->sql[] = "order by ".$order;
return $this;
}
public function Fetch($return_obj = false)
{
$this->statement = implode(" ",$this->sql);
return ($return_obj != false)? $this:$this->statement;
}
}
// I don't know what your form fields are called, these are just for instances
$_POST['gameType'] = 'RTS';
$_POST['gameTitle'] = 'whatever game';
$_POST['orderBy'] = 'price';
$_POST['list'] = 'begin';
// Create instance of builder
$SQLBuilder = new SQLBuilder();
// This will just accumulate the statement based on fed-in variables.
$sql = $SQLBuilder->Select()
->From()
->Where(array("gme_title"=>$_POST['gameTitle']),true)
->Where(array("gme_type"=>$_POST['gameType']))
->OrderBy($_POST['orderBy'],$_POST['list'])
->Fetch();
echo $sql;
?>
GIVES YOU:
select * from `gametbl` where `gme_title` like '%whatever game$' and where `gme_type` = 'RTS' order by `gme_price` DESC
Codeigniter when i submit more than one option of form_multiselect(), Only just the last one that saved on database.
in my view :
<label>Trimestres :</label>
<div class="controls" >
<?php $options = array(
'trim1' => ' Premier trimestre (Janv,Fév,Mars)',
'trim2' => ' Deuxiéme trimestre (Avril,Mai,Juin)',
'trim3' => ' Troisiéme trimestre (Juill,Aout,Sept)',
'trim4' => ' Quatriéme trimestre (Oct,Nov,Déc)',
);
echo form_multiselect('trimestres', $options , $this->input->post('trimestres') ? $this->input->post('trimestres') : $participant_sport->trimestres, 'id="trim"'); ?>
</div>
</div>
in my controller :
public function inscriresport ($id = NULL)
{
// Fetch a participant or set a new one
if ($id) {
$this->data['participant_sport'] = $this->participantsport_m->get($id);
count($this->data['participant_sport']) || $this->data['errors'][] = 'participant non trouvé';
}
else {
$this->data['participant_sport'] = $this->participantsport_m->get_new();
}
// Process the form
$this->participantsport_m->array_from_post(array('matricule', 'nom', 'prenom', 'beneficiaire', 'sexe', 'telephone', 'date_naissance', 'date_inscription_sport', 'trimestres' ,'sport_montant_paye', 'sport_debut_periode', 'sport_fin_periode'));
$this->participantsport_m->save($data, $id);
redirect('admin/agent/profile/3608');
}
// Load the view
$this->data['subview'] = 'admin/agent/inscriresport';
$this->load->view('admin/_layout_main', $this->data);
}
The function array_from_post() is defined on application\core\MY_Model.php :
public function array_from_post($fields){
$data = array();
foreach ($fields as $field) {
$data[$field] = $this->input->post($field);
}
return $data;
}
in my model :
public function get_new()
{
$participant_sport = new stdClass();
$participant_sport->matricule = '';
$participant_sport->nom = '';
$participant_sport->prenom = '';
$participant_sport->beneficiaire = '';
$participant_sport->sexe = '';
$participant_sport->telephone = '';
$participant_sport->date_naissance = '';
$participant_sport->date_inscription_sport = '';
$participant_sport->trimestres = '';
$participant_sport->sport_montant_paye = '';
$participant_sport->sport_debut_periode = '';
$participant_sport->sport_fin_periode = '';
return $participant_sport;
}
Any help Please? i think that must be an array but i don't know how to do it?
i thing that i must do something like that :
foreach($_POST["strategylist[]"] as $s) {
# do the insert here, but use $s instead of $_POST["strategylist[]"]
$result=mysql_query("INSERT INTO sslink (study_id, strategyname) " .
"VALUES ('$id','" . join(",",$s) . "')")
or die("Insert Error: ".mysql_error());
}
to insert more than one option selected in one row but i don't know how to do it in codeigniter
the get() function :
public function get($id = NULL, $single = FALSE){
if ($id != NULL) {
$filter = $this->_primary_filter;
$id = $filter($id);
$this->db->where($this->_primary_key, $id);
$method = 'row';
}
elseif($single == TRUE) {
$method = 'row';
}
else {
$method = 'result';
}
if (!count($this->db->ar_orderby)) {
$this->db->order_by($this->_order_by);
}
return $this->db->get($this->_table_name)->$method();
}
If select name (in HTML tag) is trimestres it will always remember last selection. Use trimestres[] as a name to get array with all selected values`
<select name="trimestres[]" multiple …
By the way:
I don't know how array_from_post() works but it has to change trimestres[] values to one string to save all of them in one column. It is hard to search/add/delete one value if all values are in one string. It is "SQL Antipattern". You could do another table in database for trimestres - one value in one row.
Edit:
It will change all arrays into string with elements connected by ,. Not tested.
public function array_from_post($fields){
$data = array();
foreach ($fields as $field) {
// print_r($this->input->post($field));
if( is_array( $this->input->post($field) ) ) {
$data[$field] = join(",", $this->input->post($field));
} else {
$data[$field] = $this->input->post($field);
}
// print_r($data[$field]);
}
return $data;
}
Edit:
Not tested.
public function inscriresport ($id = NULL)
{
// Fetch a participant or set a new one
if ($id) {
$this->data['participant_sport'] = $this->participantsport_m->get($id);
count($this->data['participant_sport']) || $this->data['errors'][] = 'participant non trouvé';
// explode to array
// print_r($this->data['participant_sport']->trimestres); // test before explode
// $this->data['participant_sport']['trimestres'] = explode(",", $this->data['participant_sport']['trimestres']);
$this->data['participant_sport']->trimestres = explode(",", $this->data['participant_sport']->trimestres);
// print_r($this->data['participant_sport']->trimestres); // test after explode
} else {
$this->data['participant_sport'] = $this->participantsport_m->get_new();
}
// rest of code
}
There is a easy way to solve this problem that I found today.
you have to serialize the $_POST['trimestres'] array just after array_form_post .
the this array will save to database as a serialize string.
public function inscriresport ($id = NULL)
{
// Fetch a participant or set a new one
if ($id) {
$this->data['participant_sport'] = $this->participantsport_m->get($id);
count($this->data['participant_sport']) || $this->data['errors'][] = 'participant non trouvé';
}
else {
$this->data['participant_sport'] = $this->participantsport_m->get_new();
}
// Process the form
$this->participantsport_m->array_from_post(array('matricule', 'nom', 'prenom', 'beneficiaire', 'sexe', 'telephone', 'date_naissance', 'date_inscription_sport', 'trimestres' ,'sport_montant_paye', 'sport_debut_periode', 'sport_fin_periode'));
$data['trimestres'] = serialize($_POST['trimestres']);
$this->participantsport_m->save($data, $id);
redirect('admin/agent/profile/3608');
}
// Load the view
$this->data['subview'] = 'admin/agent/inscriresport';
$this->load->view('admin/_layout_main', $this->data);
}
When you just need this data back form database just use php unserialize() function .
Hope it will help to do this easily ....
-thanks