PHP Save array in database and miss data - php

I need to save in database category like "a & b" but the model save in database just "a" miss the blank space and the &.
This is the array:
$data = array('avenvu' => $_POST['avenvu'],
'brand' => $_POST['brand'],
'category' => $_POST['category'],
'description' => $_POST['description'],
'man_women_shop'=> $_POST['man_women_shop'],
'postdatetime' => date("Y-m-d H:i:s",time()),
'publish' => 1,
'user_id' => $this->session->userdata('user_id'));
$result = $this->personal_closest->insertCloset($data);
And this is the model:
function insertCloset($data) {
$this->db->insert('personal_closest',$data);
}

Change your insertCloset function:
function insertCloset($data) {
$personal['avenvu'] = $data['avenvu'];
$personal['brand'] = $data['brand'];
$personal['category'] = $data['category'];
$personal['description'] = $data['description'];
$personal['man_women_shop'] = $data['man_women_shop'];
$personal['postdatetime'] = $data['postdatetime'];
$personal['publish'] = $data['publish'];
$personal['user_id'] = $data['user_id'];
$this->db->insert('personal_closest',$personal);
}

Related

How to insert a values into different table in a single php page?

I am inserting a record on my table after inserting to another table. This my sample code:
if(isset($_POST['submit'])){
$database = new Database();
$db = $database->getConnection();
$employee = new Employee($db);
if(!empty($first_name) && !empty($family_name) && !empty($first_name_arabic) && !empty($family_name_arabic)){
$emp_number = isset($_POST['emp_number']) && !empty($_POST['emp_number']) ? $_POST['emp_number'] : $employee->generateEmployeeNumber();
$fields = [
'reference' => $reference,
'emp_number' => $emp_number,
'first_name' => $first_name,
'middle_name' => $middle_name,
'third_name' => $third_name,
'family_name' => $family_name,
'nationality' => $nationality,
];
$employee->createOrUpdate($fields, '');
$result = $employee->selectOne('Reference', $reference);
if(!empty($_POST['passport_number']) && !empty($_POST['passport_place_issue']) && !empty($_POST['passport_date_issue']) && !empty($_POST['passport_date_expiry']) && !empty($result['id'])) {
$passport = new Passport($db);
$passport_fields = [
'passport_number' => $_POST['passport_number'],
'place_issue' => $_POST['passport_place_issue'],
'date_issue' => date_format(date_create($_POST['passport_date_issue']), 'Y-m-d'),
'date_expiry' => date_format(date_create($_POST['passport_date_expiry']), 'Y-m-d'),
'reference' => $result['reference'] ,
'employee_id' => $result['id'],
'status' => 'Active',
];
$passport->createOrUpdate($passport_fields, '');
}
}
}
but my problem is my insertion for passport table is not doing anything and no error is being return to me. As for the creatOrUpdate this is how i did:
function createOrUpdate($fields, $id){
if(is_null($id) || empty($id)){
$implodeColumns = implode(', ', array_keys($fields));
$implodePlaceholder = implode(", :", array_keys($fields));
$sql = "INSERT INTO " . $this->table_name. "($implodeColumns) VALUES(:".$implodePlaceholder.")";
echo "SQL ".$sql;
$stmt = $this->conn->prepare($sql);
foreach ($fields as $key => $value) {
$stmt->bindValue(":".$key,$value);
}
$stmt->execute();
}else{}
}
I don't know if creating a method with a same name is affecting the code, but createOeUpdate method for employee is from employee.php where createOrUpdate mehod for passport is from passport.php. Only employee is being saved in my database.
Any help is much appreciated
If the names are the same from different files you need to use namespaces like:
namespace name_of_your_main_file;
// Maybe need to add full path
// if it's not in the same folder.
use employee;
use passport;
// And use it with same names as:
employee::createOrUpdate(

How can I get the value from another form

now i'm trying to get the value from another form. But i don't know how to make it.
This is my first form:
and this is method, when we click submit in the the form1, the page will redirect to this method.
public function input_data_inserted()
{
$id_data_inserted = $this->input->post('id_data_inserted');
$date = $this->input->post('date');
$id_data = $this->input->post('id_data');
$amount= $this->input->post('amount');
$id_room = $this->input->post('id_room');
$passed = FALSE;
$checkIdData = $this->modelku->cek_idData()->result_array();
$checkIdRoom = $this->modelku->cek_idRoom()->result_array();
foreach ($cekIdData as $cID)
{
foreach ($cekIdRoom as $cIR)
{
if ($id_data == $cID['id_data'] && $id_room == $cIR['id_room'])
{
$data = array
(
'id_data_inserted' => $id_data_inserted,
'date' => $date,
'id_data' => $cID['id_data'],
'amount' => $amount,
'id_room' => $cIR['id_room'],
);
$this->modelku->input_data($data, 'table_data_inserted');
$data['table_data_inserted'] = $this->modelku->show_data('table_data_inserted')->result();
$this->modelku->increase_value($amount, $id_data);
//redirect to second form
redirect('admin/Data/data\view_detail_data');
$passed = TRUE;
break;
}
}
}
if(!$passed)
{
echo "ERORR";
}
}
And this is my second form:
Method for second form:
public function input_detail_barang()
{
$id_data = $this->input->post('id_data');
$no_inv = $this->input->post('no_inv');
$condition = $this->input->post('condition');
$data = array
(
'id_data' => $id_data,
'no_inv' => $no_inv,
'condition' => $condition
);
//I need amount from first form, because i will use it. How can i do?
}
Any Solution? Thx
After this line you can save it to session:
$data = array (
'id_data_inserted' => $id_data_inserted,
'date' => $date,
'id_data' => $cID['id_data'],
'amount' => $amount,
'id_room' => $cIR['id_room'], // You missed single quote here
);
$this->load->library('session');
$this->session->set_userdata("Firstformdata",$data);
And for show this data add this line:
$this->session->userdata("Firstformdata");

how to display dynamic array values to view from model in codeigniter

here is my model code:
foreach ($query->result() as $row)
{
$data = array(
'ptitle' =>$row->ptitle,
'technology' => $row->technology,
'description' => $row->description,
);
$this->session->set_userdata('project',$data);
}
here is my View code:
<?php
if (isset($this->session->userdata['project']))
{
$ptitle = ($this->session->userdata['project']['ptitle']);
$technology = ($this->session->userdata['project']['technology']);
$description = ($this->session->userdata['project']['description']);
}
?>
when i print array it displays
Array ( [ptitle] => opmp [technology] => hbh [description] => kg ) Array ( [ptitle] => icicse [technology] => vv [description] => bhjv ) .can someone help me to print this values in view
Setting session should be like this
$data = array(
'ptitle' => $row['ptitle'],
'technology' => $row['technology'],
'description' => $row['description'],
);
$this->session->set_userdata($data);
To retrive them use
if (isset($this->session->userdata['project']))
{
$ptitle = $this->session->userdata('ptitle');
$technology = $this->session->userdata('technology');
$description = $this->session->userdata('description');
}
If your are storing multiple as array in SESSION then you surely need foreach in your view too.
Change from
if(isset($this->session->userdata['project']))
{
$ptitle = ($this->session->userdata['project']['ptitle']);
$technology = ($this->session->userdata['project']['technology']);
$description = ($this->session->userdata['project']['description']);
}
into
if(isset($this->session->userdata['project']))
{
foreach($this->session->userdata['project'] as $project)
{
$ptitle = $project['ptitle'];
$technology = $project['technology'];
$description = $project['description'];
echo $ptitle.'<br>'.$technology.'<br>'.$description.'<br>';
}
}
Try setting your array like bellow and then pass it to session set data.
$project = array("project" =>
array(
'ptitle' => "ptitle",
'technology' => "technology",
'description' => "description",
)
);
$this->session->set_userdata($project);

Cakephp set function not passing variables from controller to the view

I'm trying to pass variable to the view and this one is very weird as the naming and directory structure is correct. Below is the function in my controller:
public function validate_apply_link(){
App::uses('CakeEmail', 'Network/Email');
$this->layout = 'blank';
$listings = $this->CareersAndJob->query("
SELECT l.sid, l.title, lp.value, u.CompanyName, u.WebSite
FROM listings l
LEFT JOIN listings_properties lp
ON lp.object_sid = l.sid
LEFT JOIN users u
ON u.sid = l.user_sid
WHERE l.active = 1
AND lp.add_parameter = 2
AND l.JobGateSenderReference IS NULL
AND u.CompanyName != 'AECOM'
ORDER BY u.CompanyName ASC
LIMIT 5
");
$doc = new DOMDocument();
ob_start();
$listing_count = count($listings);
echo nl2br("Checking $listing_count active jobs...\n\n");
$i=0;
foreach($listings as $listing){
$sid = $listing['l']['sid'];
$url = $listing['lp']['value'];
$company_name = $listing['u']['CompanyName'];
$title = htmlspecialchars($listing['l']['title']);
$length = strpos($title, "-");
if($length != 0){
$title = substr($title, 0, $length-1);
}
$title = substr($title, 0, $length-1);
$title = substr($title, 0, 10);
$data = $this->curl($url);
$check_pdf = strpos($data['info']['content_type'], "pdf");
if($check_pdf != false){
$outputs['data'][$i]['url'] = $url;
$outputs['data'][$i]['sid'] = $sid;
$outputs['data'][$i]['title'] = $title;
$outputs['data'][$i]['company_name'] = $company_name;
$outputs['data'][$i]['our_link'] = "http://careersandjobs.com.au/display-job/{$sid}";
$outputs['data'][$i]['content_type'] = $data['info']['content_type'];
$outputs['data'][$i]['data_type'] = 'pdf';
$i++;
continue;
}
#$doc->loadHTML($data['results']);
$html = $doc->saveHTML();
$xpath = new DOMXpath($doc);
$body = $doc->getElementsByTagName('body')->item(0);
$parsed_url = parse_url($url);
switch($parsed_url['host']){
case "www.michaelpage.com.au":
parse_str($url);
$exist = $xpath->query("//*[contains(#value,'{$ref}')]");
break;
case "https://vacancies.mackay.qld.gov.au":
parse_str($url);
$exist = $xpath->query("//*[contains(#value,'{$title}')]");
break;
default:
$exist = $xpath->query("//*[contains(text(),'{$title}')]");
break;
}
if($exist->length == 0){
if(strpos($url, '#') == false){
$outputs['data'][$i]['url'] = $url;
$outputs['data'][$i]['sid'] = $sid;
$outputs['data'][$i]['title'] = $title;
$outputs['data'][$i]['company_name'] = $company_name;
$outputs['data'][$i]['our_link'] = "http://careersandjobs.com.au/display-job/{$sid}";
$outputs['data'][$i]['content_type'] = $data['info']['content_type'];
$response_code = $this->http_response_codes($data['info']['http_code']);
$outputs['data'][$i]['response_code'] = $response_code;
$outputs['data'][$i]['data_type'] = 'title_not_found';
}else{
$outputs['data'][$i]['data_type'] = 'no_iframe';
}
$i++;
}
flush();
ob_flush();
}
$this->set(compact('outputs'));
}
I can do pr on the outputs variable in the view but this outputs to NULL but when I delete the entire bunch of code inside the controller function and just pass a test variable through it works.
Is there something wrong with the function that I am not aware of?
No errors were found in the above function by the way
app/Controller/CareersAndJobsController.php (line 1048)
array(
'data' => array(
(int) 0 => array(
'url' => 'http://bawbawshire.currentjobs.com.au/cvbuilder/apply+for+this+job/no/1225055',
'sid' => '3649',
'title' => 'Graduate P',
'company_name' => 'Baw Baw Shire Council',
'our_link' => 'http://careersandjobs.com.au/display-job/3649',
'content_type' => 'text/html; charset=utf-8',
'response_code' => 'OK',
'data_type' => 'title_not_found'
),
(int) 1 => array(
'url' => 'http://bawbawshire.currentjobs.com.au/cvbuilder/apply+for+this+job/no/1225724',
'sid' => '3726',
'title' => 'Program &a',
'company_name' => 'Baw Baw Shire Council',
'our_link' => 'http://careersandjobs.com.au/display-job/3726',
'content_type' => 'text/html; charset=utf-8',
'response_code' => 'OK',
'data_type' => 'title_not_found'
),
(int) 2 => array(
'url' => 'http://bawbawshire.currentjobs.com.au/cvbuilder/apply+for+this+job/no/1225826',
'sid' => '3727',
'title' => 'Road Netwo',
'company_name' => 'Baw Baw Shire Council',
'our_link' => 'http://careersandjobs.com.au/display-job/3727',
'content_type' => 'text/html; charset=utf-8',
'response_code' => 'OK',
'data_type' => 'title_not_found'
)
)
)
This is what I am getting from outputs variable just before it gets set by the set function in controller
Any reason you chose to use CakePHP? Because you seem to not make use of its functionality!
You're using literal SQL queries, therefore basically skipping the Models functionality.
You're outputting your content from your Controller? Be careful when using output buffering, this may conflict with CakePHP's inner workings, which also relies on output buffering in many cases. Because you're already outputting the content here (ob_flush()), you'll be outputting your content before your View is reached..
Normally I would point to specific points in the manual, however, because there's so much wrong here, I would suggest to start reading at the beginning

Fetch array using both if and while doesn't work

Basically I have 2 methods in the same class, getMovie and getGenres. They are very similar but One doesn't return what I expect.
Here's getMovie method:
public function getMovie($argType, $arg){
$movieQuery = "SELECT id,
rt_id,
imdb_id,
url,
rt_url,
type,
adult,
DATE_FORMAT(release_date, '%Y') AS year,
date_added,
title,
runtime,
budget,
revenue,
homepage,
rating,
tagline,
overview,
popularity,
image,
backdrop,
trailer
FROM movies
WHERE " . $argType . " = " . $arg;
$movieResult = $this->_query($movieQuery);
$movies = array();
if($movieResult->fetch_array(MYSQLI_ASSOC)){
while($m = $movieResult->fetch_array(MYSQLI_ASSOC)){
$movies[] = array( 'title' => $m['title'],
'duplicate' => $m['duplicate'],
'url' => $m['url'],
'rt_url' => $m['rt_url'],
'release_date' => $m['release_date'],
'date_added' => $m['date_added'],
'type' => 'movie',
'adult' => $m['adult'],
'id' => $id,
'rt_id' => $m['rt_id'],
'imdb_id' => $m['imdb_id'],
'rating' => $m['rating'],
'tagline' => $m['tagline'],
'overview' => $m['overview'],
'popularity' => $m['popularity'],
'runtime' => $m['runtime'],
'budget' => $m['budget'],
'revenue' => $m['revenue'],
'homepage' => $m['homepage'],
'image' => $m['image'],
'backdrop' => $m['backdrop'],
'trailer' => $m['trailer'] );
}
return $movies;
}
else{
return false;
}
Here's getGenres method:
public function getGenres($movieId = NULL){
$genresQuery = "";
if($movieId != NULL){
$genresQuery = "SELECT id,
name
FROM genres
WHERE id = ANY (
SELECT genre_id
FROM movie_genres
WHERE movie_id = " . $movieId . ")";
}
else{
$genresQuery = "SELECT id,
name
FROM genres";
}
$genresResult = $this->_query($genresQuery);
$genres = array();
if($genresResult->fetch_array(MYSQLI_ASSOC)){
while($genre = $genresResult->fetch_array(MYSQLI_ASSOC)){
$genres[] = array( 'id' => $genre['id'],
'name' => $genre['name'] );
}
return $genres;
}
else{
return false;
}
}
And here's how I call them:
$mov = $movie->getMovie(2207);
print_r($mov); // output: Array()
$gen = $movie->getGenres(2207);
print_r($gen); // output: Array(values inside)
Both queries do actually return expected values but getMovies method doesn't work with the if statement. It works fine if I just have while loop.
I am using if as well as while as I heard that while loop can sometimes execute even when there's not values. Is there any truth to this? If there is indeed a reason to use an if statement as well as wile loop then why doesn't it work with getMovies method?
Edit 1: I tried storing the array like so but that resulted in a memory related error:
$r = $genresResult->fetch_array(MYSQLI_ASSOC);
if($r){
while($r){
$genres[] = array( 'id' => $genre['id'],
'name' => $genre['name'] );
}
return $genres;
}
I am using if as well as while as I heard that while loop can sometimes execute even when there's not values. Is there any truth to this?
No, according to the php manual mysqli_result::fetch_array returns an array of strings that corresponds to the fetched row or NULL if there are no more rows in resultset.
Null is falsy so the while loop will not be entered.
Although the if statement is unnecessary if you had one you would use mysqli_result::$num_rows to check if the query returned any rows.
if($movieResult->num_rows > 0){
while($m = $movieResult->fetch_array(MYSQLI_ASSOC)){
...
}
}

Categories