Mysql Left Join DataTable Serverside Codeigniter - mysql

Can you help me on this?
No tables used
SELECT * ORDER BY id asc LIMIT 0
This is my sql code on the model
private function _get_datatables_query()
{
$this->db->query("SELECT mainproduk.id,
mainproduk.barcode as barcod,
mainproduk.nama_produk,
mainproduk.nama_alias,
mainproduk.satuan,
mainproduk.produk_jadi,
mainproduk.kemasan,
mainproduk.min_stok_kemasan,
mainproduk.status,
mainproduk.top_item,
mainproduk.tipe_produk,
mainproduk.nomor_kemtan,
coalesce(sum(R.jumlah_pc),0) as omzet
FROM mainproduk
LEFT JOIN
(
SELECT id,barcode, jumlah_pc
FROM rincian_order WHERE tipe='po' AND status!='canceled' AND tanggal_kirim BETWEEN '$kemarins' AND '$blnkemarin'
) AS R
ON mainproduk.barcode = R.barcode WHERE status=1 GROUP BY mainproduk.id ORDER BY mainproduk.id ASC");
$i = 0;
foreach ($this->column_search as $item) // loop column
{
if($_POST['search']['value']) // if datatable send POST for search
{
if($i===0) // first loop
{
$this->db->group_start(); // open bracket. query Where with OR clause better with bracket. because maybe can combine with other WHERE with AND.
$this->db->like($item, $_POST['search']['value']);
}
else
{
$this->db->or_like($item, $_POST['search']['value']);
}
if(count($this->column_search) - 1 == $i) //last loop
$this->db->group_end(); //close bracket
}
$i++;
}
if(isset($_POST['order'])) // here order processing
{
$this->db->order_by($this->column_order[$_POST['order']['0']['column']], $_POST['order']['0']['dir']);
}
else if(isset($this->order))
{
$order = $this->order;
$this->db->order_by(key($order), $order[key($order)]);
}
}
When I use the above method will appear no table problem is used, because the recording is off.
then I change it with the active record like below and there is an error that seems "COALESCE" does not support in such format, then if "coalesce (sum (details_order.jumlah_pc), 0) as omzet" I delete it will appear error as below this
private function _get_datatables_query()
{
$this->db->select('mainproduk.barcode as barcod, mainproduk.nama_produk, mainproduk.nama_alias, mainproduk.satuan, mainproduk.produk_jadi, mainproduk.kemasan, mainproduk.min_stok_kemasan, mainproduk.status, mainproduk.top_item, mainproduk.tipe_produk, mainproduk.nomor_kemtan, coalesce(sum(rincian_order.jumlah_pc),0) as omzet')
->from('mainproduk')
->join('rincian_order', 'mainproduk.barcode = rincian_order.barcode', 'left')
->where('mainproduk.status =', 1)
->group_by('mainproduk.id')
->order_by('mainproduk.id', 'ASC');
$i = 0;
foreach ($this->column_search as $item) // loop column
{
if($_POST['search']['value']) // if datatable send POST for search
{
if($i===0) // first loop
{
$this->db->group_start(); // open bracket. query Where with OR clause better with bracket. because maybe can combine with other WHERE with AND.
$this->db->like($item, $_POST['search']['value']);
}
else
{
$this->db->or_like($item, $_POST['search']['value']);
}
if(count($this->column_search) - 1 == $i) //last loop
$this->db->group_end(); //close bracket
}
$i++;
}
if(isset($_POST['order'])) // here order processing
{
$this->db->order_by($this->column_order[$_POST['order']['0']['column']], $_POST['order']['0']['dir']);
}
else if(isset($this->order))
{
$order = $this->order;
$this->db->order_by(key($order), $order[key($order)]);
}
}
Column 'id' in order clause is ambiguous
Please help

`mainproduk.id`
`mainproduk.barcode`
similarly to other fields
try writing this as your syntax.
if that doesn't work can you print_r the query ?

Related

draw datatable is null when i use where in my query

I have some problem with showing data in datatable, the problem is when I using the query clause like where condition, the draw in datatable is had a null value but when I'm not using the where condition, the data will be display on my datatable, is anything wrong with my query in codeigniter?
model :
var $attendance = 'attendance';
var $employee = 'employee';
var $project = 'project';
var $column = [
null, 'attendance.no_reg', 'employee.name', 'project.project_name', 'project.project_code'
];
var $column_search = [
'attendance.no_reg', 'employee.name', 'project.project_name', 'project.project_code'
];
var $column_order = [
null, 'attendance.no_reg', 'employee.name', 'project.project_name', 'project.project_code'
];
private function _showDaily() {
$selectedValues = $this->input->post('selectedValues');
$this->db->select($this->column);
$this->db->from($this->attendance);
// $this->db->where("project_code", $selectedValues);
$this->db->join($this->employee, "attendance.no_reg = employee.no_reg");
$this->db->join($this->project, "attendance.project_id = project.id");
$this->db->group_by("attendance.no_reg");
// length table
$i = 0;
foreach ($this->column_search as $item) // initial looping for grouping insert a text search
{
error_reporting(0);
if ($_POST['search']['value']) { // if the datatable make a input search with POST method
if ($i === 0) { // initial first condition for first column
$this->db->group_start();
$this->db->like($item, $_POST['search']['value']);
} else {
$this->db->or_like($item, $_POST['search']['value']);
}
if (count($this->column_search) - 1 == $i) // condition if the text search value counting same with $i value then minus 1
$this->db->group_end();
}
$i++;
}
if (isset($_POST['order'])) {
$this->db->order_by($this->column_order[$_POST['order']['0']['column']], $_POST['order']['0']['dir']);
}
}
public function showsDaily()
{
$this->_showDaily();
$result = $this->db->get();
return $result->result();
}
If my explanation is incomprehensible, I apologize, and you can ask me again, Thank You

Yii2 ActiveRecord add a new record with unique text field

I am using Yii2 and ActiveRecord. I have a field called "code" and for each record, it is meant to have a unique value like this: "REC0001", "REC0002", "REC0003" in a sequencial manner.
All works and I can generate a record code as described. However if I refresh my page request fast in a multiple manner (trying to test multiple requests at the same time in a very raw manner hehe), then some of the records end up with the same record code. In other words I found "REC007" a few times.
I generate the code looking at the last code and increase it by one, then I do a while foundFlag == true by checking to see if it already exists in the database.
I am suspecting there is a delay in writing to the database and hence it assumes that it is not there.
Here is a portion of the code:
static function createCode($rec){
if ($rec->code){
return $rec->code;
}
if ($rec->id){ // find it by id if one passed and record exists
$tmpRec = $rec->find()
->where([
'id' => $rec->id,
])
->one();
if ($tmpRec && $tmpRec->code){
return $tmpRec->code;
}
}
$prefix = 'REC';
if (!$prefix){
$prefix = 'REC';
}
$maxDecimals = 12;
$codeLength = $maxDecimals+strlen($prefix);
$query = $rec->find();
$query = $query->where([
'archived' => '0'
]);
// look under an organization if it exists in the model and there is one
if ($rec->hasField('organization_id') && $organization_id){
$query = addQueryWhere($query, [
'organization_id' => $organization_id,
]);
}
$query = addQueryWhere($query, [
'LENGTH(code)' => $codeLength*1,
]);
$query = $query->orderBy('code desc');
$lastRec = $query->one();
$tmpNumber = 0;
if ($lastRec && $lastRec->id){
// check what it returns
$tmpNumber = str_replace($prefix, '', $lastRec->code);
}
$tmpNumber++;
$leftDecimals = $maxDecimals - strlen($tmpNumber.'');
for ($k=0; $k <= $leftDecimals-1 ; $k++){
$tmpNumber = '0'. $tmpNumber;
}
$ret = $prefix . $tmpNumber;
return $ret;
}
public function generateCode($rec){
$foundFlag = true;
$break = 1000; // safe break point - no continuous loop
$cnt = 0;
$code = static::createCode($rec);
while ($foundFlag === true || $cnt < $break){
$tmpRec = $rec->find()
->where([
'code' => $code,
])
->one();
if (!$tmpRec->id){
$foundFlag = false;
break;
}
$time = getCurrentTimestamp();
$code = static::createCode($rec);
$cnt++;
}
$ret = $code;
return $ret;
}
So I simply call: $this->code = $this->generateCode();
Like I said it does work in generating the code, but it creates duplicates when it shouldn't!
Thank you for your assistance.

SQL can't found any values

i'm having trouble returning values of sql rows, my SQL request work well on console but can't return a row of it with my code, any help ? thanks !
<?php
require_once 'sql.php';
$sqlConnexion = new mysqli($hn,$un,$pw,$db);
if($sqlConnexion->connect_error){
die ('Soucis de connexion SQL');}
$date = date("d/m/y G:i:s");
if(isset($_POST['zoneDeText'])){
$area = $_POST['zoneDeText'];
$queryone= "SELECT SortieTraitée FROM entry WHERE entréesUtilisateurs=?";
$instruction = $sqlConnexion->prepare($queryone);
if(!$instruction->prepare($queryone)){
echo "$instruction->errno";
}else{
$instruction->bind_param('s', $area);
$instruction->execute();
$result = $instruction->get_result();
while ($row = $result->fetch_array(MYSQLI_NUM)){
foreach ($row as $out){
if($out == $area){
echo $out;
}elseif($out != $area){
echo 'Still not found';
}
}
}
$instruction->close();
}
?>
You don't actually print anything, you just return the value, which makes no sense unless your code is inside a function.
if($out == $area){
return $out;
}
The documentation http://php.net/return says:
If return is called from within the main script file, then script execution ends.
Unless the code you show above has been included in another PHP script, that means it will just end the script and output nothing.
There are several other confusing things your script, but the above is probably the one directly responsible for the problem you're asking about.
Here's how I might write this code:
if (isset($_POST['zoneDeText'])) {
$area = $_POST['zoneDeText'];
$queryone = "SELECT SortieTraitée FROM entry WHERE entréesUtilisateurs=?";
$instruction = $sqlConnexion->prepare($queryone);
// if the prepare fails, it is false
if ($instruction === false) {
// false is not an object, it has no error attribute
// the error is an attribute of the connection
die($sqlConnexion->error);
}
$instruction->bind_param('s', $area);
$instruction->execute();
$result = $instruction->get_result();
// if there are zero rows in the result, the while loop
// will finish before it starts, so there will be no output
// so first check for a result of zero rows in the result
if ($result->num_rows == 0) {
echo("Found zero rows");
} else {
while ($row = $result->fetch_assoc()) {
echo $row["SortieTraitée"];
}
}
$instruction->close();
}

Get data into array using mysql prepared statements

I'm trying to get the function below to return an array of user_ids. Here is the function in php.
function users_following($follower_id)
{
include "dbconn.php";
$stmt = mysqli_prepare($con, "SELECT user_id FROM follo WHERE follower_id = ?");
mysqli_stmt_bind_param($stmt, "i", $follower_id);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $following_user_id);
$count = 0;
$user_array = array();
while (mysqli_stmt_fetch($stmt) ) {
$user_array[] = $following_user_id;
$count = $count + 1;
}
mysqli_stmt_close($stmt);
if ($count > 0)
{
return $user_array;
} else {
return false;
}
}
The problem is that the above function just returns the output: 'Array' (without quotes), when I tested with the code below, not the list of user_ids.
$userid_array = users_following($_SESSION["user_id"]);
echo $userid_array;
Can anyone please help me out? If you need additional details, just comment below and I will try to clarify.

Was: Grab the last inserted id - mysql Now: Where should we call the last insert id?

Here's the thing, I don't have access to code that inserts data into a given table. However, I need to add related additional data into another table. So, I was thinking about grabbing the last inserted ID and from there... insert the related data into that other table.
Since I don't have access to the statement, I believe that mysql last insert id function will be of no use here.
All the PDO::lastInsertId examples that I see, are also attached to some "insert query" before it, so no use as well.
How can I grab the last inserted ID on the cases were we DON'T have access to the original insert statement ?
Data flow:
It starts here: signup.tpl
Where we have:
onclick="checkoutvalidate();return false"
On the js we have:
function checkoutvalidate() {
$.post("order/index.php", 'a=validatecheckout&'+$("#orderfrm").serialize(),
function(data){
if (data) {
...
} else {
document.orderfrm.submit();
}
});
So, now, let's look for "validatecheckout" into index.php
And we found it:
We can't read along this lines, anything concerning the insertion. The immediately after that I can get is, after the conditional statement - right ?
if ($a=="validatecheckout") {
$errormessage = '';
$productinfo = getProductInfo($pid);
if ($productinfo['type']=='server') {
if (!$hostname) $errormessage .= "<li>".$_LANG['ordererrorservernohostname'];
else {
$result = select_query("tblhosting","COUNT(*)",array("domain"=>$hostname.'.'.$domain,"domainstatus"=>array("sqltype"=>"NEQ","value"=>"Cancelled"),"domainstatus"=>array("sqltype"=>"NEQ","value"=>"Terminated"),"domainstatus"=>array("sqltype"=>"NEQ","value"=>"Fraud")));
$data = mysql_fetch_array($result);
$existingcount = $data[0];
if ($existingcount) $errormessage .= "<li>".$_LANG['ordererrorserverhostnameinuse'];
}
if ((!$ns1prefix)OR(!$ns2prefix)) $errormessage .= "<li>".$_LANG['ordererrorservernonameservers'];
if (!$rootpw) $errormessage .= "<li>".$_LANG['ordererrorservernorootpw'];
}
if (is_array($configoption)) {
foreach ($configoption AS $opid=>$opid2) {
$result = select_query("tblproductconfigoptions","",array("id"=>$opid));
$data = mysql_fetch_array($result);
$optionname = $data["optionname"];
$optiontype = $data["optiontype"];
$qtyminimum = $data["qtyminimum"];
$qtymaximum = $data["qtymaximum"];
if ($optiontype==4) {
$opid2 = (int)$opid2;
if ($opid2<0) $opid2=0;
if ((($qtyminimum)OR($qtymaximum))AND(($opid2<$qtyminimum)OR($opid2>$qtymaximum))) {
$errormessage .= "<li>".sprintf($_LANG['configoptionqtyminmax'],$optionname,$qtyminimum,$qtymaximum);
$opid2=0;
}
}
}
}
$errormessage .= checkCustomFields($customfield);
if (!$_SESSION['uid']) {
if ($_REQUEST['signuptype']=="new") {
$firstname = $_REQUEST['firstname'];
$lastname = $_REQUEST['lastname'];
$companyname = $_REQUEST['companyname'];
$email = $_REQUEST['email'];
$address1 = $_REQUEST['address1'];
$address2 = $_REQUEST['address2'];
$city = $_REQUEST['city'];
$state = $_REQUEST['state'];
$postcode = $_REQUEST['postcode'];
$country = $_REQUEST['country'];
$phonenumber = $_REQUEST['phonenumber'];
$password1 = $_REQUEST['password1'];
$password2 = $_REQUEST['password2'];
$temperrormsg = $errormessage;
$errormessage = $temperrormsg.checkDetailsareValid($firstname,$lastname,$email,$address1,$city,$state,$postcode,$phonenumber,$password1,$password2);
$errormessage .= checkPasswordStrength($password1);
} else {
$username = $_REQUEST['username'];
$password = $_REQUEST['password'];
if (!validateClientLogin($username,$password)) $errormessage .= "<li>".$_LANG['loginincorrect'];
}
}
if (($CONFIG['EnableTOSAccept'])AND(!$_REQUEST['accepttos'])) $errormessage .= "<li>".$_LANG['ordererrortermsofservice'];
$_SESSION['cart']['paymentmethod'] = $_REQUEST['paymentmethod'];
if ($errormessage) echo $_LANG['ordererrorsoccurred']."<br /><ul>".$errormessage."</ul>";
else {
if ($_REQUEST['signuptype']=="new") {
$userid = addClient($firstname,$lastname,$companyname,$email,$address1,$address2,$city,$state,$postcode,$country,$phonenumber,$password1);
}
}
//DO THE DO INSERT_LAST_ID() here ?
}
Thanks in advance,
MEM
After the insert statement you can fire another query:
SELECT LAST_INSERT_ID();
and this will return one row with one column containing the id.
Docs: http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_last-insert-id
mysql> SELECT LAST_INSERT_ID();
-> 195
This works per connection so there is no problem if another thread writes into the table. But your SELECT needs to be executed 'RIGHT AFTER'/'As the next query' after the insert query ran
Edit
An example:
$dbConnection = MyMagic::getMeTheDatabase("please");
$oSomeFunkyCode->createThatOneRowInTheDatabase($dbConnection);
$result = $dbConnection->query("SELECT LAST_INSERT_ID();");
// ... fetch that one value and you are good to go
If the column is a simple auto_incrementing integer, you could use SELECT MAX(MyAutoincrementingColumn) FROM MyTable. You might risk selecting a row that has been inserted by another user in the meantime, if your users are not using transactions.
If you don't have access to the last INSERT line, you can make a subquery to find the last inserted id:
select max(id) from <table>