Skip to content
View in the app

A better way to browse. Learn more.

Web Designer Forum

A full-screen app on your home screen with push notifications, badges and more.

To install this app on iOS and iPadOS
  1. Tap the Share icon in Safari
  2. Scroll the menu and tap Add to Home Screen.
  3. Tap Add in the top-right corner.
To install this app on Android
  1. Tap the 3-dot menu (⋮) in the top-right corner of the browser.
  2. Tap Add to Home screen or Install app.
  3. Confirm by tapping Install.

SQL Problem

Featured Replies

Hi folks,

 

I'm kind of burned out so I might be overlooking something simple here, but I have a piece of SQL code that works in PHPMyAdmin but not PHP. Basically it's just the num_expressions column that comes up empty (0) in PHP but has good values in SQL. The SQL statement is:

 

SELECT ca.category_name, ca.category_description, ca.category_slug, COUNT( e.id ) AS num_expressions
FROM Categories ca
LEFT JOIN Expressions e ON ( e.category_id = ca.id )
GROUP BY ca.category_name

 

In PHP I have it in an array, like so:

 

Output by print_r()

Array ( [0] => SELECT ca.category_name, ca.category_description, ca.category_slug, COUNT(e.id) AS num_expressions FROM Categories ca LEFT JOIN Expressions e ON ( e.category_id = ? ) GROUP BY ca.category_name [1] => Array ( [0] => ca.id ) )

 

Which is processed by this function...

 

	public function preparedQuery(array $values) {
	$dbh = self::connect(); //returns a PDO DBH object
	$sth = $dbh->prepare($values[0]);
	$sth->execute($values[1]);
	if (empty($sth)) {
		throw new Exception("Nothing was queried.");
	}
	$sth->setFetchMode(PDO::FETCH_ASSOC);
	return $sth->fetchAll();
}

 

And it results in a perfectly fine multi-dimensional array with all good values, except that the num_expressions column is filled with 0s. Like I said, the exact same query on PHPMyAdmin fills that column up with good values.

 

Anyone?

Edited by troyfawkes

  • Author

I found the solution.

 

PDO doesn't allow you to pass table names as prepared values - presumably it converts the table name into a string.

 

$sql = "SELECT * FROM table_name t1 LEFT JOIN other_table t2 ON ( t1.id = ? )";
$value = "t2.id";
$sth = $dbh->prepare($sql);
$sth->execute($value);

 

Doesn't work.

 

You have to have t1.id = t2.id hardcoded. You could of course have t1.id = 2 or something like that. No errors are thrown.

Create an account or sign in to comment

Account

Navigation

Search

Search

Configure browser push notifications

Chrome (Android)
  1. Tap the lock icon next to the address bar.
  2. Tap Permissions → Notifications.
  3. Adjust your preference.
Chrome (Desktop)
  1. Click the padlock icon in the address bar.
  2. Select Site settings.
  3. Find Notifications and adjust your preference.