I never thought i would trip up on such an easy task, what i'm doing is getting rows from MySQL, and showing them on a form, the user can then update the values if needed:
<?php
include('includes/db_connection.php');
include('includes/sessions.php');
include('includes/functions.php');
include('includes/header.php');
include('includes/navbar-logged.php');
// AUTHENTICATION //
$row = DB::getInstance()->selectOneByField('membership', 'member_username', $member);
if ($row['member_user_class'] != 'Site Administrator') {
stderr("Sorry, <b>no authorization</b> to access this page.");
}
// AUTHENTICATION //
// CLOUD KEYS //
if (isset($_POST['submitCloudKeys']))
{
// TRY/CATCH //
try {
foreach ($_POST['cloudId'] as $val) {
DB::getInstance()->update(
'clouds',
'cloud_id',
$val,
[
'cloud_key' => $_POST['cloud_key'][$val]
]);
stdmsg('Cloud keys \'<b>'.$_POST['cloud_key'][$val].'</b>\' have been <b>updated</b>.');
}
} catch (Exception $e) {
stderr($e);
}
}
$rows = DB::getInstance()->select('SELECT * FROM `clouds`');
?>
<div class="panel panel-primary">
<div class="panel-heading">Current cloud hosts.</div>
<div class="panel-body">
<form action="clouds.php" method="post" class="form-horizontal container-fluid" role="form">
<?php $x = 0; ?>
<?php $z = 0; ?>
<?php foreach ($rows as $row) { ?>
<div class="row form-group">
<div class="col-sm-4 text-right"><label for="txtNetwork" class="control-label"><?php echo htmlspecialchars($row['cloud_name']) ?>:</div>
<div class="col-sm-8">
<input type="text" name="cloud_key[]" value="<?php echo htmlspecialchars($row['cloud_key']) ?>" size="30" class="form-control" />
<input type="hidden" name="cloudId[]" value="<?php echo $row['cloud_id']; ?>" />
</div>
</div>
<?php } ?>
<div class="row form-group">
<div class="col-sm-12 text-right">
<button type="submit" name="submitCloudKeys" class="btn btn-default">Update</button>
</div>
</div>
</form>
</div>
<div class="panel-footer">Update the <b>cloud hosts</b> keys.</div>
</div>
<?php
include('includes/footer.php');
I'm getting an error:
PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'b447297ddb6be7377......................' in 'field list' in /home/admin/web/wraithpbns.com/public_html/includes/DB.php:268
Stack trace: #0 /home/admin/web/wraithpbns.com/public_html/includes/DB.php(268): PDOStatement->execute()
#1 /home/admin/web/wraithpbns.com/public_html/clouds.php(26): DB->update('clouds', 'cloud_id', '1', Array)
#2 {main}
The table names in MySQL are all correct, i don't see why i'm not able to update the form values, the "Unknown column" part is showing me the key value i'm trying to update, i have never had this issue before, any help would be appreciated guys!
UPDATED METHODS:
<?php
class DB
{
private static $instance;
public static function getInstance() {
if(is_null(self::$instance)) {
self::$instance = new DB();
}
return self::$instance;
}
public static function map(array $rows = array(), $keyColumn, $valueColumn = null) {
$result = array();
foreach($rows as $row) {
if(is_null($valueColumn)) {
$result[$row[$keyColumn]] = $row;
} else {
$result[$row[$keyColumn]] = $row[$valueColumn];
}
}
return $result;
}
private $pdo;
private function __construct() {
try {
$this->pdo = new PDO(
sprintf('%s:host=%s;dbname=%s',
DRIVER,
HOST,
DATA
),
USER,
PASS,
array(
PDO::ATTR_PERSISTENT => true,
PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8; SET CHARACTER SET utf8;'
)
);
} catch(Exception $ex) {
throw new Exception('Cannot connect to database.');
}
}
public function execute($query, array $params = []) {
$normParams = $this->normalizeParams($params);
$command = $this->pdo->prepare($query);
$command->closeCursor();
$status = $command->execute($normParams);
if(!$status) {
throw new Exception('DB::execute(): Can\'t execute query:');
}
return $status;
}
public function select($query, array $params = [], $fetchType = PDO::FETCH_ASSOC) {
$normParams = $this->normalizeParams($params);
$command = $this->pdo->prepare($query);
$command->closeCursor();
foreach($normParams as $paramName => $paramValue) {
if(is_array($paramValue)
&& isset($paramValue['type'])
&& isset($paramValue['value'])) {
$command->bindValue($paramName, $paramValue['value'], $paramValue['type']);
} else {
$command->bindValue($paramName, $paramValue);
}
}
if(!$command->execute()) {
throw new Exception('DB::select(): Can\'t execute query.');
}
return $command->fetchAll($fetchType);
}
public function selectValues($query, array $params = [], $fetchType = PDO::FETCH_ASSOC) {
$row = $this->selectOne($query, $params, $fetchType);
if(empty($row)) {
throw new Exception('DB::selectValues(): No values selected.');
} else {
return $row;
}
}
public function selectValue($query, array $params = []) {
$values = $this->selectValues($query, $params, PDO::FETCH_NUM);
return $values[0];
}
public function selectAll($tableName, $fetchType = PDO::FETCH_ASSOC) {
return $this->select(
sprintf('
SELECT *
FROM `%s`',
$tableName
),
[],
$fetchType
);
}
public function selectByField($tableName, $fieldName, $value, $fetchType = PDO::FETCH_ASSOC) {
return $this->select(
sprintf('
SELECT *
FROM `%s`
WHERE `%s` = :value',
$tableName,
$fieldName
),
[
':value' => $value
],
$fetchType
);
}
public function selectOne($query, array $params = [], $fetchType = PDO::FETCH_ASSOC) {
$rows = $this->select($query, $params, $fetchType);
return array_shift($rows);
}
public function selectOneByField($tableName, $fieldName, $value, $fetchType = PDO::FETCH_ASSOC) {
$rows = $this->selectByField($tableName, $fieldName, $value, $fetchType);
return array_shift($rows);
}
public function get($tableName, $fieldName, $value, $fetchType = PDO::FETCH_ASSOC) {
return $this->selectOneByField($tableName, $fieldName, $value, $fetchType);
}
public function insert($tableName, array $fields) {
$normParams = $this->normalizeParams($fields);
$paramNames = implode(', ', array_keys($normParams));
$fieldNames = '`' . implode('`, `', array_keys($fields)) . '`';
$command = $this->pdo->prepare(
sprintf('
INSERT INTO `%s` (%s)
VALUES (%s)',
$tableName,
$fieldNames,
$paramNames
)
);
$command->closeCursor();
if(!$command->execute($normParams)) {
throw new Exception('DB::insert(): Can\'t execute query.');
}
return $this->pdo->lastInsertId();
}
public function bulkInsert($tableName, array $rows = []) {
if(empty($rows)) {
return;
}
$fieldNames = array_keys($this->normalizeParams($rows[0]));
$normParams = [];
$paramNames = '';
$counter = 0;
foreach($rows as $row) {
$paramNames .= ((0 < $counter)? ',': '') . '(';
$nextParamNames = [];
foreach($row as $paramKey => $paramValue) {
$nextParamNames[] = ':' . $paramKey . $counter;
$normParams[':' . $paramKey . $counter] = $paramValue;
}
$paramNames .= implode(',', $nextParamNames);
$paramNames .= ')';
$counter++;
}
$command = $this->pdo->prepare(
sprintf('
INSERT INTO `%s` %s
VALUES %s',
$tableName,
$fieldNames,
$paramNames
)
);
$command->closeCursor();
if(!$command->execute($normParams)) {
throw new Exception('DB::bulkInsert(): Can\'t execute query.');
}
}
public function update($tableName, $fieldName, $fieldValue, array $updateFields, $updateAll = false) {
if(is_null($fieldName)) {
if(!$updateAll) {
throw new SystemException('Attempt to update all table records without confirmation.');
}
$sqlWhere = '';
} else {
$sqlWhere = sprintf('WHERE `%s` = %s', $fieldName, $fieldValue);
}
// echo $sqlWhere;
//
// exit;
$normUpdateFields = $this->normalizeParams($updateFields);
$sqlSetRows = [];
foreach($updateFields as $updateFieldName => $updateFieldValue) {
$sqlSetRows[] = sprintf('`%s` = %s', $updateFieldName, $updateFieldValue);
}
$sqlSet = implode(', ', $sqlSetRows);
$command = $this->pdo->prepare(
$sql = sprintf('
UPDATE `%s`
SET %s
%s',
$tableName,
$sqlSet,
$sqlWhere
)
);
$command->closeCursor();
foreach($normUpdateFields as $updateFieldName => $updateFieldValue) {
if(is_array($updateFieldValue)
&& isset($updateFieldValue['type'])
&& isset($updateFieldValue['value'])) {
$command->bindValue($updateFieldName, $updateFieldValue['value'], $updateFieldValue['type']);
} else {
$command->bindValue($updateFieldName, $updateFieldValue);
}
}
if(!empty($sqlWhere)) {
$command->bindValue(':' . $fieldName, $fieldValue);
}
if(!$command->execute()) {
throw new Exception('DB::update(): Can\'t execute query.');
}
}
public function remove($tableName, $fieldName = null, $value = null, $removeAll = false) {
$isExecuted = false;
if(is_null($fieldName)
&& is_null($value)
&& $removeAll) {
$isExecuted = $this->execute(sprintf('DELETE FROM `%s`', $tableName));
} else if(!is_null($fieldName)
&& !is_null($value)) {
$isExecuted = $this->execute(
sprintf('
DELETE FROM `%s`
WHERE `%s` = :value',
$tableName,
$fieldName
),
[
':value' => $value
]
);
}
if(!$isExecuted) {
throw new Exception('DB::remove(): Can\'t execute query.');
}
}
protected function normalizeParams(array $params = []) {
$normParams = [];
foreach($params as $paramKey => $paramValue) {
$normParams[(strlen($paramKey) && (':' === $paramKey{0}))? $paramKey: ':' . $paramKey] = $paramValue;
}
return $normParams;
}
/**
* Replaces any parameter placeholders in a query with the value of that
* parameter. Useful for debugging. Assumes anonymous parameters from
* $params are are in the same order as specified in $query
*
* #param string $query The sql query with parameter placeholders
* #param array $params The array of substitution parameters
* #return string The interpolated query
*/
public function interpolateQuery($query, $params) {
$keys = array();
# build a regular expression for each parameter
foreach ($params as $key => $value) {
if (is_string($key)) {
$keys[] = '/:'.$key.'/';
} else {
$keys[] = '/[?]/';
}
}
$query = preg_replace($keys, $params, $query, 1, $count);
#trigger_error('replaced '.$count.' keys');
return $query;
}
}
You have an logic issue within your update method ,
first , you are assigning a value then you are trying to bind a value,
$sqlWhere = sprintf('WHERE `%s` = %s', $fieldName, $fieldValue);
// ^^ ^^^^^^^^^^^^
and the same for your set clause :
$sqlSetRows[] = sprintf('`%s` = %s', $updateFieldName, $updateFieldValue);
// ^^ ^^^^^^^^^^^^^^^^^^
then as I told, you are trying to bind those values again using bindValue whether in your where clause :
$command->bindValue(':' . $fieldName, $fieldValue);
or in your this loop :
foreach($normUpdateFields as $updateFieldName => $updateFieldValue) {
....
$command->bindValue($updateFieldName, $updateFieldValue);
to solve you have two ways :
1 ) fix this by passing the write keys as follows :
$sqlWhere = sprintf('WHERE `%s` = :%s', $fieldName, $fieldName);
and for your set clause :
$sqlSetRows[] = sprintf('`%s` = :%s', $updateFieldName, $updateFieldName);
2 ) directly inject those values and leave your bindValue method which is not preferable:
$sqlSetRows[] = sprintf('`%s`="%s"', $updateFieldName, $updateFieldValue);
and $sqlWhere = sprintf('WHERE%s="%s"', $fieldName, $fieldValue);
Related
Recently I try to create an API with PHP. all thing goes alright till suddenly I face unexpected 'a' error when trying to parse a JSON from the request throw Postman. I found something related to my issue but there is no solution in my case here : link
I send
{
"teacher_code":"sas"
}
JSON to teachers.php file to assign a student to the teacher
here is the teacher.php file content :
require_once ("classes/Rest.php");
require_once ("classes/api.php");
$api = new Api();
if($api->getHttpmethod() === 'POST'){
$api->validateParameter('teacher_code' ,$teacher_code = $api->getParam('teacher_code') , STRING , true);
$api->checkUserAccessablity();
$api->teacherCodeinRange($teacher_code);
$query = "INSERT INTO `group_users` (`user_id`,`group_id` )
VALUES (:user_id , (SELECT group_id FROM `groups` WHERE group_name = 'all' AND user_id =
(SELECT user_id FROM `teachers` WHERE t_code = :teacher_code)) )";
$keyValue = [
"user_id" => $api->getUserid() ,
"teacher_code" => $teacher_code
];
$result = $api->queryExecute($query , $keyValue );
$api->returnResponse(SUCCESS , SUCCESS_MESSAGE);
}
and api.php file :
require_once ("dbConnect.php");
require_once ("JWT.php");
class Api extends Rest
{
public $dbConn;
private $userId;
public function __construct()
{
parent::__construct();
$db = new dbConnect();
$this->dbConn = $db->connect();
}
public function setUserid($id){
$this->userId = $id;
}
public function getUserid(){
return $this->userId;
}
public function checkUserAccessablity(){
$payload = $this->deCodetoken();
$this->setUserid($payload->user_id);
$this->validateUser();
}
public function validateUser(){
$query = "SELECT * FROM `users` WHERE user_id = :id";
$keyValue = [
"id" => $this->getUserid()
];
$result = $this->queryExecute($query , $keyValue,true );
if(!$result){
$this->throwError(SYSTEM_ERROR , SYSTEM_ERROR_MESSAGE );
}
if(!is_array($result)){
$this->throwError(USER_NOT_FOUND_CODE , USER_NOT_FOUND_MESSAGE . $this->getUserid());
}
//TODO CHECK USER ACTIVE
return true;
}
public function teacherCodeinRange($tCode){
$query = "SELECT * FROM `teachers` INNER JOIN `licenses` ON (licenses.user_id = teachers.user_id)
WHERE teachers.t_code = :tcode LIMIT 1";
$keyValue = [
"tcode" => $tCode
];
$this->queryExecute($query , $keyValue,true );
return true;
}
public function teacherCodeinStudentrange($teacherID){
//TODO SELECT TEACHER STUDENT RANGE
$query = "SELECT DISTICT user_id FROM `teachers` INNER JOIN `groups` ON (groups.user_id = teachers.user_id)
INNER JOIN `group_users` ON (group_users.group_id = groups.group_id)
WHERE teachers.user_id = :teacherID AND groups.group_name = 'all' AND group_users.user_id = :userID ";
$keyValue = [
"userID" => $this->getUserid(),
"teacherID" => $teacherID,
];
$result = $this->queryExecute($query , $keyValue,true );
if(!is_array($result)){
$this->throwError(TEACHER_NOT_FOUND , TEACHER_NOT_FOUND_MESSAGE);
}
return true;
}
public function getHttpmethod(){
return $this->HttpMethod;
}
public function getParam($key){
return $this->arrayFinddeep($this->data , $key);
}
public function queryExecute($query , $keyArray , $isSelect = false){
$queryExec = $this->dbConn->prepare($query);
if(is_array($keyArray) || !empty($keyArray)) {
foreach ($keyArray as $key => &$value) {
$queryExec->bindParam(':' . $key, $value);
}
}
if($isSelect) {
$queryExec->execute();
$result = $queryExec->fetch(PDO::FETCH_ASSOC);
}else {
$result = $queryExec->execute();
}
return $result;
}
public function getLastuserId(){
return $this->dbConn->lastInsertId();
}
public function generateToken($payload , $secretKey){
try{
return \Firebase\JWT\JWT::encode($payload , $secretKey);
}catch (Exception $exception){
$this->throwError(JWT_PROCESSING_ERROR , $exception->getMessage());
}
}
public function deCodetoken(){
try{
$token = $this->getBearerToken();
$payload = \Firebase\JWT\JWT::decode($token , SECURITY_KEY , ['HS256']);
return $payload;
}catch (Exception $exception){
$this->throwError(ACCESS_TOKEN_ERROR , $exception->getMessage());
}
}
}
and the last class is Rest.php :
require_once ("Constans.php");
class Rest
{
protected $HttpMethod;
protected $request;
protected $data;
public function __construct(){
$this->HttpMethod = $_SERVER['REQUEST_METHOD'];
if($this->checkValidhttpMethod()) {
try{
$handler = fopen('php://input', 'r');
$this->request = stream_get_contents($handler);
}catch (Exception $exception){
//TODO HANDLE EXEPTION
}
$this->validateRequest();
}
}
public function checkValidhttpMethod(){
if(empty($this->HttpMethod) or !in_array($this->HttpMethod,ACCEPTABLE_HTTP_METHOD)){
$this->throwError(NOT_VALID_HTTP_METHOD,NOT_VALID_HTTP_METHOD_Message);
}
return true;
}
public function setJsonheader(){
header("content-type: application/json");
}
public function validateRequest(){
if($_SERVER['CONTENT_TYPE'] !== 'application/json'){
$this->throwError(REQUEST_CONTENT_NOT_VALID , REQUEST_CONTENT_NOT_VALID_MESSAGE);
}
try{
$this->data = json_decode($this->request , true);
}catch (Exception $exception){
//TODO HANDLE EXEPTION
}
}
public function processAPI(){
}
public function throwError($code , $message){
$this->setJsonheader();
echo json_encode(['error' => ['status' => $code , 'message' => $message]]);
exit;
}
public function returnResponse($code , $data){
$this->setJsonheader();
echo json_encode(['response' => ['status' => $code , 'result' => $data ]]);
exit;
}
//TODO SQL injection Validate
public function validateParameter($fieldName , $value , $dataType , $required = true){
if($required && empty($value)){
$this->throwError(PARAMETR_REQUIRED,PARAMETR_REQUIRED_MESSAGE . $fieldName);
}
//TODO SQL injection
//TODO CHECK The All Data Type
switch ($dataType){
case BOOLEAN :
if(!is_bool($value)){
$this->throwError(PARAMETR_DATA_TYPE_NOT_VALID , PARAMETR_DATA_TYPE_NOT_VALID_MESSAGE . $fieldName);
}
break;
case INTEGER :
if(!is_numeric($value)){
$this->throwError(PARAMETR_DATA_TYPE_NOT_VALID , PARAMETR_DATA_TYPE_NOT_VALID_MESSAGE . $fieldName);
}
break;
case STRING :
if(!is_string($value)){
$this->throwError(PARAMETR_DATA_TYPE_NOT_VALID , PARAMETR_DATA_TYPE_NOT_VALID_MESSAGE . $fieldName);
}
break;
case DONT_CARE :
break;
default:
break;
}
return $value;
}
public function arrayFinddeep($array, $search)
{
foreach($array as $key => $value) {
if (is_array($value)) {
$sub = $this->arrayFinddeep($value, $search);
if (count($sub)) {
return $sub;
}
} elseif ($key === $search) {
return $value;
}
}
return array();
}
/**
* Get hearder Authorization
* */
function getAuthorizationHeader(){
$headers = null;
if (isset($_SERVER['Authorization'])) {
$headers = trim($_SERVER["Authorization"]);
}
else if (isset($_SERVER['HTTP_AUTHORIZATION'])) { //Nginx or fast CGI
$headers = trim($_SERVER["HTTP_AUTHORIZATION"]);
} elseif (function_exists('apache_request_headers')) {
$requestHeaders = apache_request_headers();
// Server-side fix for bug in old Android versions (a nice side-effect of this fix means we don't care about capitalization for Authorization)
$requestHeaders = array_combine(array_map('ucwords', array_keys($requestHeaders)), array_values($requestHeaders));
//print_r($requestHeaders);
if (isset($requestHeaders['Authorization'])) {
$headers = trim($requestHeaders['Authorization']);
}
}
return $headers;
}
/**
* get access token from header
* */
function getBearerToken() {
$headers = $this->getAuthorizationHeader();
// HEADER: Get the access token from the header
if (!empty($headers)) {
if (preg_match('/Bearer\s(\S+)/', $headers, $matches)) {
return $matches[1];
}
}
$this->throwError(AUTHORIZATION_HEADER_NOT_FOUND , AUTHORIZATION_HEADER_NOT_FOUND_MESSAGE);
}
}
all queries go along queryExecute function in api.php class and recently I got that the bindParam function is not going to work fine too.
I really don't have any idea where the problem is, as In the reference said its somehow related to DB queries result. I try to use mysqli also but it did not work.
any help will be appreciated :-)
I have a sql UPDATE query in PDO that should update a name and a permissions string.
But instead it just places the id of that row inside all columns.
Here is my code:
public function saveRole($roleID, $name, $permissions)
{
$sql = "UPDATE roles SET name = :name, permissions = :permissions WHERE id = :id";
//this one sets a string variable in the PDO wrapper class
PDO::setSQL($sql);
//this one sets an array inside the PDO wrapper class
PDO::setData([
'name' => $name,
'permissions' => $permissions,
'id' => $roleID,
]);
PDO::execute();
return PDO::getResponse(true);
}
As you see, I've written a wrapper for PDO, which looks like this:
static function execute($sql = null, $data = null, $fetchmode = \PDO::FETCH_OBJ)
{
//check if data and SQL are set in function call, if so, use function call params, if not use class params ($this->SQL & $this->data)
self::connect();
try
{
$stmnt = self::$con->prepare(self::$sql);
$stmnt->setFetchMode($fetchmode);
if (sizeof(self::$data) > 0)
{
foreach (self::$data as $key => $value)
{
$stmnt->bindParam(':' . $key, $value);
}
}
$stmnt->execute();
self::$stmnt = $stmnt;
self::$data = [];
self::$sql = '';
self::$lastResponse = new pdoReturn(true, $stmnt);
return;
} catch (\PDOException $exception)
{
self::$data = [];
self::$sql = '';
self::$lastResponse = new pdoReturn(false, $exception);
return;
}
}
function setSQL($sql) {
if (!is_string($sql))
return false;
if (strlen($sql) == 0)
return false;
$this->sql = $sql;
return true;
}
function setData($data) {
if (!is_array($data))
return false;
$this->data = $data;
return true;
}
As you see, I've written a wrapper for PDO
For the immediate fix, change
$stmnt = self::$con->prepare(self::$sql);
$stmnt->setFetchMode($fetchmode);
if (sizeof(self::$data) > 0)
{
foreach (self::$data as $key => $value)
{
$stmnt->bindParam(':' . $key, $value);
}
}
$stmnt->execute();
to
$stmnt = self::$con->prepare(self::$sql);
$stmnt->setFetchMode($fetchmode);
$stmnt->execute(self::$data);
Then read about your first database wrapper's childhood diseases and fix other issues such as statefulness and error reporting.
Firstly,Thanks for reading this. How to solve my problems
CODE
$roomid = CMS::$MySql->Query("SELECT room_id FROM user_roomvisits WHERE user_id ='".$users['id']."' ORDER BY entry_timestamp DESC LIMIT 1");
$room = CMS::$MySql->Query("SELECT caption FROM rooms WHERE id ='".$roomid."'");
AND got the error :
Catchable fatal error: Object of class mysqli_result could not be converted to string.
Here mysql class
<?php
class MySql{
private $Link;
private $Statement;
public $Result = null;
private $FetchRows = Array();
public function __construct($Data)
{
$this->Link = new MySQLi($Data['mysql.hostname'], $Data['mysql.username'], $Data['mysql.password'], $Data['mysql.database']);
}
public function Query($Query)
{
if (isset($this->Statement))
{
$this->Statement->Close();
$this->Statement = null;
}
return $this->Link->query($Query);
}
public function Prepare($Query)
{
if (isset($this->Statement))
{
$this->Statement->Close();
}
$this->Statement = $this->Link->prepare($Query);
}
public function Execute($FuncArgs = null)
{
if (!is_array($FuncArgs))
{
$FuncArgs = func_get_args();
}
$Args = Array('');
foreach ($FuncArgs as &$Arg)
{
$Args[0] .= substr(gettype($Arg), 0, 1);
$Args[] =& $Arg;
}
call_user_func_array(Array($this->Statement, 'bind_param'), $Args);
if (!$this->Statement->Execute())
{
exit('Execute Stmt Error: '.$this->Statement->error);
}
return $this->Statement;
}
public function Fetch($Columns)
{
if (!is_array($Columns))
{
$Columns = func_get_args();
}
if ($this->Result == null)
{
$this->Result = array_combine($Columns, $Columns);
$Args = Array();
foreach ($Columns as $Column)
{
$Args[] =& $this->Result[$Column];
}
call_user_func_array(Array($this->Statement, 'bind_result'), $Args);
}
$RowsLeft = $this->Statement->fetch();
if (!$RowsLeft)
{
self::Clear();
return false;
}
return $this->Result;
}
?>
these are the mysql class for the PDO maybe?
$roomid = CMS::$MySql->Query("SELECT room_id FROM user_roomvisits WHERE user_id ='".$users['id']."' ORDER BY entry_timestamp DESC LIMIT 1");
while($row=mysql_fetch_array($roomid)){
$rumid=$row[0];
}
$room = CMS::$MySql->Query("SELECT caption FROM rooms WHERE id ='".$rumid."'");
the result from mysql query is object. u cannot echo objects
use var_dump() or print_r() to view the structure of them
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
I'm using this class to connect to database. It works just fine, except I couldn't get the lastInsertId().
<?php
class connDB
{
public function connDB()
{
require_once( 'dbconfig/config.php' );
$this->confPDO = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_PERSISTENT => false,
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES UTF8"
);
try
{
$this->dbc = new PDO( "mysql:host=$this->dbHost;dbname=$this->dbName",
$this->dbUser, $this->dbPass, $this->confPDO );
}
catch( PDOException $errMsg )
{
return false;
}
}
public function exec( $sql, array $params = array() )
{
try
{
$this->stmt = $this->dbc->prepare( $sql );
if ( count( $params ) > 0 )
{
foreach ( $params as $k=>$v )
{
$this->bind($k, $v);
}
}
return $this->stmt->execute();
}
catch( PDOException $errMsg )
{
$this->dbc = null;
return false;
}
}
public function bind( $param, $value, $type = null )
{
if ( is_null( $type ) )
{
switch ( true )
{
// Boolen parameter
case is_bool( $value ):
$type = PDO::PARAM_BOOL;
break;
// Integer parameter
case is_int( $value ):
$type = PDO::PARAM_INT;
break;
// Null parameter
case is_null( $value ):
$type = PDO::PARAM_NULL;
break;
// String parameter
default:
$type = PDO::PARAM_STR;
}
}
$this->stmt->bindValue( $param, $value, $type );
}
public function single()
{
return $this->stmt->fetch(PDO::FETCH_ASSOC);
}
public function resultset()
{
return $this->stmt->fetchAll(PDO::FETCH_ASSOC);
}
public function rowCount()
{
return $this->stmt->rowCount();
}
}
Usage: [SELECT]
$sql = "SELECT * FROM < table >";
$db->exec($sql, $params);
$rows = $db->resultset();
foreach ($rows as $row)
{
echo $row['< column >'] . "\n";
}
Usage: [INSERT]
$sql = "INSERT INTO < table > (< column_1 >, < column_2 >, ... ) VALUES
(:valuename_1,
:valuename_2, ...)";
$params = array(':valuename_1' => 'value', ':valuename_2' => 'value', ...);
$db->exec($sql, $params);
I tried to do it this way:
include_once'classe.php';
$db = new connDB();
$sql = "INSERT INTO < table > (< column_1 >, < column_2 >, ... ) VALUES
(:valuename_1,
:valuename_2, ...)";
$params = array(':valuename_1' => 'value', ':valuename_2' => 'value', ...);
$db->exec($sql, $params);
$id = $db->lastInsertId();
I am getting an error:
Fatal error: Call to undefined method connDB::lastInsertId() in
I've tried adding a method into the class:
public function lastinsert()
{
// Return result
return $this->stmt->lastInsertId();
}
Then I called it like this this:
$db = new connDB();
$id = $db->lastinsert();
The error this time was
Fatal error: Call to undefined method PDOStatement::lastInsertId() in
There is no lastInsertId() method in your class.
You need to add it to the connDB class.
you need to call $dbc, not $stmt to get lastInsertId();
$this->dbc->lastInsertId();
as this function belongs to PDO class, not PDO statement class
Also, this piece of code may cause the problem
catch( PDOException $errMsg )
{
$this->dbc = null;
return false;
}
}
Make your exec() function this way
public function exec( $sql, array $params = array() )
{
$this->stmt = $this->dbc->prepare( $sql );
foreach ( $params as $k=>$v )
{
$this->bind($k, $v);
}
return $this->stmt->execute();
}
Using the same database class and was able to use lastInsertId like this:
$db = new connDB();
...
$_SESSION['users_id'] = $db->dbc->lastInsertId('id');
If you are using the model's save function:
$row->save();
You can use:
return $row->save();
which returns the id