Page 1 of 1

can i use a variable as table name?

Posted: Tue Nov 28, 2006 10:15 am
by forphp
Burrito | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]


can i use like this---->
what changes needed?--->

Code: Select all

<?php
$TableName="Student";
$connect=mysql_connect("localhost","root","");
$result=mysql_query("select * from $TableName",$connect);
while($row=mysql_fetch_array($result))
{
for($i=0;$i<mysql_num_fields($result);$i++)
echo $row[$i];
}
?>
:o


Burrito | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]

Posted: Tue Nov 28, 2006 10:29 am
by zeek
You should view some examples at: http://us2.php.net/manual/en/function.m ... -array.php

You can use a variable for a table name, but...

Your example has problems. In addition to the fact that you never select a database, you will want to change:

Code: Select all

for($i=0;$i<mysql_num_fields($result);$i++)
to:

Code: Select all

for ($i=0; $i<count($row); $i++)
I recommend you take one of the examples from the page above.

Re: can i use a variable as table name?

Posted: Tue Nov 28, 2006 10:29 am
by Obadiah
forphp wrote: can i use like this---->
what changes needed?--->

Code: Select all

<?php
$TableName="Student";
$connect=mysql_connect("localhost","root","");
$result=mysql_query("select * from $TableName",$connect);
while($row=mysql_fetch_array($result))
{
for($i=0;$i<mysql_num_fields($result);$i++)
echo $row[$i];
}
?>
:o
yes, i would suggest doing it this way though...its a bit cleaner

Code: Select all

<?php

$table_name = "student";
$connect=mysql_connect("localhost","root","")or die(mysql_error());
mysql_select_db("name_of_database",$connect) or die(mysql_error());
return $connect;

$sql = "select * from $table_name";
$result = mysql_query($sql,$conn) or die(mysql_error());

while($row=mysql_fetch_array($result))
{
for($i=0;$i<mysql_num_fields($result);$i++)
echo $row[$i];
}
?>
[edited]

please take this into account also if you choose not to use a database name
zeek wrote: Your example has problems. In addition to the fact that you never select a database, you will want to change:

Code: Select all

for($i=0;$i<mysql_num_fields($result);$i++)
to:

Code: Select all

for ($i=0; $i<count($row); $i++)
nice catch zeek! :)