For some reason when I run a $result=mysql_query(...) that should return an array to be parsed with mysql_fetch_array, I keep getting an error that the value returned for $result is either a string or boolean, which mysql_fetch_array() can't work with. I've been running the same query on my server for years and for some reason it stopped working recently.
here's the sample code:
$result=mysql_query("SELECT * FROM `patient_list`");
while ($row=mysql_fetch_array($result)) {
...
}
I recently upgraded to the newest version of wamp. might that have anything to do with it? Any thoughts?
This error means taht result of mysql_query is not valid.Please place
echo mysql_error();
after you call mysql_query
Your problem could be access / database doesn't exist / anything
Always check the query runs correctly execute your query like this :
$result = mysql_query(<query>);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
// process the result here
Documentation for mysql_query
Try this:
$result = mysql_query("SELECT * FROM `patient_list`") or die( mysql_error() );
Related
I am using mysqli_num_fields() but facing error
I also used mysql_num_fields but again faced error.
$this->db->select('*');
$this->db->from('quizmarks');
$query = $this->db->get();
$data= $query->result();
echo mysqli_num_fields($data);
exit();
Here is the error
A PHP Error was encountered
Severity: Warning
Message: mysqli_num_fields() expects parameter 1 to be mysqli_result, array given
$query = $this->db->get('quizmarks');
return $query->num_fields();
More optimal solution
Use directly get method becoz you need all fields of that table
I have been using a hook in the Advanced Custom Fields plugin (load_field) which loads objects from a table in my database to an ACF select field. The table ('wp_new_royalsliders') is created by the RoyalSlider image slider plugin so i use the hook to populate a select field with the slider names.
This function has worked fine for a long time but recently stopped working - I think after updating core to 4.8.2:
add_filter('acf/load_field/name=media_gallery_slider', 'my_acf_royalslider_choices');
function my_acf_royalslider_choices($field){
$field['choices'] = array();
global $wpdb;
$query = $wpdb->prepare('SELECT * FROM %1$s ORDER BY ID ASC', 'wp_new_royalsliders');
$results = $wpdb->get_results($query);
if(!empty($results)) :
foreach($results as $result) :
$value = $result->id;
$label = $result->name;
$field['choices'][ $value ] = $label;
endforeach;
endif;
return $field;
}
When I turn debugging on I get an error:
WordPress database error: [You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '%1$s ORDER BY ID ASC' at line 1]
SELECT * FROM %1$s ORDER BY ID ASC
When you pass in a hardcoded string value, you don't need placeholders, you can just use
$query = $wpdb->prepare('SELECT * FROM wp_new_royalsliders ORDER BY ID ASC');
If you want to get fancy and portable, you might opt for
$query = $wpdb->prepare('SELECT * FROM ' . $wpdb->prefix . 'new_royalsliders ORDER BY ID ASC');
So it would work on other prefixes, too, but that might not be necessary if this is a very custom thing that's not going to make it into any other site.
It appears that others have noted the removal of that possibility too, see this request.
Update: as $wpdb->prepare() expects a second parameter (since its job is to escape variable inputs for use in SQL), it might complain. Solution: get rid of it and give your SQL directly to get_results:
$results = $wpdb->get_results('SELECT * FROM ' . $wpdb->prefix . 'new_royalsliders ORDER BY ID ASC');
Can i use where and order by in mysql together like this
$results=mysql_query("SELECT `status_content`
FROM `status`
WHERE `user_id`=".$_SESSION['user_id']."
ORDER BY `status_time` DESC" );
her is my code, but it is giving me error
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\lr\profile.php on line 65
<?php
$results=mysql_query("SELECT status_content FROM status
WHERE user_id=".$_SESSION['user_id']."
ORDER BY status_time DESC" );
while($row=mysql_fetch_array($results)) {
echo $row['status_content'];
}
?>
yes, this is valid as google will tell you http://dev.mysql.com/doc/refman/5.0/en/select.html
For your actual error, from the php docs:
For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query() returns a resource on success, or FALSE on error.
// Perform Query
$result = mysql_query($query);
// Check result
// This shows the actual query sent to MySQL, and the error. Useful for debugging.
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}
// Use result
// Attempting to print $result won't allow access to information in the resource
// One of the mysql result functions must be used
// See also mysql_result(), mysql_fetch_array(), mysql_fetch_row(), etc.
while ($row = mysql_fetch_assoc($result)) {
// do something
}
Also: you should not use the mysql_* functions anymmore since they are deprecated and unsafe.
Use mysqli_* or PDO instead.
i keep having this error "mysql_fetch_array() expects parameter 1 to be resource, null given in" when i try to display the returned value of count in sql. heres my code.
$query="SELECT med_rec_ID, COUNT(med_rec_ID)
FROM med_issue
WHERE MONTH(issue_date) = MONTH('2013-02-05')
GROUP BY med_rec_ID";
$result= mysql_query($query);
while($count = mysql_fetch_array($display3)){
echo $count[0];
}
i have tried to run the query in sql alone it displays 2 columns (the med_rec_ID, and the COUNT). guys how do i display the count and fix the error too?
First of all, don't use mysql_* functions since they're deprecated. Use mysqli or PDO.
Secondly, look at what you're passing into the fetch_array function.
You probably want to do something like:
$link = mysqli_connect("localhost", "admin", "pass", "db_name");
$result = mysqli_query($link, $sql);
while($row = $result->fetch_array(MYSQLI_ASSOC)){
$medIds[] = $row['med_rec_ID'];
...
}
Then fix the count by giving it an alias.
Please note that you should actually store how you access the DB in a more secure manner, but I use this only to illustrate the example. Here's a pretty good post: How to create global configuration file?
Is your query even executing? that error will happen if mysql_query doesnt return the resource, in case query fails
$query="SELECT med_rec_ID, COUNT(med_rec_ID) as C FROM med_issue where MONTH(issue_date) = MONTH('2013-02-05') GROUP BY med_rec_ID";
$result= mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_assoc($result))
{
echo $row["C"];
}
Note: Please do not use mysql_* functions anymore
Give it an alias:
SELECT
med_rec_ID,
COUNT(med_rec_ID) TheCount
FROM med_issue
where MONTH(issue_date) = MONTH('2013-02-05') GROUP BY med_rec_ID
then you can select that column TheCount inside the while loop with $row['TheCount'], also use lope through the $result:
$result = mysql_query($query);
while($row = mysql_fetch_array($result)){
echo $row['TheCount'];
}
I am using CakePHP 1.3 and writing custom shells to run mundane tasks in cronjobs. I am seeing failed Model->save() from time to time but I don't know anyway to find out what the exact problem is.
Is there a way to display the actual SQL statements executed and warning/error returned by MySQL in a CakePHP shell?
Thanks.
You can use the following SQL dump task for shells.
http://bakery.cakephp.org/articles/carcus88/2011/04/08/sql_dump_task_for_shells
One way to do this would be to watch the MySQL log file in a separate terminal.
A couple ways of doing this are listed here:
MySQL Query Logging in CakePHP
I found a way to do it. In your shell, add:
function initialize()
{
Configure::write('debug', 2);
$this->_loadDbConfig();
$this->_loadModels();
}
Then whenever you like to see the log, call this function:
function dump_sql()
{
$sql_dump = '';
if (!class_exists('ConnectionManager') || Configure::read('debug') < 2)
return false;
$noLogs = !isset($logs);
if ($noLogs)
{
$sources = ConnectionManager::sourceList();
$logs = array();
foreach ($sources as $source):
$db =& ConnectionManager::getDataSource($source);
if (!$db->isInterfaceSupported('getLog')):
continue;
endif;
$logs[$source] = $db->getLog();
endforeach;
}
if ($noLogs || isset($_forced_from_dbo_))
{
foreach ($logs as $source => $logInfo)
{
$text = $logInfo['count'] > 1 ? 'queries' : 'query';
$sql_dump .= "cakeSqlLog_" . preg_replace('/[^A-Za-z0-9_]/', '_', uniqid(time(), true));
$sql_dump .= '('.$source.') '. $logInfo['count'] .' '.$text. ' took '.$logInfo['time'].' ms';
$sql_dump .= 'Nr Query Error Affected Num. rows Took (ms)';
foreach ($logInfo['log'] as $k => $i)
{
$sql_dump .= $i['query'];
}
}
}
else
{
$sql_dump .= 'Encountered unexpected $logs cannot generate SQL log';
}
}
One other approach would be to have all your custom queries in the models/behaviors, and just calling the data/updates from shells. This would give you an extra benefit of being able to reuse those custom SQL in other parts of the project. For example, in unit tests.
In CakePHP 1.2, I was able to get the SQL queries to show up in my console output by adding a Configure::write('debug', 2); call to the bottom of the __bootstrap method in the cake/console/cake.php file.
No need to mess around with specifically calling a dump_sql function like some of these answers, I just automatically get the normal queries like at the bottom of a web page.