I'm new to php so can't understand this

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Flycow
Forum Newbie
Posts: 9
Joined: Thu Jul 08, 2010 8:04 am

I'm new to php so can't understand this

Post by Flycow »

I'm new to php but have done some basic and pascal coding in the past as well as some elaborate spreadsheets so I can't understand why this

Code: Select all

$con = mysql_connect("localhost",$dbuser,$dbpassword);
mysql_select_db($dbname, $con);
$file=fopen($csvfile,"r");
$data = fgetcsv($file,1000,",");
$sql = 'CREATE TABLE $table (';
for ($i=1;$i<=count($data);$i++) {
$sql .= $data[$i] . 'VARCHAR(50), ';
 }

mysql_query($sql,$con);
Produces a t_variable error on line 7
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: I'm new to php so can't understand this

Post by requinix »

a) Which one is line 7?
b) Variables don't work in single-quoted strings.
c) Your SQL is very incorrect.
websitesca
Forum Newbie
Posts: 16
Joined: Fri Jul 09, 2010 2:47 pm

Re: I'm new to php so can't understand this

Post by websitesca »

Hey!

Firstly, you're gonna have trouble with:

Code: Select all

$sql = 'CREATE TABLE $table (';
You wanna use double quotes here. If you use single quotes, your $table variable will actually remain literally as '$table' and not get replaced with the value inside that variable.

I don't see any syntax errors here - I ran this code and it had no syntax errors.

I can see how you would get a runtime error however for your sql. You're gonna have a dangling comma at the end. You're gonna get something like:

Code: Select all

"Create table $table (name1 VARCHAR(50), name2 VARCHAR(50), "
So what you want to do is:

Code: Select all

$sql = substr($sql, 0, strlen($sql)) . ")";
Hope that helps!

Georges,
http://www.websites.ca
Flycow
Forum Newbie
Posts: 9
Joined: Thu Jul 08, 2010 8:04 am

Re: I'm new to php so can't understand this

Post by Flycow »

I ran it through again and the error disappeared and I'd figured the lack of an ending but thanks for your help
Post Reply