我有一个连接到Mysql DB的函数,它在“正常”调用中运行良好,但无法连接以响应ajax调用。
php代码:
// 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>';
}
从'普通'php调用它时效果很好。
ajax电话:
$.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);
}
});
我收到此错误:
Fatal error: Call to a member function select() on a non-object
我确定它是因为ajax调用,也许它无法正确加载全局$ db var。我有什么想法解决这个问题?
非常感谢
*注意:我知道我应该使用mysqli,但整个项目是用这个构建的,我无法改变它
答案 0 :(得分:0)
当你从php项目中调用/包含这个文件时,你可能在某个地方定义了全局变量$ db并且也可以在这个文件中访问它。
但是如果你从你的网站上调用这个,那么所有的php都已经运行了,而且不存在全局变量...... - &GT;所以你必须包括f.e.你再次定义$ db变量的config.php!
的config.php:
$db = new mysqli(DB_HOST, DB_USER, DB_PW, DB_DB);
yourFile.php
require_once('./config.php');