i want to add an entrance (using a form) into a Mysql table using POO.
Here is what i did :
My class :
<?php
class portfolio{
public $title;
public $img_desk;
public $img_tablet;
public $img_phone;
public $id;
public function __construct($title, $img_desk, $img_tablet, $img_phone, $port_id){
$this->title = $title;
$this->img_desk = $img_desk;
$this->img_tablet = $img_tablet;
$this->img_phone = $img_phone;
$this->id = $port_id;
}
public function getPortfolio($id){
$reponse = $bdd->query('SELECT * FROM designer WHERE id = $id');
$portfolio = $reponse->fetch();
$a = new portfolio($portfolio['title'], $portfolio['img_desk'], $portfolio['img_tablet'], $portfolio['phone'], $portfolio['id']);
return $a;
}
public function addPortfolio($title, $img_desk, $img_tablet, $img_phone){
$add = $bdd->exec('INSERT INTO designer(title, img_desk, img_tablet, img_phone) VALUES(:title, :img_desk, :img_tablet, :img_phone)');
$add->execute(array( // _> was used.!!!
'title' => $title,
'img_desk' => $img_desk['name'],
'img_tablet' => $img_tablet['name'],
'img_phone' => $img_phone['name']
// imgs...
));
if (isset($img_desk) AND $img_desk['error'] == 0){
// Testons si le fichier n'est pas trop gros
if ($img_desk['size'] <= 3000000)
{
require("class/img.class.php");
// Testons si l'extension est autorisée
$infosfichier = pathinfo($img_desk['name']);
$extension_upload = $infosfichier['extension'];
$extensions_autorisees = array('jpg', 'jpeg', 'gif', 'png');
if (in_array($extension_upload, $extensions_autorisees))
{
// On peut valider le fichier et le stocker définitivement
move_uploaded_file($img_desk['tmp_name'], 'img/port/' . basename($img_desk['name']));
}
}
}
echo 'Élement ajouté';
}
public function editPortfolio($old, $new){
$edit = $bdd->prepare('UPDATE designer SET title = :title, img_desk = :img_desk, img_tablet = :img_tablet, img_phone = :img_phone WHERE id = $old->id ');
$edit->execute(array(
'title' => $new->title,
'img_desk' => $new->img_desk,
'img_tablet' => $new->img_tablet,
'img_phone' => $new->img_phone
));
}
public function deletePortfolio($cible){
//DELETE FROM designer WHERE id = $cible->id;
}
public function getAllPortfolio(){
//$reponse = $bdd->query('SELECT * FROM designer');
//$donnees = $reponse->fetch();
//return $donnees;
}
}
?>
And here is my using on a php file containing the form :
<?php
include('class/portfolio.class.php');
if(isset($_POST['title'])){
addPortfolio($_POST['title'], $_FILES['img_desk'], $_FILES['img_tablet'], $_FILES['phone']);
echo 'ok';
}else{
?>
<form method="post" action="admin.php" enctype="multipart/form-data">
<input type="text" placeholder="Titre" name="title"><br>
<input type="file" name="img_desk"><br>
<input type="file" name="img_tablet"><br>
<input type="file" name="img_phone"><br>
<input type="submit" value="Ajouter" name="ok">
</form>
<?php
}
?>
And it's telling me :
Fatal error: Call to undefined function addPortfolio() in C:\wamp\www\designers\admin.php on line 47
Would someone explain me please ? I know i'm doing things wrong but i'm actually learning OOP.
Thank you in advance : ).
You need to create an object first of the class portfolio
So, the corrected code should be:
// YOUR CODE HERE.
$portfolio = new portfolio;
if(isset($_POST['title'])){
$portfolio->addPortfolio($_POST['title'], $_FILES['img_desk'], $_FILES['img_tablet'], $_FILES['phone']);
echo 'ok';
}else{
// YOUR CODE HERE
Or you can directly use the function like this
provided the function is declared Static but since you have personal data so not recommended!
portfolio::addPortfolio();
Related
Hello every {body] !
I have a simple "members" table to which I normally add rows with the function bellow.
The problem is that when I call the read function, it returns each column to me twice. Like this:
The weirdest thing is that all the columns are correct except "phone", it returns me '1' instead of an empty string.
Can anybody help me please ?
Here is the read function:
function db_read($columnToRead, $table, $targetColumn, $targetValue) {
//connecting to database
include('dbConnection.php');
//reading data
$result = $tilelli->prepare('SELECT '.$columnToRead.' FROM '.$table.' WHERE '.$targetColumn.' = ? LIMIT 1');
if ($result->execute(array($targetValue))) {
return $result->fetch();
} else {
return "Accès à la base de données refusé!";
}
}
And here is the calling method:
//reading member
$member = db_read("*", "members", "link", $_SESSION["member"]["link"]);
print_r($member);
exit;
#BoykeFerdinandes
Yes, when I print_r($member), it displays the phone correctly, but look at the web page :
PHP code
HTML result
Here is the "info()" function:
//inserting a profile info
function info($svg, $text, $buttonHref, $buttonLabel, $rounded = false, $previewable = false, $notif = "") {
$style = "";
$class = "";
$notification = '<span class="notifCounter">'.$notif.'</span>';
if ($rounded)
$style = 'style="border-radius: 50%;"';
if ($previewable)
$class = ' previewable';
echo '<div class="info">
<p class="info_icon_container">
<img src="'.$svg.'" class="info_icon'.$class.'" '.$style.' />
</p>
<p class="info_text">
'.$text.'
</p>
<p class="info_alter" onclick="window.location=\''.$buttonHref.'\';">
'.$buttonLabel.$notification.'
</p>
</div>';
}
Sorry friends, this is a stupid typo. I put (=!) Instead of (!=) In the php code.
$phone = "Aucun numéro de téléphone";
if ($member["phone"] =! "")
$phone = $member["phone"];
hi am making this edit function in my code igniter hmvc project. i am getting the value of the things i want to edit, and it is posted to the textbox i want to. but, i cannot save the changes. my model is this,
public function update(){
$sql = "UPDATE $this->table SET PROVINCE = ? WHERE PROV_ID = ?";
$input = array(
'PROVINCE' => $this->input->post('PROVINCE'),
'PROV_ID' =>$this->uri->segment(3)
);
// print_r($input);
// exit;
$query = $this->db->query($sql, $input);
return $query;
}
when i print_r the input, it says
Array ( [PROVINCE] => Province [PROV_ID] => )
i think dont get the uri value. how can i fix this?
here is my controller
/// EDIT
public function update(){
$data['content'] = $this->Provinces_Model->getrow();
$data['content_view'] = 'Provinces/edit_view';
$this->templates->admin_template($data);
}
public function update_row(){
if($this->Provinces_Model->update()){
redirect('Provinces/index');
}else{
$this->update();
}
}
}
here is my full model
//// EDIT
public function getrow(){
$this->db->where('PROV_ID', $this->uri->segment(3));
$query = $this->db->get($this->table);
return $query->row();
}
public function update(){
$sql = "UPDATE $this->table SET PROVINCE = ? WHERE PROV_ID = ?";
$input = array(
'PROVINCE' => $this->input->post('PROVINCE'),
'PROV_ID' =>$this->uri->segment(3)
);
// print_r($input);
// exit;
$query = $this->db->query($sql, $input);
return $query;
}
here is my edit view
<?php
echo form_open('Provinces/update_row');
?>
<p>
<label class="field" for="PROVINCE"><span>*</span>Province Name:</label>
<input type = "text" name="PROVINCE" class ="textbox-300" value= "<?php echo $content->PROVINCE; ?>">
<label class = "error"><?php echo form_error("PROVINCE"); ?></label>
</p>
<?php
echo form_submit('submit','Update');
echo form_close();
?>
here is the part of my table where i click to edit
<td><?php echo anchor("Provinces/update/$i->PROV_ID","<i class='fa fa-edit'>" ); ?></td>
Try this
public function update() {
$input = array(
'PROVINCE' => $this->input->post('PROVINCE'),
'PROV_ID' =>$this->uri->segment(3)
);
$this->db->where('prov_id',$input['PROV_ID']);
$this->db->update('province',$input);
}
get the all segments of URI in an array
For that use this line...
$segs = $this->uri->segment_array();
foreach ($segs as $segment)
{
echo $segment;
echo '<br />';
}
and use that specific key to get the ID or something else!!
I'm trying to use the typeahead.js Twitter Typeahead (not Bootstrap typeahead) to display names pulled from a mysql table using the CodeIgniter framework. The model also collects id values along with the name.
The controller and model seem to be presenting the correct array format.
Model
class People_model extends CI_Model{
function __construct() {
parent::__construct();
}
function get_person($name) {
$mode = $this->uri->segment(3);
$this->db->select("id, CONCAT(firstName,' ', lastName) AS name, type",FALSE);
$this->db->from('people');
if($mode == 'signin')
$this->db->where("status !=", "enter");
else
$this->db->where("status", "enter");
$this->db->like("concat(firstName,' ', lastName)", $name);
$this->db->order_by('name');
$query = $this->db->get();
if($query->num_rows > 0){
foreach ($query->result_array() as $row){
$new_row['value']=htmlentities(stripslashes($row['name']));
$new_row['id']=htmlentities(stripslashes($row['id']));
$row_set[] = $new_row; //build an array
}
}
echo json_encode($row_set); //format the array into json data
}
}
Controller (relevant functions)
function get_person() {
$this->config->set_item('disable_template', TRUE);
$this->load->model('People_model');
$name = $this->input->get_post();
$this->People_model->get_person($name);
}
function dosigninout() {
$mode = $this->uri->segment(3);
switch($mode) {
case 'signin':
$mode = 'enter';
break;
case 'signout':
$mode = 'exit';
break;
default:
$this->load->view("home/error", array('error' => "Invalid mode specified."));
}
$meeting = $this->_currentMeeting();
$person = $this->input->post('person_id');
if(!$this->_validPerson($person, $this->input->post('name'))) $this->load->view("home/error", array('error' => "You requested an operation with ".$this->input->post('name')." who has an ID of $person. The name and ID don't match."));
$this->db->insert("attendance", array('person_id' => $person, 'meeting_id' => $meeting['meetingID'], 'type' => $mode));
$this->db->where("id", $person);
$this->db->update("people", array('status' => $mode));
$redirectTo = (isset($_POST['redirect'])) ? $this->input->post('redirect') : false;
if($redirectTo) redirect($redirectTo);
else redirect('attendance');
}
Sample JSON data returned
[{"value":"Anna Woodhouse","id":"2"},{"value":"Elaine Woodhouse","id":"4"}]
View
$baseURL = base_url();
$extraHeadData = "";
?>
<h2><?=$title?></h2>
<p>Current meeting: <?=$meetingTitle?> on <?=$meetingDate?>.</p>
<?=form_open("attendance/dosigninout/$mode", array('id' => "signInOutForm"))?>
<fieldset>
<legend>Whom do you want to sign <?=($mode == "signin") ? 'in' : 'out'?>?</legend>
<div class="control-group">
<div class="controls">
<input type="hidden" name="person_id" id="person_id" value="" />
<input class="people-typeahead" type="text" id="typeahead" name="name" placeholder="person's full name"/>
</div>
</div>
</fieldset>
<div class="form-actions">
<?=form_submit('','Save changes','class="btn btn-primary"'); ?>
</div>
</form>
<script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.4.4/underscore-min.js"></script>
<script src="<?php echo $baseURL?>assets/js/typeahead.min.js"></script>
<script>
$(function($) {
$('input.people-typeahead').typeahead({
name: 'people',
remote: 'http://localhost/badgeentry/index.php/attendance/get_person',
dataType: 'json'
});
$("#people-typeahead").on("typeahead:selected typeahead:autocompleted", function(e,datum) {
$(person_id).val() = datum.id
});
});
</script>
In the form field I get the correct drop down list, but when an item is selected any new database entry has an id of "0" instead of the selected name id. I'm almost certain that this is an issue with the javascript code in the view not being correct, but quite frankly, I have no js skills to sort it out!
I see an issue here :
$(person_id).val() = datum.id
You are using jQuery's .val() incorrectly and the use of the selector is wrong too. It should look like :
$("#person_id").val(datum.id);
jQuery .val() documentation
I finally figured out how to get this working. Part of the problem was that I could find no examples of using typeahead.js in CodeIgniter that showed how the various script, view, controller and model components interact. I tried switching to Twitter bootstrap typeahead. However, despite finding references to using it with an arrays rather than a string, I still could not get a working solution.
In the end I went back to Twitter typeahead and started from scratch. I found this tutorial helped enormously:
Twitter Bootstrap typeahead.js with underscore.js Templating – A Tutorial - Alan Greenblatt
I'm posting what worked for me in case it can help anyone else with similar issues. This version also includes setting the remote source as a variable which allowed me to define it through PHP so that I could select data in the model based on the URL.
Model
class People_model extends CI_Model{
function __construct() {
parent::__construct();
}
function get_person($name) {
$modeinout = $this->uri->segment(3);
$this->db->select("id, CONCAT(firstName,' ', lastName) AS name, type",FALSE);
$this->db->from('people');
if($modeinout == 'signin'){
$this->db->where('status !=', 'enter');
}
else {
$this->db->where('status', 'enter');
}
$this->db->like("concat(firstName,' ', lastName)", $name);
$this->db->order_by('name');
$query = $this->db->get();
if($query->num_rows > 0){
foreach ($query->result_array() as $row){
$new_row['name']=htmlentities(stripslashes($row['name']));
$new_row['id']=htmlentities(stripslashes($row['id']));
$row_set[] = $new_row; //build an array
}
}
echo json_encode($row_set); //format the array into json data
}
Controller (relevant functions)
function signin() {
$this->load->helper("form");
$this->template->javascript('assets/js/underscore-min.js');
$this->template->javascript('assets/js/typeahead.min.js');
$data = $this->_currentMeeting();
$data['title'] = "Sign Someone In";
$data['attributes_form'] = array('id' => 'signInOutForm','class' => 'form-horizontal validate', 'enctype' => 'multipart/form-data');
$data['mode'] = 'signin';
$this->load->view("home/attendance/signinout", $data);
}
function signout() {
$this->load->helper("form");
$this->template->javascript('assets/js/underscore-min.js');
$this->template->javascript('assets/js/typeahead.min.js');
$data = $this->_currentMeeting();
$data['attributes_form'] = array('id' => 'signInOutForm','class' => 'form-horizontal validate', 'enctype' => 'multipart/form-data');
$data['id'] = '';
$data['title'] = "Sign Someone Out";
$data['mode'] = 'signout';
$this->load->view("home/attendance/signinout", $data);
}
function get_people() {
$this->config->set_item('disable_template', TRUE);
$this->load->model('People_model');
$name = $this->input->post('query');
$this->People_model->get_person($name);
}
function dosigninout() {
$mode = $this->uri->segment(3);
switch($mode) {
case 'signin':
$mode = 'enter';
break;
case 'signout':
$mode = 'exit';
break;
default:
$this->load->view("home/error", array('error' => "Invalid mode specified."));
}
$meeting = $this->_currentMeeting();
$person = $this->input->post('person_id');
if(!$this->_validPerson($person, $this->input->post('person_name'))) $this->load->view("home/error", array('error' => "You requested an operation with ".$this->input->post('person_name')." who has an ID of $person. The name and ID don't match."));
$this->db->insert("attendance", array('person_id' => $person, 'meeting_id' => $meeting['meetingID'], 'type' => $mode));
$this->db->where("id", $person);
$this->db->update("people", array('status' => $mode));
$redirectTo = (isset($_POST['redirect'])) ? $this->input->post('redirect') : false;
if($redirectTo) redirect($redirectTo);
else redirect('attendance');
}
View
<?php
$baseURL = base_url();
$extraHeadData = "";
?>
<h2><?=$title?></h2>
<p>Current meeting: <?=$meetingTitle?> on <?=$meetingDate?>.</p>
<?=form_open("attendance/dosigninout/$mode", array('id' => "signInOutForm",'class' => "form-horizontal validate"))?>
<input type="hidden" name="person_id" id="person_id">
<?php echo validation_errors(); ?>
<fieldset>
<legend>Whom do you want to sign <?=($mode == "signin") ? 'in' : 'out'?>?</legend>
<div class="control-group">
<div class="controls">
<input type="text" placeholder="person's full name" name="person_name" id="person_name" class="person-typeahead">
</div>
</div>
</fieldset>
<div class="form-actions">
<?=form_submit('','Save changes','class="btn btn-primary"'); ?>
</div>
</form>
<script>
var person_url="<?php echo site_url('attendance/get_people')."/".$mode;?>";
$(function($) {
_.compile = function(templ) {
var compiled = this.template(templ);
compiled.render = function(ctx) {
return this(ctx);
}
return compiled;
}
$('.person-typeahead').typeahead({
template: '<p><strong><%= name %></strong>: <%= id %></p>',
name: 'people',
valueKey: 'name',
engine: _,
remote: (person_url),
dataType: 'json'
}).on('typeahead:selected typeahead:autocompleted', function(event, datum) {
$('#person_id').val(datum.id);
$('#person_name').val(datum.name);
});
});
</script>
<?=jquery_validate('attendance/signout');?>
I am working with two classes: usuarios, preguntas.
In preguntas I store id_usuario which correspond to the id from user, ok. But sometimes I need to display more than the id, so I made a function in usuarios. php to print this info:
This is mi code for now
usuarios.php (I'm only including relevant code for this problem)
Código PHP:
function __construct($id){
$consulta = mysql_query("SELECT * FROM usuarios WHERE id = '".$id."'");
while($item = mysql_fetch_array($consulta)){
$this->id = $item['id'];
$this ->fid = $item['fid'];
$this ->usuario = $item['alias'];
$this ->password = $item['pass'];
$this ->email = $item['mail'];
$this ->fechar = $item['fechar'];
$this ->ultima = $item['ultima'];
$this ->img_src = $item['img_src'];
$this ->reputacion = $this ->fechar = $item['reputacion'];
}
}
function miniatura(){
$html_mini = "<div>$this->usuario</div>";
return $html_mini;
}
pregunta.php (i'm only including relevant code for this problem)
Código PHP:
function get_autor(){
$us = new usuario($item['id']);
return $us->miniatura();
}
function imprimir_titular(){
$html_t = '<h1 class="prg'.$this->id.'" >[ '.$this->id_eval_q.' ] '.$this->get_autor().' pregunta: '.$this->pregunta.' , '.$this->fecha.'</h1>';
return $html_t;
}
And this is the error:
Cita:
Fatal error: Call to undefined method
usuario::miniatura() in
/home/piscolab/public_html/keepyourlinks.com/recetorium/clases/pregunta.php
on line 35 No entiendo por qué no
accede al método de la clase usuarios,
aunque me deje crear el objeto usuario
:S
Details:
- Protected atributes
Any help will be wellcome
I copied you code, change content of methods and everything works
class usuario {
function __construct($id){
echo 'ok';
}
function miniatura(){
echo 'ok';
}
}
function get_autor(){
$us = new usuario($item['id']);
return $us->miniatura();
}
Show full classes because with Your code as shown in nothing wrong.
ok, this is the file where i'm calling both:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
Recetorium > Preguntas - Pregunta o responde qué y cómo cocinar algo
Cargando..
and in router.php
<?php require_once('funciones.php');
if(isset($_POST['inicio'])){
// el usuario está iniciando sesion
$iniciando = new sesion_usuarios();
if($iniciando->iniciar()){
imprimir_sesion_iniciada();
}else{
imprimir_formulario_sesion();
}
}else if(isset($_POST['registro'])){
$registrando = new registro_usuarios();
if($registrando->register()){
imprimir_usuario_registrado();
}else{
imprimir_formulario_registro();
}
}else if(isset($_GET['que']) or isset($que)){
if(isset($que))
$tarea = $que;
else
$tarea = $_GET['que'];
if($tarea == 'registro'){
imprimir_formulario_registro();
}else if($tarea == 'login'){
imprimir_formulario_sesion();
}else if($tarea == 'salir'){
cerrar_sesion();
}else if($tarea == 'ultimas_preguntas'){
listar_preguntas();
}else if($tarea == 'nueva_pregunta'){
$tem = new pregunta();
$tem->imprimir_formulario;
}else if($tarea == 'ultimas_recetas'){
$tem = new pregunta();
$tem->imprimir_formulario;
}
}else if(sesion()){
echo 'Pronto prodrás: Preguntar cosas, responder cosas y evaluar ambos. Publicar tus recetas, descubrir otras, evaluarlas y ser evaluado.';
}else{
$archivo = 'bienvenida.php';
include($archivo);
imprimir_formulario_sesion();
}
?>
I have two dropdownlist in one view but i don't know if i can load the view passing the two arrays like this:
$this->load->view('primerPaso',$data,$data2);
To be more specific i'm doing everything like this:
Model
/*
* Método encargado de consultar las ciudades
* donde existen agencias.
*/
function ConsultarCiudadesAgencias()
{
$this->db->select('LISValor');
$this->db->from('410LIS');
$this->db->where('LISNombre','ESTLista3');
$query = $this->db->get();
$result = array();
if($query->num_rows() > 0)
{
foreach ($query->result_array() as $row)
{
$result[$row['LISValor']] = $row['LISValor'];
}
return $result;
}
}
/*
* Método encargado de consultar los diferentes
* tipos de vehiculos que existen para su alquiler.
*/
function ConsultarTiposVehiculos()
{
$this->db->select('LISValor');
$this->db->from('410LIS');
$this->db->where('LISNombre','SUBLista3');
$query = $this->db->get();
$result = array();
if($query->num_rows() > 0)
{
foreach ($query->result_array() as $row)
{
$result[$row['LISValor']] = $row['LISValor'];
}
return $result;
}
}
Controller:
function index()
{
$this->load->model('PrimerPasoModel');
$data['ciudades'] = $this->PrimerPasoModel->ConsultarCiudadesAgencias();
$data2['vehiculos'] = $this->PrimerPasoModel->ConsultarTiposVehiculos();
$this->load->view('primerPaso',$data,$data2);
}
and in the view i have this (not going to paste all the html):
<tr>
<td>Ciudad de Alquiler:</td>
<td><?php echo form_dropdown('CiudadAlquiler',$ciudades); ?></td>
</tr>
<tr>
<td colspan="2">
<?php echo form_dropdown('TipoVehiculo',$vehiculos);?>
</td>
</tr>
whit this code i get this error:
Severity: Notice
Message: Undefined variable: vehiculos
Filename: views/primerPaso.php
Line Number: 76
Where "primerPaso.php" is the name of mi view.
Thanks for your time and help.
Just use the same $data array and it'll work.
function index()
{
$this->load->model('PrimerPasoModel');
$data['ciudades'] = $this->PrimerPasoModel->ConsultarCiudadesAgencias();
$data['vehiculos'] = $this->PrimerPasoModel->ConsultarTiposVehiculos();
$this->load->view('primerPaso', $data);
}