Hello I was building my Query class which I saw on YouTube, but I'm stuck. My Query function that allows you to use advanced SQL queries like SELECT * FROM market LIMIT ? OFFSET ? It binds values so I can't find any solution. Anybody help? What should I do?
My Query.php class contains
public function query($sql, $params = array())
{
$this->_error = false;
if ($this->_query = $this->db->prepare($sql))
{
$x = 1;
if (count($params))
{
foreach ($params as $param)
{
$this->_query->bindValue($x, $param);
$x++;
}
}
if ($this->_query->execute())
{
$this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ);
$this->_count = $this->_query->rowCount();
} else {
$this->_error = true;
}
}
return $this;
}
Here I tried to select items from db like it's in my Query bellow
$i = 3;
$x = 100;
$sql = Query::getInstance()->query("SELECT * FROM market LIMIT ? OFFSET ?", array($i, $x));
var_dump($sql);
I didn't put here full source code, I think there is a problem in query function but I'm not able to find it.
ERROR IMAGE
Thanks nogad,
All i do is set this at the beginning of query function:
$this->db->setAttribute( PDO::ATTR_EMULATE_PREPARES, false );
Related
How to implode and insert values into the database in CodeIgniter?
I am creating multiple choice quiz script using CodeIgniter framework. I want to store user results like this:
id userid q_id answer_id time_taken
1 1 1,2,3,4,5 2,3,4,5,3 4,5,7,6,7
in my controller:
public function insert_result()
{
$this->load->model('quiz_models');
$user_id=$this->input->post('user_id');
$qq_id=$this->input->post('questionid');
$answer_id=$this->input->post('AnswerID');
$time_taken=$this->input->post('timetaken');
$question_no=$this->input->post('question_no');
$bd = "$question_no";
switch ($bd) {
case"1":
$data=array('user_id'=>$user_id,
'q_id'=>$qq_id,
'answer_id'=>$answer_id,
'time_taken'=>$time_taken);
$this->quiz_models->insert_result($data);
break;
case"2":
quiz_test();
break;
case"3":
quiz_test();
break;
case"4":
quiz_test();
break;
case"5":
quiz_test();
$this->session->unset_userdata('lastids');
break;
default:
echo "something is wrong";
}
}
public function quiz_test()
{
$this->load->model('quiz_models');
$quiz=$this->quiz_models->quiz_test();
foreach($quiz as $row){
$qid=$row->q_id;
$ans=$row->answer_id;
$time=$row->time_taken;
$a = array("$qq_id","$qid");
$b = array("$answer_id","$ans");
$c = array("$time_taken","$time");
$comma = implode(",",$a);
$comma1 = implode(",",$b);
$comma2 = implode(",",$c);
$data=array('q_id'=>$comma,
'answer_id'=>$comma1,
'time_taken'=>$comma2);
$this->quiz_model->update_result($data);
}
}
}
and Model:
function insert_result($data)
{
$this->dbb->insert('results',$data);
$sectio=$this->db->insert_id();
$this->session->set_userdata('lastids',$sectio);
}
function quiz_test()
{
$ses_id = $this->session->userdata('lastids');
$sql = "SELECT q_id, answer_id, time_taken FROM results WHERE id='$ses_id'";
$query = $this->dbb->query($sql);
$result = $query->result();
return $result;
}
function update_result($data){
$ses_id = $this->session->userdata('lastids');
$this->db->where('id',$ses_id);
$this->db->update('results',$data);
}
when i run it nothing happened,not showing any error where do i mistake?
pls help me what am i doing wrong
First of all - i think you've a major problem in your DB structure
Normalize your Data
You should prevent to store your information in the table like that.
It should be possible to normalize your data properly. If you dont know
how to do that the following link could be interesting:
Normalization in MYSQL
However a possible solution would be to structure your data:
In order to do that - create a save Method in your Model to split between update and insert - this model could look like
class Quiz_Models
{
private $arrPostData;
public function save($arrPostData = false)
{
$this->arrPostData = (!$arrPostData) ? $this->input->post() : $arrPostData;
$id = $this->session->userdata("lastids");
if ($id)
{
$query = $this->db
->select("*")
->from("results")
->where("id",$id)
->get();
if ($query->num_rows() == 1)
{
$this->update($query->row(0));
}
else return false;
}
else
{
$this->insert();
}
if ($this->arrPostData['question_no'] == 10) $this->session->unset_userdata("lastids");
}
private function update($objData)
{
$objCollection = new Quiz_Collection();
$objCollection->userId = $objData->userid;
$objCollection->id = $objData->id;
$arrData = explode($objData->q_id);
foreach($arrData AS $key => $quizId)
{
$objQuiz = new stdClass();
$objQuiz->q_id = $quizId;
$objQuiz->answer_id = explode($objData->answer_id)[$key];
$objQuiz->time_taken = explode($objData->answer_id)[$key];
$objCollection->append($objQuiz);
}
$objQuizFromPost = new stdClass();
$objQuizFromPost->q_id = $this->arrPostData["questionid"];
$objQuizFromPost->answer_id = $this->arrPostData['AnswerID'];
$objQuizFromPost->time_taken = $this->arrPostData['timetaken'];
$objCollection->addQuizFromPost($objQuizFromPost);
$this->db
->where("id",$objCollection->id)
->update("results",$objCollection->getDbData());
}
private function insert()
{
$objCollection = new Quiz_Collection();
$objCollection->userId = $this->arrPostData['user_id'];
$objQuizFromPost = new stdClass();
$objQuizFromPost->q_id = $this->arrPostData["questionid"];
$objQuizFromPost->answer_id = $this->arrPostData['AnswerID'];
$objQuizFromPost->time_taken = $this->arrPostData['timetaken'];
$objCollection->addQuizFromPost($objQuizFromPost);
$this->db->insert("results",$objCollection->getDbData());
$this->session->set_userdata("lastids", $this->db->insert_id());
}
}
as an addition you need a Collection Object (put this below your model)
class Quiz_Collection extends Array_Object
{
public $userId = 0;
public $id = 0;
public function addQuizFromPost($objQuiz)
{
if (intval($objQuiz->q_id) > 0)
{
foreach($this AS $key => $obj)
{
if ($obj->q_id == $objQuiz->q_id)
{
$this->offsetSet($key, $objQuiz);
return true;
}
}
$this->append($objQuiz);
return true;
}
return false;
}
public function sortQuizData($objA, $objB)
{
if ($objA->q_id == $objB->q_id) return 0;
return ($objA->q_id < $objB->q_id) ? -1 : 1;
}
public function getDbData()
{
$this->uasort(array($this,"sortQuizData"));
$arrData = $this->getArrayCopy();
$arrDbData = [
"userid" => $this->userId,
"q_id" => implode(array_map(function($obj){ return $obj->q_id;},$arrData),","),
"answer_id" => implode(array_map(function($obj){ return $obj->answer_id;},$arrData),","),
"time_taken" => implode(array_map(function($obj){ return $obj->time_taken;},$arrData),","),
];
return $arrDbData;
}
}
pS: this is just an instruction how you can do that in a proper way. Pls study this code. If you still don't understand whats going on, feel free to ask.
Am working on a student portal, below is the code i used for students position but, every user keeps getting 1st position. Every student seems to have 1st position, when they check their results from the front view. Cant seem to figure out where the problem is from in the code
function get_position($student, $class, $session, $term){
$this->db->select('*');
$this->db->from('result');
$this->db->where(array( 'class_id'=>$class, 'Session'=>$session, 'Term'=>$term));
$this->db->order_by('Total', 'asc');
$other_results = $this->db->get()->result_array();
$this->db->select("*");
$this->db->from('result');
$this->db->where(array('class_id'=> $class, 'Session'=>$session, 'Term'=>$term, 'StudentID'=>$student ));
$student_result = $this->db->get()->result_array();
$student_total = $this->get_student_total($student_result);
$position =1;
foreach($other_results as $res){
if($student_total < $res['Total']){
$position++;
}
}
return $position;
}
function get_student_total($result){
$total = 0;
foreach($result as $res){
$total+= $res['Total'];
}
return $total;
}
}
?>
I am assuming that the result table may have many records for a given studentID. Several test scores (Totals) for each student during the term right?
This should do the trick
public function get_position($student, $class, $session, $term)
{
//I like to use db method chaining.
$ranking = $this->db->select('StudentID')
->select_sum('Total', 'sumScore')
->from('result')
->where(array('class_id' => $class, 'Session' => $session, 'Term' => $term))
->group_by('StudentID')
->order_by('sumScore', 'desc')
->get()->result_array();
//The code above retrieves results from a query statement that looks like this:
//SELECT `StudentID`, SUM(`Total`) as sumScore
//FROM `result` where `class_id` = $class and `Session` = $session and `Term` = $term
//GROUP BY `StudentID`
//order by `sumScore` desc
$position = 1;
foreach($ranking as $rank)
{
if($rank['StudentID'] !== $student)
{
++$position;
}
else
{
return $position;
}
}
return NULL; //to indicate studentID was not found
}
I have a select query and then another select query but for another table. I need to run the first query, then if it finds something, show a table with a foreach loop. And then, a second query run and select another table with a foreach loop too.
This is my DB class to run my DB :
class DB {
private static $_instance = null;
private $_pdo,
$_query,
$_error = false,
$_count = 0;
public $_results;
private function __construct() {
try {
$this->_pdo = new PDO(...);
} catch(PDOException $e) {
die($e->getMessage());
}
}
public static function getInstance() {
if(!isset(self::$_instance)) {
self::$_instance = new DB();
}
return self::$_instance;
}
public function query($sql, $params = array()) {
$this->_error = false;
if($this->_query = $this->_pdo->prepare($sql)) {
$x = 1;
if(count($params)) {
foreach($params as $param) {
$this->_query->bindValue($x, $param);
$x++;
}
}
if($this->_query->execute()) {
$this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ);
$this->_count = $this->_query->rowCount();
} else {
$this->_error = true;
}
}
return $this;
}
Then, on a page I have this following :
<?php if ($st = DB::getInstance()->query("SELECT * FROM resum WHERE form_id = ? ORDER by date DESC", array(Input::get('formID')))) {
if ($st->count()) { ?>
<div id="topSeparateurClient">
<div>Date</div>
<div>Concessionnaire</div>
<div>Client</div>
<div>Voiture</div>
<div>Prix</div>
<div>Statut</div>
</div>
<div style="clear:both;"></div>
<?php
foreach($st->_results as $result) {
echo "<div class=\"clientGenInfos\">
<div><b>".substr($result->date, 0, 10)."</b> / ".substr($result->date, 10)."</div>
<div>".$result->concessionnaire."</div>
<div>".$result->client."</div>
<div>".$result->voiture."</div>
<div>".$result->prix."</div>";
if ($result->statut == 'En Attente') {
echo '<div class="enAttente"><span>En Attente</span></div>';
} else if ($result->statut == 'Accepter') {
echo '<div class="accepter"><span>Accepter</span></div>';
} else if ($result->statut == 'Refuser') {
echo '<div class="refuser"><span>Refuser</span></div>';
}
echo " </div>
";
}
} else {
echo '<div class="aucuneDemande">Nothing from now.</div>';
}
}
?>
Then a second block, almost identical but with another table name in his query. The problem now is that my second table have the same values as the first one..I am stuck here, reading stuff on the net and nothing about this situation. I am still new to PDO object! please help!
EDIT ---
This is my second block..
<?php
if ($st = DB::getInstance()->query("SELECT * FROM users WHERE users.group = 3 ORDER by date DESC")) {
if ($st->count()) { ?>
<div id="topSeparateurClientConc">
<div>Prénom et Nom</div>
<div>Adresse</div>
<div>Nom d'utilisateur</div>
<div>Date d'inscription</div>
<div>Demandes reçues</div>
</div>
<div style="clear:both;"></div>
<?php
foreach($st->_results as $result2) {
echo "<div class=\"clientGenInfosConc\">
<div>".$result2->name."</div>
<div>".$result2->adresse."</div>
<div>".$result2->username."</div>
<div><b>".substr($result2->joined, 0, 10)."</b> / ".substr($result2->joined, 10)."</div>
<div>".$result2->concessionnaire."</div>
</div>";
}
} else {
echo '<div class="aucuneDemande">Aucune demande transférable en ce moment</div>';
}
}
?>
Do not write your own PDO wrapper. Period.
PDO is already a wrapper. Written by the professionals. It has some drawbacks, but at least it has no harmful features which newbie programmers introduce in hundreds.
If you want static method to get instance - all right, have it. But leave the rest for raw PDO. Saving yourself one function call doesn't worth struggling against fallacies of your own wrapper.
Do not save on calls at all! Look what are you doing:
<?php if ($st = DB::getInstance()->query("SELECT * FROM resum WHERE form_id = ? ORDER by date DESC", array(Input::get('formID'))))
It cannot be even read without scrolling. Are you fined for every extra line or what?
This one single line contains almost dozen operators!
This is called "write-only" style.
You are saving yourself a linefeed to write faster, but when it come to reading, you'll run here, crying "read my code for me!".
Always code as if the person who ends up maintaining your code is a violent psychopath who knows where you live.
Especially if it's you who have to maintain. Look:
<?php
$sql = "SELECT * FROM resum WHERE form_id = ? ORDER by date DESC";
$st = DB::getInstance()->query($sql, array(Input::get('formID')));
if ($st)
One can read and comprehend it. And noone died for splitting this call in four lines. Now add a couple:
$sql = "SELECT * FROM resum WHERE form_id = ? ORDER by date DESC";
$st = DB::getInstance()->prepare($sql);
$st->execute(array(Input::get('formID')));
$data = $st->fetchAll();
if ($data)
assuming getInstance() returns raw PDO instance. And your code will be perfectly fine working.
All right, I can understand a programmer's desire to avoid repetitions. Here is a solution that solves this problem without drawbacks:
$sql = "SELECT * FROM resum WHERE form_id = ? ORDER by date DESC";
$data = DB::prepare($sql)->execute(array(Input::get('formID')))->fetchAll();
And quit that idea of writing SQL calls right in the template. Fetch all your data first and then include a file with markup.
<?php if ($data): ?>
<div id="topSeparateurClientConc">
<div>Prénom et Nom</div>
<div>Adresse</div>
<div>Nom d'utilisateur</div>
<div>Date d'inscription</div>
<div>Demandes reçues</div>
</div>
<div style="clear:both;"></div>
<?php foreach($data as $result2): ?>
<div class="clientGenInfosConc">
After I prepare mysqli statement, and bind parameters to it, can I pass this object to a function?
For example code like this
$prepSQL = "DELETE FROM tbl_limit_rates
WHERE prod_code = ? AND prod_type = ? AND prod_rate = ?";
$stmtDelLimO = $mysqli->prepare($prepSQL);
$stmtDelLimO->bind_param("isd", $prodCode, $prodType, $prodRate);
$prodCode = 2;
$prodType = "Food";
$prodRate = "15.4";
$quatity = 0;
$test = adjustLimit($quantity, $stmtDelLimO);
echo $test;
function adjustLimit ($quantity, $stmtDelLimO)
{
if ($quantity == 0)
{
$stmtDelLimo->execute();
return true;
}
else
{
return false;
}
}
The function is not working and I am not sure if it's even allowed to use it like this or if I have some other error.
I have a foreach loop that iterates through an array.
In each instance, I organise the array into a query string and use MySQLi to add it to the database.
function storeProperties($data, $db) {
foreach ($data['property'] as $property) {
$query_string = "INSERT INTO table VALUES(..., ..., ...,)"
$db->query($query_string);
echo $db->error;
}
}
Is there a better way I should be doing this?
Obviously, this method uses n database queries one after another so this is memory intensive and time intensive.
Is there a better way to do this?
Should I be concatenating each query into a single string and running it all outside the for loop?
The following method is from my PDO workhorse, used for bulk insertions. It creates a single INSERT statement with multiple VALUES entries.
Use it as
$db->bulkinsert(
'tbl_my_tablename',
array('fieldname_1','fieldname_2', 'fieldname_3'),
array(
/* rec1 */ array('r1f1', 'r1f2', 'r1f3'),
/* rec2 */ array('r2f1', 'r2f2', 'r2f3'),
/* rec3 */ array('r3f1', 'r3f2', 'r3f3')
));
Please note that the method is an snip from a complex class definition, some methods used here are not contained in the code snippet, especially $this->connect() (connects to PDO),$this->begin() (starts transaction), $this->commit()and $this->rollback(), and the static Log class for Logging similar to Apache Commons ;-)
But I'm sure this is what you might need.
/**
* Performs fast bulk insertion
* Parameters:
* $tablename
* $datafields - non-assiciative array of fieldnames
* or propertynames if $data is an array of objects
* $data - array of either non-associative arrays (in the correct order)
* or array of objects with property names matching the $datafields array
*/
const MAX_BULK_DATA = 3000;
public function bulkinsert($tablename, $datafields, &$data) {
$result = 0;
try {
try {
$this->connect();
$datacount = count($data);
// loop until all data has been processed
$start = 0;
$lastbinds = 0;
$this->begin();
while ($start < $datacount) {
$ins = array();
$bindscount = min(self::MAX_BULK_DATA, $datacount - $start);
if ($bindscount != $lastbinds) {
// prepare the binds
$binds = substr(str_repeat(',?', count($datafields)), 1);
$binds = substr(str_repeat(",($binds)", $bindscount), 1);
$lastbinds = $bindscount;
}
for ($go = $start, $last = $start + $bindscount; $go < $last; $go++) {
if (is_object($data[$go])) {
try {
foreach($datafields as $propname) {
$rfl = new ReflectionProperty($data[$go], $propname);
$rfl->setAccessible(true);
$ins[] = $rfl->getValue($data[$go]);
}
}
catch(ReflectionException $e) {
throw new InvalidArgumentException('PDOCONNECT_ERR_SQL_UNKNOWN_PROPERTY', 0, $e);
}
}
else {
foreach($data[$go] as $value) {
$ins[] = $value;
}
}
}
$sql = sprintf('INSERT INTO %s (%s) VALUES %s', $tablename, join(',',$datafields), $binds);
Log::trace($sql);
$stmt = $this->pdo->prepare($sql);
$stmt->execute($ins);
$start = $last;
$result += $bindscount;
}
$this->commit();
}
catch(PDOException $e) {
// do something with the exception if necessary
throw $e;
}
}
catch(Exception $e) {
$this->rollback();
throw $e;
}
return $result;
}
}