I have a function that connects to Mysql DB that works great in a "normal" call, but fails to connect in response to ajax call.
The php code:
// return data to ShowDdl()
function getDDLdata($tablename) {
global $db;
$data = '';
$name = ($tablename == 'sapak' || $tablename == 'cupon' ? 'Name' : 'Hebrewname');
////****** $db IS NOT RECOGNIZED WHEN CALLING ShowDdl() FROM AJAX
////****** BUT WORKS GREAT IN NORMAL CALLS
$query = $db->select("SELECT `id` , `".$name."` AS name FROM `".$tablename."` ORDER BY `id` ASC");
for($i=0;$result = $db->get_row($query, 'MYSQL_ASSOC');$i++){
$data[$i] = $result;
}
return $data; // id, name
}
// echo ddl with current data from requested table
function ShowDdl($tablename, $sapakid = null) {
$possibletables = array (
'category', 'subcategory', 'brand', 'sapak', 'cupon'
);
$ddlname = '';
// find the correct name for the ddl
for ($i = 0; $i<count($possibletables); $i++) {
if ($possibletables[$i] == $tablename) {
// only cupon ddl should have different id and name
if ($tablename == 'cupon') {
$ddlname = 'sapak-'.$sapakid .'-cupon';
}
else {
$ddlname = 'product-' . $tablename;
}
continue;
}
}
echo '<select multiple id="'.$ddlname.'" name="'.$ddlname.'[]">';
$data = getDDLdata($tablename);
foreach ($data as $vn ) {
if ($vn['id'] != null) {
echo '
<option value="'.$vn['id'].'"> '.$vn['name'].' </option>
';
}
}
echo '</select>';
}
It works great when called from 'normal' php.
The ajax call:
$.ajax({
type: "GET",
url: 'moudels/product/generic_offer.php',
data: 'sid=' + sid + '&name=' + name,
success: function (data) {
$('<div id='+ sid + '> </div>').appendTo('#genericofferdiv');
// append the response to the new div
$("#"+sid).html(data);
}
});
I get this error:
Fatal error: Call to a member function select() on a non-object
I'm sure it it because the ajax call, maybe it can't load the global $db var correctly. Any ideas how I solve this?
Thank you very much
*Note: I know that I should use mysqli, but the whole project is build with this and I can't change it
When you call / include this file from within your php project, you probably defined somewhere the global variable $db and can access it in this file, too.
But if you call this from you website, all the php has run through and no global variable exist anymore...
-> So you have to include f.e. the config.php where you defined your $db variable again!
config.php:
$db = new mysqli(DB_HOST, DB_USER, DB_PW, DB_DB);
yourFile.php
require_once('./config.php');
Related
I've been working on creating an object oriented database call class for practice and I've been trying to figure out how to incorporate a scrollable cursor properly. I would like to be able to call this function in order to grab the next 10 records or a different function for the previous 10 records. I've gotten to the point where I can specify an offset for the records through the scrollable cursor but I cannot call the same function again to get the next set without passing in an incremented offset value.
How would I go about being able to specify a number of records per page and simply call getNextSet() or getPrevSet() in order to get the results I want.
My current line of thinking is setting a static variable somewhere and incrementing/deincrementing or resetting it accordingly then use that as the offset value in the functions. However, I believe I heard there was an issue with using static variables in instantiated classes.
Here's the code so far:
<?php
$i5DBconn = db2_connect("*LOCAL", "", "");
if (!$i5DBconn) {
echo "Database Connection failed. SQL Err:";
echo db2_conn_error();
echo "<br>";
echo db2_conn_errormsg();
die();
}
class queryDB{
var $query;
var $outputFunction;
var $parameters;
function performDBCall(){
global $i5DBconn;
$dbStatement = db2_prepare($i5DBconn, $this->query, array('cursor' => DB2_SCROLLABLE));
$i = 1;
foreach ($this->parameters as $param) {
db2_bind_param($dbStatement, $i, 'param', DB2_PARAM_IN);
$i++;
}
$result = db2_execute($dbStatement);
if (!$result){
echo "$this->query failed!. ";
echo 'SQLSTATE value: ' . db2_stmt_error();
echo ' Message: ' . db2_stmt_errormsg();
}
return $dbStatement;
}
}
class invoiceCall extends queryDB {
function testQueryFormatter($dbResultSet, $dataOffset){
$zebraStriping = 1;
?>
//snipped header row formatting
<?php
$rowLimit = 10;
while(($rowData = db2_fetch_array($dbResultSet, $dataOffset)) && ($zebraStriping < $rowLimit)){
list($dataNames) = $rowData;
?>
//snipped data formatting
<?php
$dataOffset++;
}
}
}
$offsetVal = 5;
$testQuery = new invoiceCall();
$testQuery->query = "select invoice#, status, amountpaid, amountbilled, invoicedate, paydate, custname, termofpay, balance from TESTSCHEMA.SAMPLE_INVOICE_TABLE";
//$testQuery->parameters = [8000001];
$resultSet = $testQuery->performDBCall();
$testQuery->testQueryFormatter($resultSet, $offsetVal);
?>
If there are also some coding practices I could improve on, let me know as I am starting my first real journey into Object Oriented PHP.
I am struggling to workout a good method to update one column of my wcx_options table.
The new data is sent fine to the controller but my function isn't working at all.
I assumed i could loop through each column by option_id updating with the values from the array.
The database:
I update the option_value column with the new information via a jQuery AJAX Call to a controller which then calls a function from the backend class.
So far i have the following code:
if(isset($_POST['selector'])) {
if($_POST['selector'] == 'general') {
if($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest' && isset($_POST['token'])
&& $_POST['token'] === $_SESSION['token']){
$site_name = $_POST['sitename'];
$site_url = $_POST['siteurl'];
$site_logo = $_POST['sitelogo'];
$site_tagline = $_POST['sitetagline'];
$site_description = $_POST['sitedescription'];
$site_admin = $_POST['siteadmin'];
$admin_email = $_POST['adminemail'];
$contact_info = $_POST['contactinfo'];
$site_disclaimer = $_POST['sitedisclaimer'];
$TimeZone = $_POST['TimeZone'];
$options = array($site_name, $site_url, $site_logo, $site_tagline, $site_description, $site_admin, $admin_email,$contact_info, $site_disclaimer, $TimeZone);
// Send the new data as an array to the update function
$backend->updateGeneralSettings($options);
}
else {
$_SESSION['status'] = '<div class="error">There was a Problem Updating the General Settings</div>';
}
}
}
This is what i have so far in terms of a function (It doesnt work):
public function updateGeneralSettings($options) {
$i = 1;
foreach($options as $option_value) {
$where = array('option_id' => $i);
$this->queryIt("UPDATE wcx_options SET option_value='$option_value' WHERE option_id='$where'");
$i++;
}
if($this->execute()) {
$_SESSION['success'] = 'Updated General Settings Successfully';
}
}
With the given DB-layout i'd suggest to organize your data as assiciative array using the db fieldnames, like:
$option = array(
'site_name' => $_POST['sitename'],
'site_url' => $_POST['siteurl'],
// etc.
'timeZone' => $_POST['TimeZone']
);
And than use the keys in your query:
public function updateGeneralSettings($options) {
foreach($options as $key => $value) {
$this->queryIt("UPDATE wcx_options SET option_value='$value' WHERE option_name='$key'");
if($this->execute()) {
$_SESSION['success'] = 'Updated General Settings Successfully';
}
}
}
(However, are you sure, you do not want to have all options together in one row?)
Change your query, you try to use an array as where condition. In the syntax you used that won't work. Just use the counter as where condition instead of define a $where variable. Try this:
public function updateGeneralSettings($options) {
$i = 1;
foreach($options as $option_value) {
$this->queryIt("UPDATE wcx_options SET option_value='$option_value' WHERE option_id='$i'");
$i++;
}
if($this->execute()) {
$_SESSION['success'] = 'Updated General Settings Successfully';
}
}
In my Codeigniter project ,table value is not retrieving from database.Am using MySQL (WAMP) as database.Using Select Query i have checked the data in database and its fine there.When updating the same also its retrieving the old value in db.But when retrieving the value in later stage (ie,taking old bill) its not retrieving the value.The problem is happening only on the single field(ie,actual_price).How to solve this error.Here am attaching the screenshot and controller code for the same.
Controller Code
function bill_view($billid)
{
if(!$billid) {
redirect('report/bill_report');
}
$salecode =str_replace("_","/",$billid);
$filter ="gm_sale.saleCode ='$salecode'";
$billArray =$this->sale_model->getBillinfo($filter);
$exshowroom='';
$bank ='';
$scheme='';
$wcoNo ='';
$saleId =0;
foreach($billArray as $key=>$val) {
$exshowroom = $val['actual_price'];
$date =$val['saledate'];
$sale_to=$val['saleCustomer'];
$saleUserId=$val['saleUserId'];
$wcoNo = $val['wcoNo'];
$saleId= $val['saleId'];
if(!is_null($val['bank']) && !empty($val['bank'])){
$bank =$val['bank'];
}
if(!is_null($val['scheme_id']) && !empty($val['scheme_id'])){
$array_scheme = unserialize($val['scheme_id']);
///////////////////////////////////////////
foreach ($array_scheme as $val_scheme_id) {
$res_scheme = $this->db->get_where("gm_scheme",array('id'=>(int)$val_scheme_id));
if($res_scheme->num_rows >0){
$arrscheme = $res_scheme->row_array();
if(!empty($scheme)) {
$scheme .= ",";
}
$scheme .= $arrscheme['schemeName'];
}
}
/////////////////////////////////////////////
}
break;
}
$query = $this->db->get_where('gm_users',array('userId'=>(int)$saleUserId));
if($query->num_rows >0) {
$arrUser =$query->row_array();
}else{
$arrUser =array();
}
$data['list_product'] = $billArray;
$data['exshowroom']=$exshowroom;
$data['userinfo'] =$arrUser;
$data['saleCode'] =$salecode;
$data['sale_to'] =$sale_to;
$data['added_date'] =$date;
$data['bank'] =$bank;
$data['scheme'] =$scheme;
$data['wcoNo'] =$wcoNo;
$data['saleId'] =$saleId;
$this->load->view('header_login');
$this->load->view('report/bill_view',$data);
//print_r($billArray);
$this->load->view('footer_login');
}
Model Code
function getBillinfo($filter=''){
$this->db->select('*,gm_sale.added_date as saledate');
$this->db->from('gm_sale',FALSE);
$this->db->join('gm_products',"gm_sale.productId=gm_products.productId",FALSE);
$this->db->join('gm_model',"gm_products.model_id=gm_model.id",FALSE);
$this->db->join('gm_banks',"gm_sale.bank_id=gm_banks.bank_id","LEFT");
if($filter<>"")
$this->db->where($filter,'',FALSE);
$this->db->order_by('gm_sale.saleId',"desc");
$query = $this->db->get();
print_r($query);
if($query->num_rows>0) {
$arrRow =$query->result_array();
print_r($arrRow);
return($arrRow);
}
return(array());
}
Your code that you have in the controller doing DB stuff should be in the model.
The controller does not have context to
$this->db
modify your joins (3rd param) to retrieve values in actual_price
I have a php file that i connect to it with ajax and callback value is JSON
when i get data from php it dosnt show and when alert data i see Object
Where is my problem ?
PHP:
if(isset($_SERVER["HTTP_X_REQUESTED_WITH"])){
$query = mysql_query("select * from tab");
for ($i=0;$i<mysql_num_rows($query);$i++){
while($row = mysql_fetch_assoc($query)){
$title['t'][i] = $row['title'];
$title['d'][i] = $row['description'];
}
}
echo(json_encode($title));
exit();
?>
JS:
$('#button').click(function(){
$.ajax({
url : "test2.php",
data : $("#tab"),
type : "GET",
success : function(b){
b = eval('('+ b +')');
console.log((b['t']));
alert(b);
}
});
});
How can i get all of data from this JSON and show me corect it ?
Here's a full working example with single row fetch and multi row fetch, without using mysql_ syntax and using prepared statements to prevent sql injections.
And yes, DON'T use mysql specific syntax, like I mentioned here: I cant get the form data to go into database. What am I doing wrong?
function example()
{
var select = true;
var url = '../scripts/ajax.php';
$.ajax(
{
// Post select to url.
type : 'post',
url : url,
dataType : 'json', // expected returned data format.
data :
{
'select' : select // the variable you're posting.
},
success : function(data)
{
// This happens AFTER the PHP has returned an JSON array,
// as explained below.
var result1, result2, message;
for(var i = 0; i < data.length; i++)
{
// Parse through the JSON array which was returned.
// A proper error handling should be added here (check if
// everything went successful or not)
result1 = data[i].result1;
result2 = data[i].result2;
message = data[i].message;
// Do something with result and result2, or message.
// For example:
$('#content').html(result1);
// Or just alert / log the data.
alert(result1);
}
},
complete : function(data)
{
// do something, not critical.
}
});
}
Now we need to receive the posted variable in ajax.php:
$select = isset($_POST['select']) ? $_POST['select'] : false;
The ternary operator lets $select's value become false if It's not set.
Make sure you got access to your database here:
$db = $GLOBALS['db']; // An example of a PDO database connection
Now, check if $select is requested (true) and then perform some database requests, and return them with JSON:
if($select)
{
// Fetch data from the database.
// Return the data with a JSON array (see below).
}
else
{
$json[] = array
(
'message' => 'Not Requested'
);
}
echo json_encode($json);
flush();
How you fetch the data from the database is of course optional, you can use JSON to fetch a single row from the database or you can use it return multiple rows.
Let me give you an example of how you can return multiple rows with json (which you will iterate through in the javascript (the data)):
function selectMultipleRows($db, $query)
{
$array = array();
$stmt = $db->prepare($query);
$stmt->execute();
if($result = $stmt->fetchAll(PDO::FETCH_ASSOC))
{
foreach($result as $res)
{
foreach($res as $key=>$val)
{
$temp[$key] = utf8_encode($val);
}
array_push($array, $temp);
}
return $array;
}
return false;
}
Then you can do something like this:
if($select)
{
$array = array();
$i = 0;
$query = 'SELECT e.result1, e.result2 FROM exampleTable e ORDER BY e.id ASC;';
foreach(selectMultipleRows($db, $query) as $row)
{
$array[$i]["result1"] = $row['result1'];
$array[$i]["result2"] = $row['result2'];
$i++;
}
if(!(empty($array))) // If something was fetched
{
while(list($key, $value) = each($array))
{
$json[] = array
(
'result1' => $value["result1"],
'result2' => $value["result2"],
'message' => 'success'
);
}
}
else // Nothing found in database
{
$json[] = array
(
'message' => 'nothing found'
);
}
}
// ...
Or, if you want to KISS (Keep it simple stupid):
Init a basic function which select some values from the database and returns a single row:
function getSingleRow($db, $query)
{
$stmt = $db->prepare($query);
$stmt->execute();
// $stmt->execute(array(":id"=>$someValue)); another approach to execute.
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if($result)
{
$array = (
'result1' => $result['result1'],
'result2' => $result['result2']
);
// An array is not needed for a single value.
return $array;
}
return false;
}
And then fetch the row (or the single value) and return it with JSON:
if($select)
{
// Assume that the previously defined query exists.
$results = getSingleRow($db, $query);
if($results !== false)
{
$json[] = array
(
'result1' => $results['result1'],
'result2' => $results['result2'],
'message' => 'success'
);
}
else // Nothing found in database
{
$json[] = array
(
'message' => 'nothing found'
);
}
}
// ...
And if you want to get the value of $("#tab") then you have to do something like $("#tab").val() or $("#tab").text().
I hope that helps.
I suggest to use either:
b = jQuery.parseJSON(data)
see more here
or
$.getJSON
instead of eval()
I looked at all the other posts on this and none of them came up with exactly what my problem is so here we go:
$dbh stores my PDO connection, if I do a var dump on it, it returns:
object(PDO)#1 (0) { }
So I know my PDO connection is working. I then use $sth to hold my query:
$c = 2;
$sth = $dbh->query("SELECT * FROM table WHERE ID = " . $c);
Then to make sure this is working I did:
echo $sth->rowCount();
That return a value of 6. So I know it is grabbing some rows. My next step of checking my problem was to fetch a single row like the following:
$row = $sth->fetch()
print_r($row);
This returned a single row (as it should) with the $row array filled exactly how I would expect it (column names as keys and column values as the array value).
So we are good up to this point. Once I move $row = $sth->fetch() into a while loop my script fails the error it returns is: Call to a member function fetch() on a non-object
Here is my while loop:
while($row = $sth->fetch()){
//while loop stuff here
}
I know it has something to do with the condition of the loop because even when I comment out all the stuff in the middle it still isn't working. What am I doing wrong? Why won't this work? I'm beyond confused on this as it has worked in the past with all the PDO I have done but for some reason it is failing in this script.
If anyone has any tips or something that can help it would be greatly appreciated.
EDIT Since ninetwozero's post worked, I'm posting my class and basically everything I've got to get this figured out.
class html_elements {
var $units;
var $useMaps;
var $cid;
var $uid;
var $companyMoney;
var $currCity;
var $terminals;
var $termLocs;
var $cityArray;
var $cargoArray;
var $cargo;
var $tid;
var $truckArray;
var $load;
var $cityID;
var $cargoID;
var $xp;
var $gasPrice;
var $warning;
function __construct($u, $maps, $c, $userID, $cMoney, $dbh, $city, $tid, $xp){
$this->units = $u;
$this->useMaps = $maps;
$this->cid = $c;
$this->uid = $userID;
$this->companyMoney = $cMoney;
$this->currCity = $city;
$this->terminals = array();
$this->termLocs = array();
$this->cityArray = array();
$this->cargoArray = array();
$this->cargo = array();
$this->tid = $tid;
$this->truckArray = array();
$this->load = 0;
$this->cityID = array();
$this->cargoID = array();
$this->xp = $xp;
$this->gasPrice = 0;
$sth = null;
$sth = $dbh->query("SELECT * FROM tblCTerminals WHERE companyID = " . $c);
//THIS LOOP FAILS
while($row = $sth->fetch()){
$this->termLocs[] = $row['Location'];
}
}
Then in another file that has my class file included in it is:
$h = new html_element($u->get_units(), $u->get_maps(), $u->get_company(), $u->get_user_id(), $c->get_money(), $dbh, $u->get_city(), $u->get_truck_id(), $u->get_xp());
Each of those getters work, I tested them. Also $dbh is what is used my connection file that is included before anything else. So I know all of that is working.
I got to say that you've encountered a pretty interesting error, so let's try some things to pinpoint the cause:
if( $sth == null ) die('My sth is null at #1');
while( $row = $sth->fetch() ) {
if( $row == null ) die('My row is null at #2');
echo '<pre>';
print_r($row);
echo '</pre>';
}
Let me know what this tells you.
Edit:
$sql = 'SELECT * FROM tblCTerminals WHERE companyID = ' . $c;
if( intval($c) == 0 ) { die('Aaaaaaaaaa.......aaaaah.');
foreach ($dbh->query($sql) as $row) {
echo '$row[\'Location\'] is: ' . $row['Location'] .'<br />';
$this->termLocs[] = $row['Location'];
}