Page 1 of 1

Quotes as table names?

Posted: Mon Sep 05, 2011 7:04 am
by ThatPerson
I have been trying to make a wiki, and release it in an easy format. I have setup.php which sets the tables and things. The problem is it will not accept the variable as a table name. The way I am trying to do it is:

Code: Select all

<?php
include("setup.php");
include("database.php");
ob_start();
$table = "table_name";
$pagetest = mysql_query("select count(*) as count from '$table'");
$pages = mysql_fetch_object($pagetest)->count;
$pagenum = intval($pages);
Which should return $pagenum as 1, however it errors with:

Warning: mysql_fetch_object(): supplied argument is not a valid MySQL result resource on line 6


How could I use a variable as a table name?

Re: Quotes as table names?

Posted: Mon Sep 05, 2011 7:18 am
by twinedev
The problem is you are trying to quote a table name with a single quote as if it was a string.

Database names, table names and filed names are "quoted" (not sure if is the right term) with backticks (`, left of the 1 key). Also, in case you ever need to stack them, you do each item separately.

ie.

SELECT `databasename`.`tablename`.`fieldname` FROM `databasename`.`tablename`

will do a SELECT fieldname FROM tablename on the databasename database (although that is way overkill on most cases)

-Greg

Re: Quotes as table names?

Posted: Mon Sep 05, 2011 7:55 am
by ThatPerson
Ah, thanks for that. Another method is:

$query = "select count(*) as count from ".$table;
$queryreply = mysql_query($query);

And then continue it. Thanks!

Re: Quotes as table names?

Posted: Mon Sep 05, 2011 2:15 pm
by twinedev
Yes, as long as you know $table will never contain reserved words