Wonder if you can help me figure this out. Latest PHP in WordPress 3.92. WordPress is using MySqli. I am trying to change my custom MYSQL to MYSQLI which should really be simple enough, but is throwing up so issues.
Below are 2 examples. Example 1 is using WordPress built in MYSQLI connection inside a function and the one underneath is my own. The first one throws up errors as shown but my own one does not.
function name{
global $wpdb;
$options = array();
$res=mysqli_query($wpdb,"select ID,County from counties ORDER BY County ASC");
$value="";
$label="Please select a county";
$options[] = array('label' => $label, 'value' => $value);
while($row=mysqli_fetch_array($res)) {
$sC=$row['ID'];
$res1=mysqli_query($wpdb,"select County from wedding_shows where County='$sC'");
if (mysqli_num_rows($res1) == 0) {
} else {
$options[] = array('label' => $row['County'], 'value' => $row['ID']);
}
}
}
Here are the errors i get
Warning: mysqli_query() expects parameter 1 to be mysqli, object given eval()’d code on line 3
Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, null given eval()’d code on line 4
and here is it working with my own connection and no errors.
function name(
$dbhost1 = 'localhost';
$dbuser1 = 'user';
$dbpass1 = 'pass';
$dbname1 = 'DBName';
$conn=mysqli_connect($dbhost1 ,$dbuser1,$dbpass1,$dbname1);
$options = array();
$res=mysqli_query($conn,"select ID,County from counties ORDER BY County ASC");
$value="";
$label="Please select a county";
$options[] = array('label' => $label, 'value' => $value);
while($row=mysqli_fetch_array($res)) {
$sC=$row['ID'];
$res1=mysqli_query($conn,"select County from wedding_shows where County='$sC'");
if (mysqli_num_rows($res1) == 0) {
} else {
$options[] = array('label' => $row['County'], 'value' => $row['ID']);
}
}
}
I must be looking to hard as I cannot see why this would not work in the first instance to save having to create a new connection inside every function.
Many thanks
P
The first argument of mysqli_query is expected to be a mysqli connection object. $wpdb is not a mysqli connection object, it is the wordpress database object. That being said, you could just do $wpdb->get_results("select ID,County from counties ORDER BY County ASC"); instead, given that the query is proper.
Related
I'm getting this error while trying to execute my function.
The columns of my database are 100% correct and i tested every request and it worked!
Error :
[26-May-2018 05:21:49 UTC] PHP Notice: Array to string conversion in C:\wamp64\www\gcm\database.php on line 82
[26-May-2018 05:21:49 UTC] PHP Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given in C:\wamp64\www\gcm\database.php on line 88
My function:
function getHistoriqueNotification($user,$mdp){
$com = new DbConnect();
$message=array();
$sql="select UTLR_UID from adm_utilisateurs where UTLR_LOGIN='$user' and UTLR_MDP='$mdp'";
$result=mysqli_query($com->getDb(),$sql);
$getID = mysqli_fetch_assoc($result);
$userID = $getID['UTLR_UID'];
$sqli = "SELECT alr_alertes.ALRT_DES_LN1,alr_alertes.ALRT_PHOTO,alr_historiques.AHIS_DES_LN1,alr_historiques.AHIS_DATEHEURE from alr_alertes,alr_historiques WHERE alr_alertes.ALRT_UID=alr_historiques.ALRT_UID AND alr_historiques.UTLR_UID=$userID";
$resulti = mysqli_query($com->getDb(),$sqli);
while($row=mysqli_fetch_assoc($resulti)){
$message = array('photo' =>$row['ALRT_PHOTO'] , 'titre' => $row['ALRT_DES_LN1'] , 'dateHeure' =>$row['AHIS_DATEHEURE'] , 'detail' => $row['AHIS_DES_LN1']);
}
return $message;
}
When using mysqli you need to free up the results per each query. Since you made a query with the $sql and then a second query using the $sqli without freeing up the results in between the two queries it caused you the problem.
Please read on these mysqli functions:
http://php.net/manual/en/mysqli-result.free.php
Notice I closed your first connection and then made a second one. I think you can do this by keeping the same connection but calling mysqli_free_result() prior to your next query. I am not all that familiar with mysqli but I think that's right.
function getHistoriqueNotification($user, $mdp){
$com = new DbConnect();
$message=array();
$sql = "select UTLR_UID from adm_utilisateurs where UTLR_LOGIN='$user' and UTLR_MDP='$mdp'";
$result = mysqli_query($com->getDb(),$sql);
$getID = mysqli_fetch_assoc($result);
$userID = $getID['UTLR_UID'];
mysqli_close($com);
unset($com);
$com1 = new DbConnect(); //This is really just a test.
$sqli = "SELECT alr_alertes.ALRT_DES_LN1,alr_alertes.ALRT_PHOTO,alr_historiques.AHIS_DES_LN1,alr_historiques.AHIS_DATEHEURE from alr_alertes,alr_historiques WHERE alr_alertes.ALRT_UID=alr_historiques.ALRT_UID AND alr_historiques.UTLR_UID=$userID";
if ($resulti = mysqli_query($com1->getDb(), $sqli)){
while($row = mysqli_fetch_assoc($resulti)){
//Added the [] after message.
$message[] = array(
'photo' =>$row['ALRT_PHOTO'],
'titre' =>$row['ALRT_DES_LN1'],
'dateHeure' =>$row['AHIS_DATEHEURE'],
'detail' =>$row['AHIS_DES_LN1']
);
}
}else{
echo("Error description: " . mysqli_error($com1->getDb()));
}
print_r($message); //<---This will show you if you have a result.
return $message;
}
Very new to using mysql, however, I'm trying to fix a bug in an old piece of code in a wordpress plugin - here is the original code:
$sql = mysqli_query("SELECT count(`question_count`) as Qcount FROM `wp_posts` WHERE `question_count` = 1 and `question_date` = '".date("Y-m-d")."'") or die(mysql_error());
$no_of_questions = get_option( 'askme_setting_no_of_questions', 10 );
if($row = mysql_fetch_array($sql)) {
$qry = $row['Qcount'];
}
if($qry >= $no_of_questions) {
$value = "The question limit for today has been reached";
$button = "disabled";
} else {
$value = "Add your question to the cart";
$button = " ";
}
Which was giving the following error:
mysqli_query() expects at least 2 parameters, 1 given in
I have since changed the first line as follows to use Wordpress functions:
$sql = $wpdb->get_results( "SELECT count(`question_count`) as Qcount FROM `wp_posts` WHERE `question_count` = 1 and `question_date` = '".date("Y-m-d")."'" );
which now gives the following errors:
mysql_fetch_array() expects parameter 1 to be resource, array given in ...
Undefined variable: qry in ...
Is there something obvious that I am doing wrong here?
You should make mysqli connection first and then use queries and fetch queries further. You can follow the below link to use mysqli fetch queries.
https://www.w3schools.com/php/func_mysqli_fetch_array.asp
You're mixing things up.
mysql_ and mysqli_ are two completely different sets of functions in PHP. You can't send a query using the mysqli_ function, and manipulate the results with mysql_*.
Also, mysql_ functions were deprecated in later versions of PHP5, and removed altogether in PHP7.
Your best bet is to follow #tadman's advice and use WP's API for this.
Is the only line you changed the $sql = line?
From the wordpress codex:
global $wpdb;
$results = $wpdb->get_results( 'SELECT * FROM wp_options WHERE option_id = 1', OBJECT );
should return you an array or object of results per the documentation.
so your code wouldn't need to do any of the fetch_assoc related methods. Wordpress is handling the actual DB connection and query parsing and just handing you back your results.
Possible Solution:
// formatting for readability.
$date = date("Y-m-d");
// Prepare query.
$sql = $wpdb->prepare(
"SELECT count(`question_count`) as Qcount
FROM `wp_posts`
WHERE `question_count` = 1
AND `question_date` = %s",
$date
);
// Execute query.
$results = $wpdb->get_results($sql);
// Get option for number of questions.
$no_of_questions = get_option( 'askme_setting_no_of_questions', 10);
// Set base values to avoid usage of else condition.
$value = "Add your question to the cart";
$button = " ";
// Check to ensure results returned.
if (!empty($results)) {
// Evaluate result of query.
if ($results[0]->Qcount >= $no_of_questions) {
// Update values only if necessary.
$value = "The question limit...";
$button = "disabled";
}
}
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
I am getting the following errors when i am trying to insert parsed data into a table in my database:
PHP Notice: Undefined index: manu in /home/svn/dev.comp/Asus.php on line 112
PHP Notice: Undefined index: partnumber in /home/svn/dev.comp/Asus.php on line 112
PHP Notice: Undefined index: description in /home/svn/dev.comp/Asus.php on line 112
PHP Notice: Undefined property: DatabaseManager::$_link in /home/svn/dev.comp/Asus.php on line 112
PHP Warning: mysql_query() expects parameter 2 to be resource, null given in /home/svn/dev.comp/Asus.php on line 112
Here is the code i have so far:
<?php
//Declaring all database connection information
$username = "username";
$password = "password";
$database = "database_name";
//Setting connection to database, fail if could not connect
$link = mysql_connect("localhost", $username, $password) or die("Could not connect to database");
mysql_select_db($database, $link);
$csv = new CSVManager();
$data = $csv->get_data_array();
$api = new DataGrabber($link);
$xmldata = $api->call_api($data);
$dm = new DatabaseManager();
$dm->insert_asus_data($xmldata);
//This class will pull data from the .CSV file and store it inside an array
class CSVManager {
public function get_data_array() {
//Open and declare location of .CSV file to pull data from
$hook = fopen('asus.csv', 'r');
//Number of columns in .CSV file we are getting data from
$allowedCols = 5;
//Store all data we will extract, into an array
$data = array();
//Count the number of lines in the .CSV file
while($line = fgetcsv($hook)) {
$numcols = count($line);
//Test wether the number of columns we are declaring, is equal to the number of columns in the .CSV file
if($numcols == $allowedCols) {
//If so, assign each data row from the column names to new entries which will be declared in the DatabaseManager Class
$entry = array(
'man' => $line[0], //index of column name in .CSV file
'cat' => $line[1],
'model' => $line[2],
'family_id' => $line[3],
'family' => $line[4]
);
//Insert all entries into the data array declared above
$data[] = $entry;
}
}
//Once data is inside the array, return this data
return $data;
}
}
//This class will pull data from the XML document and store it inside another array
class DataGrabber {
//The URL where data will be extracted from, which is an XML file
protected $URL = "http://json.zandparts.com/api/category/GetCategories/44/EUR/";
public function call_api($data) {
if(count($data) == 0) return array();
$jsondata = array();
foreach($data as $entry){
$url = $this->URL . $entry['model'] . "/". "E%20Series" . "/" . rawurlencode($entry['cat']) . "/" . $entry['man'] . "/null";
$json = file_get_contents($url);
$data = json_decode($json, true);
if(!empty($data['Products'])){
foreach ($data['Products'] as $id => $product) {
$jsonentry = array(
'productnumber' => $id,
'partnumber' => $product['strPartNumber'],
'description' => $product['strDescription'],
'manu' => $product['Brand']
);
$jsondata[] = $jsonentry;
}
}
}
return $jsondata;
}
}
It works fine upto here, but with the following code below it throws the errors above:
class DatabaseManager {
public function insert_asus_data($partbind) {
//create a new MySQL statement to insert data into the database table. Bind the entries declared above from both classes, to the fieldnames in the database and insert them as values.
mysql_query("INSERT INTO asus_parts (manufacturer, partNumber, description) VALUES ('{$partbind['manu']}', '{$partbind['partnumber']}','{$partbind['description']}')", $this->_link);
}
}
?>
They are both in the same file.. I dont understand why it is throwing these errors and how can i overcome this? Thanks.
[EDIT]
Here is one of the print statements:
[5] => Array
(
[productnumber] => 0
[partnumber] => 0B200-00120100
[description] => ME370T BAT COSLI LI-POLY FPACK
[manu] => Google
)
[6] => Array
(
[productnumber] => 1
[partnumber] => 0B200-00120200
[description] => ME370T BAT COSLI LI-POLY FPACK
[manu] => Google
)
Still does not insert any data in the table
The query is wrong you don't need the link in insert query change it to this
mysql_query("INSERT INTO asus_parts (manufacturer, partNumber, description) VALUES ('{$partbind['manu']}', '{$partbind['partnumber']}','{$partbind['description']}')");
You must escape your variables.
'{$partbind['manu']}'
This is shown as '{$partbind['
To escape the second quote just double it:
'{$partbind[''manu'']}'
Something really weird is going on here. I have this method for mysqli query.
public function select($options) {
$default = array (
'table' => '',
'fields' => '*',
'condition' => '2',
'order' => '1',
'limit' => 50
);
$options = array_merge($default,$options);
$query = "SELECT {$options['fields']} FROM {$options['table']} WHERE {$options['condition']} ORDER BY {$options['order']} LIMIT {$options['limit']}";
if ($result = $this->conn->query($query)) {
while ($row = $result->fetch_assoc()) {
$rows[] = $row;
}
return $rows;
} else {
printf("Query failed: %s\n", $mysqli->error);
exit;
}
}
Once the query get executed I get $rows and everything works like a charm. But then when I try to get specific key in array I get the "Query failed:" without specific message :S
$options = array(
'table' => 'settings',
'fields' => 'setting_wall_post,setting_status_tag,setting_photo,setting_like,setting_comment',
'limit' => '1',
'condition' => "setting_id = 6",
);
$check = $this->mysql->select($options);
print_r($check);
$check = $check[0];
if($check["setting_wall_post"]) //if I comment out this IF block it works :(
$this->scope["wall_post"] = "publish_stream";
Also I've tried to close mysqli connection and then I get
Warning: mysqli::query() [mysqli.query]: Couldn't fetch mysqli
this IF block is acting like it works with mysqli :S
So the question is, what is the issue here? Why can't I access to "setting_wall_post"? I guess that part is the problem since it works if I comment out that IF block.
Edit. What a silly I am, overlooked such a typo: $this->conn have to be used instead of undefined $mysqli.
That's why one should always have error reporting no less than E_ALL
The code you posted just cannot cause this kind of error.
Change your error reporting code to this one
} else {
throw new Exception($this->conn->error);
}
this way you will have a stack trace which will show the chain of calls, pointing to the place of code that caused particular error.
BTW, the whole function looks unusable and error prone to me. it is open to injection and require more code than a conventional SQL
Can anyone tell me I get the error: Fatal error: Call to a member function fetch_assoc() on a non-object for this method inside the class
This is a recursive function, and it runs fine the first time, is the second time when I get the error.
function getSite($var, $var1 = 0, $numLevel = 1){
//get the page
$qry = "SELECT * FROM table WHERE columnA = $var AND columnB = $var1 ORDER BY parent, position ASC";
$arrPage = $this->my_sqli->query($qry);
//a valid resut was returned from the DB
while($obj = $arrPage->fetch_assoc()){
//add to array
if($obj['id']){
$this->arrMenu = array(
'id' => $obj['id'],
'parent' => $obj['parent'],
'level' => $numLevel
);
... some more code
// call the function again
getSite($value1);
}
}
}
You are not including error checking.
Change
$arrPage = $this->my_sqli->query($qry);
to
if ( ($arrPage = $this->my_sqli->query($qry)) === false) {
printf("Error: %s in query %s\n", $this->my_sqli->error,$qry);
}
Normally when i see those errors there's something wrong with the query, try echo the query and executing it in something like Query Browser