Naz
Naz

Reputation: 910

Counting the number of records returned

I have the following code to tell me if a record with "widgets_active" in the option_name column of the table wp_options exists.

    global $wpdb;
    $table_name = $wpdb->prefix . "options";
    $ActiveWidgets ="widgets_active";
    $CheckAllActiveWidgets = $wpdb->get_results("SELECT `option_name` FROM '$table_name' WHERE `option_name` = '$ActiveWidgets'");

    echo '<script type="text/javascript">alert("'.$CheckAllActiveWidgets.'");</script>';

    if (mysql_num_rows($CheckAllActiveWidgets) == 0) {

However, when I run the function the alert simply says 'Array' and the error

Warning: mysql_num_rows() expects parameter 1 to be resource, array given.... on line 6...

is displayed, if I run just the SQL statment mySQL it does return the 1 record that I placed there. How can I fix the code above?

Upvotes: 0

Views: 45

Answers (3)

user5937446
user5937446

Reputation:

That's because $CheckAllActiveWidgets holds an array!

Try this:

echo '<script type="text/javascript">alert("' . $CheckAllActiveWidgets[0][0] . '");</script>';

`

Upvotes: 0

naui95
naui95

Reputation: 31

I'm not much of an expert with Wordpress, but according to Wordpress documentation (https://codex.wordpress.org/Class_Reference/wpdb) you should be able to count the results of your query using $wpdb->num_rows. So your code should be something linke this:

global $wpdb;
    $table_name = $wpdb->prefix . "options";
    $ActiveWidgets ="widgets_active";
    $CheckAllActiveWidgets = $wpdb->get_results("SELECT `option_name` FROM '$table_name' WHERE `option_name` = '$ActiveWidgets'");

    echo '<script type="text/javascript">alert("'.$CheckAllActiveWidgets.'");</script>';

    if ($wpdb->num_rows == 0) {

Upvotes: 1

Naz
Naz

Reputation: 910

I changed the code to do a count in the SQL itself.

    global $wpdb;
    $table_name = $wpdb->prefix . "options";
    $CheckAllActiveWidgets = $wpdb->get_var("SELECT COUNT(*) FROM `wp_options` WHERE `option_name` = 'siteorigin_widgets_active'");

    if ($CheckAllActiveWidgets == 0) {

Upvotes: 0

Related Questions