(dispicable err) syntax error, unexpected T_VARIABLE

I’ve cut the script to a short test and still can’t locate the cause of …
syntax error, unexpected T_VARIABLE … on line 24.

Here’s the script …

[php]
include_once ($_SERVER[‘DOCUMENT_ROOT’] . ‘/cgi-bin/cnnct2mysqli.php’);

$id			= '';
$hits		= 123;
$first_name	= 'First name';

$mysqli = new mysqli($DBServer, $DBUser, $DBPass, $DBName);

if ($mysqli->connect_errno) {
	echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
	}

if (!$mysqli->query("DROP TABLE IF EXISTS test4") 
	||
	!$mysqli->query("CREATE TABLE test4(
	`id` int(10) unsigned NOT NULL auto_increment,
	`hits` int(10) unsigned NOT NULL,
	`first_name` varchar(20) NOT NULL default ,
	PRIMARY KEY  (`id`)
	)") 

24 $mysqli->query(“INSERT INTO test4(id, hits, first_name) VALUES (?, ?, ?)”);
$query->bind_param(sss, $id, $hits, $first_name);
$query->execute();

$mysqli->close();

[/php]

I don’t see it. Any help appreciated.
usit

Looks like you’re missing the || before that and after the other query call. Honestly I think how you are nesting all these queries in the if() is a very bad idea, it makes the logic very difficult to read and understand what’s doing what and why.

Well, I agree with Fastsol… This code is messed up…

So, first, take out the 24 that is stuck in the code at line 23. I think that might have been a typo…

Next, you are checking two queries inside of an if statement and if the BOTH are NOT , then you run another query? That logic does not compute, Will Robinson! :slight_smile:

Hmmm…
if (!$mysqli->query(“DROP TABLE IF EXISTS test4”)
||
!$mysqli->query(“CREATE TABLE test4(id int(10) unsigned NOT NULL auto_increment,hits int(10) signed NOT NULL, first_name varchar(20) NOT NULL default , PRIMARY KEY (id))”)
$mysqli->query(“INSERT INTO test4(id, hits, first_name) VALUES (?, ?, ?)”);
Sooooo…
This tests to see if the first query does NOT drop the table and then it tests if the second query does NOT create the table? Then, if both do NOT happen, it inserts data? The logic of that is so messed up.
Normally, you would try to drop the table, if it does it, then try to create the table and then if it does it, insert the data.

My question would be, why would you want to empty out the table every time you insert something into it? Makes no sense.

Anyways, the T_VARIABLE on like 24 is the added in code “24”…

Thanks fatsol and ErnieAlex,
yes, as presented, the code leaves something to be desired.
The original was lifted from the web and reduced to what I needed to find my mysqli syntax errors. I liked the idea of having nothing change but syntax, so rebuilding a subset of the main table seemed to be appropriate.

With your comments, I scrapped the script presented here, went back to the original, and did a more careful deleting of blocks of code to get a working subset. Here it is …

[php] include_once ($_SERVER[‘DOCUMENT_ROOT’] . ‘/cgi-bin/cnnct2mysqli.php’);//4 db connection parameters
$id = ‘’;
$first_name = ‘First name’;
$USIT_txt = true;
$invoiceNo = 40814;

$mysqli = new mysqli($DBServer, $DBUser, $DBPass, $DBName);

if ($mysqli->connect_errno) {
	echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
	}
if (!$mysqli->query("DROP TABLE IF EXISTS test4") 
	||
	!$mysqli->query("CREATE TABLE test4		
	(
	`id` int(6) UNSIGNED NOT NULL AUTO_INCREMENT,
	`first_name` varchar(20) NOT NULL default '',
	`USIT_txt` varchar(4) default NULL,		
	`invoiceNo` varchar(20) default NULL,
	PRIMARY KEY  (`id`),
	INDEX(`invoiceNO`)
	)") 	
	||
           !$mysqli->query("INSERT INTO `test4`(
	 `id`,	`first_name`,	`USIT_txt`,		`invoiceNo`
	 ) 
		VALUES 
	(
	'{$id}',	'{$first_name}',	'{$USIT_txt}',	'{$invoiceNo}'
	)
	")
) 
{
echo "Table creation failed: (" . $mysqli->errno . ") " . $mysqli->error;
}	
$mysqli->close();				

[/php]

This solved the problem.

Thanks again. Your insights are part of my learning experience.

usit

Looks to me like you didn’t make any change for the good. You still have all those queries in the one if() which is a terrible design.

The original web script had the nested ||s, which suited my need at the moment. However, I had trouble getting the script to work and spent many hours learning multiple ways to create ‘enexpected T_VARIABLE’ errors. The multiple ||s didn’t bother me because they seemed to fit my experience with boolean-algebra statements. But, locating the source of the syntax errors does give me trouble. When finally I got the abbreviated, 3 column table to work, I then expanded it bacd to the original 24 column version. Now I’m back to square 1 with syntax errors I can’t trace.

I’m reluctant to restart with some other template script. This dodges an opportunity to understand php mysqli better. However, if this syntax error is an issue of boolean logic, which I doubt but can’t proove, then I will start over.

Well, Usit, sometimes people like Fastsol and myself see the future in someone’s code.

Using badly formed code from someone else, just make us think what else did they do wrong in the
rest of the code. So, normally you never nest queries. You can nest “for” statements, “While” statements
and really most any code as long as you can follow the logic of the flow of it all. But, queries are totally
different.

Queries my be tested after they run. You need to know if a query that is feeding into another query has
actually finished correctly. Piling them on top of each other will just cause problems which are very hard
to follow and to debug.

Well, that is really my opinion, but…

So, in your IF clause, you run a query which may give you an output of 0 records OR fail due to a DB
error or bad inputs in the query which would also give you 0 records. So, testing with an “OR” or “||”
could give you false outputs going into the next condition clause. This code basically DROP’s a table
which means it is deleted, then you CREATE a table of the same name and then insert one line of data
into the new table.

This logic is okay, but should be done in three different steps. Each step should be checked for errors
and the correct error messages given back if one fails. Also, this type of code is usually done only once
in any type of program. Usually after checking if the table exists to start with. It does not make a lot of
sense to drop the table and recreate it every time you run this program. If needed, you could delete all
of the records in it much faster by just DELETE * inside a query. Not sure on why you would want to
rebuild the table every time you run this code. (DROPing a table if fairly fast, creating one is slower.)
Actually, I guess this depends on why you would want a new table every time you run it…

Well, not sure if all that helped or not. Hope so… Good luck and post your errors if you want to try again!

Back for another lesson.
Thanks ErnieAlex for a lucid and informative explanation. Helped a lot.

I’ve modified the test script as shown below. And I’m back to “syntax error, unexpected T_VARIABLE in /…/testMySQLiCreateTABLE2a.php on line 53”. The script follows:

[php]
include_once ($_SERVER[‘DOCUMENT_ROOT’] . ‘cnnct2mysqli.php’);
$id = ‘’;
$hits = 223;
$amount = 1.00;
$item_name = ‘book’;
$email = ‘[email protected]’;
$first_name = ‘First name’;
$last_name = ‘LastNames’;
$address1 = ‘Addr01’;
$address2 = ‘Addr02’;
$city = ‘city’;
$state = ‘MI’;
$zip = 48118;
$country = ‘US’;
$USIT_txt = true;
$invoiceNo = 40814;

$mysqli = new mysqli($DBServer, $DBUser, $DBPass, $DBName);

if ($mysqli->connect_errno) {
	echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
	}

	!$mysqli->query("CREATE TABLE test2		
	(
	`id` int(6) UNSIGNED NOT NULL AUTO_INCREMENT,
	`hits` int(6) UNSIGNED NOT NULL,
	`amount` varchar(6) default NULL,
	`item_name` varchar(24) default NULL,
	`email` varchar(40) default NULL,
	`first_name` varchar(20) NOT NULL default '',
	`last_name` varchar(40) NOT NULL default '',
	`address1` varchar(100) default NULL,
	`address2` varchar(100) default NULL,
	`city` varchar(50) default NULL,
	`state` varchar(6) default NULL,
	`zip` varchar(12) default NULL,
	`country` varchar(6) DEFAULT NULL,
	`USIT_txt` varchar(4) default NULL,		
	`invoiceNo` varchar(20) default NULL,
	`expence_date` DATE,
	`updated` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
	PRIMARY KEY  (`id`),
	INDEX(`invoiceNO`)
	)") 
			

	$query = $con->prepare("INSERT INTO `test2` (
	`id`,		`hits`,		`amount`,	`item_name`,	`email`,	`first_name`,	`last_name`,	
	`address1`,	`address2`,	`city`,		`state`,		`zip`,		`country`,		`USIT_txt`,	
	`invoiceNo`,`expence_date`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )");
	 
	$mysqli->query("INSERT INTO `test2`(
	 `id`,			`hits`,		`amount`,	`item_name`,	`email`,	`first_name`,	`last_name`,
	 `address1`,	`address2`,	`city`,		`state`,		`zip`,		`country`,		`USIT_txt`,		
	 `invoiceNo`, 	`expence_date`
	 ) 
	VALUES 
	(
	$id,		$hits,		$amount,	$item_name,	$email,		$first_name,	$last_name,
	$address1,	$address2,	$city,		$state,		$zip,		$country,		$USIT_txt,	
	$invoiceNo, $expence_date
	)
	") 

	$query->execute();	
			
$mysqli->close();

[/php]

Well, short on time right now. But…

When you insert data using a query like "INSERT INTO tablename (field1, field2, etc.) VALUES(‘val1’, ‘val2’,etc)
you need to use quotes for certain types of data in the VALUES list. My question is it is that…

And, not sure why you need to PREPARE the insert before you actually execute it.
I will have to look at that in depth later on. Working on several systems right now and have plans tonight!

Try it without the PREPARE line…

Re-Do of last reply. It got out of hand and was posted before I was through writing it.

Latest version of test script follows: It throws the error mssg: “unexpected T_VARIABLE in /home/…/testMySQLiCreateTABLE2a.php on line 52”. Again, I don’t see it.

SCRIPT:
[php]
include_once ($_SERVER[‘DOCUMENT_ROOT’] . ‘/cgi-bin/cnnct2mysqli.php’);//4 db connection parameters

$id			= '';
$hits		= 223;
$amount		= 1.00;
$item_name	= 'book';
$email 		= '[email protected]';	
$first_name	= 'First name';
$last_name  = 'LastNames';
$address1 	= 'Addr01';
$address2 	= 'Addr02';
$city		= 'city';
$state 		= 'MI';
$zip		= 48118;
$country 	= 'US';
$USIT_txt	= true;
$invoiceNo	= 40814;

$mysqli = new mysqli($DBServer, $DBUser, $DBPass, $DBName);

if ($mysqli->connect_errno) {
	echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
	}

	!$mysqli->query("CREATE TABLE test2		
	(
	`id` int(6) UNSIGNED NOT NULL AUTO_INCREMENT,
	`hits` int(6) UNSIGNED NOT NULL,
	`amount` varchar(6) default NULL,
	`item_name` varchar(24) default NULL,
	`email` varchar(40) default NULL,
	`first_name` varchar(20) NOT NULL default '',
	`last_name` varchar(40) NOT NULL default '',
	`address1` varchar(100) default NULL,
	`address2` varchar(100) default NULL,
	`city` varchar(50) default NULL,
	`state` varchar(6) default NULL,
	`zip` varchar(12) default NULL,
	`country` varchar(6) DEFAULT NULL,
	`USIT_txt` varchar(4) default NULL,		
	`invoiceNo` varchar(20) default NULL,
	`expence_date` DATE,
	`updated` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
	PRIMARY KEY  (`id`),
	INDEX(`invoiceNO`)
	)") 

52 $stmnt = $mysqli->prepare(“INSERT INTO test2 (
id, hits, amount, item_name, email, first_name, last_name,
address1, address2, city, state, zip, country, USIT_txt,
invoiceNo, expence_date
)VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )”);

$stmnt->bind_param('ssssssssssssssss', $id, $hits, $amount, $item_name, $email, $first_name, $last_name,
$address1, $address2, $city, $state, $zip, $country, $USIT-txt, $invoiceNo, $expece_date);

$stmt->execute();			

$mysqli->close();

[/php]

Any help?
usit

Well, if it is exactly as you posted it, remove the ‘52’ from line #52. It is an extra line number!

Really!, Now you’re just breaking things out of the if() (cause we told you to) but you’re not rewriting the code to make sense. You’re still leaving the ! at the start of this line like it’s supposed to still be in the if()
[php]!$mysqli->query("CREATE TABLE test2[/php]
And you don’t have a ; at the end of the query code block, so it sees the next var and throws the error.
PHP works very logically, you need to think logically. Plan out the path that the script needs to take in order to accomplish the task. Like, this thing needs to happen first, then this, then if this happens do this.

Like ErnieAlex has said a few times and you still have not given us a reason for, why do you have all 3 of these queries in the first place. I can’t even fathom a instance that you should be dropping a table and instantly creating it again only to insert data to it. That makes absolutely no sense, unless you can give us a very specific reason for it. Your logic is highly flawed!

I totally agree with Fatsol…

Please explain why you delete the table and then create it? That is mostly the part we do not understand!

(3rd try to answer your question. I get part way through an answer, need to go get some information, and can’t get back into this program again. Don’t know how to do that yet. Now I have 2 copies of Fiirefox open; one with this reply and one with your question – seems to be working.)

The nested ||'s script was lifted from a tutorial mysqli site. I left in the deletion and creation of a table. It is not needed, but it simplified the unix display of a table to one row of data, which keeps the table headings visible over repeated test runs.

I’ve restarted the process of copying a valid script and modifying it. Here’s my current source:

http://www.phphelp.com/forum/mysql-database/(dispicable-err)-syntax-error-unexpected-t_variable/new/?topicseen#new
The script follows:

<?php $mysqli = new mysqli('localhost', 'my_user', 'my_password', 'world'); /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } $stmt = $mysqli->prepare("INSERT INTO CountryLanguage VALUES (?, ?, ?, ?)"); $stmt->bind_param('sssd', $code, $language, $official, $percent); $code = 'DEU'; $language = 'Bavarian'; $official = "F"; $percent = 11.2; /* execute prepared statement */ $stmt->execute(); printf("%d Row inserted.\n", $stmt->affected_rows); /* close statement and connection */ $stmt->close(); /* Clean up table CountryLanguage */ $mysqli->query("DELETE FROM CountryLanguage WHERE Language='Bavarian'"); printf("%d Row deleted.\n", $mysqli->affected_rows); /* close connection */ $mysqli->close(); ?>

Here’s a fresh start at its modification: This abbreviated script tests only the first stage – accessing the DB, which throws an error …

<?php include_once ($_SERVER['DOCUMENT_ROOT'] . '/cgi-bin/cnnct2mysqli.php'); //In cnnct2mysqli.php the 4 parameters have single quote marks. $mysqli = new mysqli($DBServer, $DBUser, $DBPass, $DBName); /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } $mysqli->close(); ?>

…“Connect failed: Access denied for user ‘ntelleckdb’.”

The line of new mysqli() with 4 parameters was typed with `, ', ", and no superscript marks. All produced connection failures naming one of the 4 parameters (usually server or user).

Of course, I’ve cut/pasted the include_once statement from my usual (working) scripts yet get this error. I’ve also replaced the include_once statement with 4 individual definition statements. No luck their either.

I’ve sent an email to my isp asking for corroboration of the 4 credential parameters. I’m waiting to hear.

I appreciate your patience.
usit

Update 9:45am 25July14
//My ISP informs: “Bear in mind that you are using mysql_select_db when opening the connection with mysqli.”
//The PHP manual says, re; ‘mysql_select_db’: “This extension is deprecated as of PHP 5.5.0.
// … The MySQLi or PDO_MySQL extension should be used.”
//I don’t see that I’m using mysql_select_db anywhere. Does $mysqli=new mysqli() not work?
//I know I’m confused, but haven’t discovered the root cause.

Here’s my latest test.

[php]include_once ($_SERVER[‘DOCUMENT_ROOT’] . ‘/cgi-bin/cnnct2mysqli.php’);

$mysqli = new mysqli($DBServer, $DBUser, DBPass, $DBName);

/* check connection */
if (mysqli_connect_errno()) {
printf(“Connect failed: %s\n”, mysqli_connect_error());
exit();
}
$mysqli->close();[/php]

usit :frowning: Another week of going in circles.

You’re mixing oop mysqli and procedural mysqli. You’re connecting using oop but then try to use the procedural mysqi_connect_errono.

RTFM http://php.net/manual/en/mysqli.connect-errno.php

(2nd time on this reply. Lost 1st try when trying to check on an email announcing fastsol’s reply).
Thanks fastsol. I know better than mixing oo and procedural mysqli, but didn’t recognize that I had fallen into that trap. Thanks too for the reference. That’s a new one for me.

I’ve managed to get past the error in accessing the mysqli data base. Then two steps later it’s back. (Connect Error: 1045) – disallowed access. This time I’m not spending two days chasing corroboration of my mysqli credentials, since, although the error message pointed to that cause, it turned out to be a red herring.

Here’s what I have done – from the web …

<?php //testCreatInsrtBindExec.php include_once ($_SERVER['DOCUMENT_ROOT'] . '/cgi-bin/cnnct2mysqli.php'); //Previous failure ... //$mysqli = new mysqli($DBServer, $DBUser, DBPass, $DBName); //$link = mysqli_connect("$DBServer", "$DBUser", "$DBPass", "$DBName") ; //mysqli_error($link); //Latest trial (from the web) to get past mysqli connection ... //http://php.net/manual/en/mysqli-stmt.bind-param.php $mysqli = @new mysqli($DBServer, $DBUser, DBPass, $DBName); //Connect error 1045 if ($mysqli->connect_errno) { die('Connect Error: ' . $mysqli->connect_errno); } $code = 'DEU'; $language = 'Bavarian'; $official = "F"; $percent = 11.2; $stmt = $mysqli->prepare("INSERT INTO test2 VALUES (?, ?, ?, ?)"); $stmt->bind_param('sssd', $code, $language, $official, $percent); $stmt->execute(); /* check connection */ //if (mysqli_connect_errno()) { // printf("Connect failed: %s\n", mysqli_connect_error()); exit(); $mysqli->close(); ?>

Ever appreciating your insights.
usit

If I can get this recommended code to work, I’ll switch to the original insert_into db code.

From what I’m reading in the manual, the @ here [php]@new[/php]Will produce the error code you have. Get rid of the @, it’s a terrible thing to use anyway. All it does it stop errors from showing up in the code. They only had it in the example code to show how it works to produce errors, not for real world use.

Yes, fastsol, but, I removed the @ to no avail. These seemingly misleading error messages that point to bad connection data but are only red herrings, are what caused me to use the word despicable. I would have removed the @ for php reasons but I’ve become paranoid trying to adapt to mysqli.

I’m presently searching the web for other tutorials.

Thanks,
usit

Check out phpacademy on youtube. Alex on there is very good and uses real world examples.

Sponsor our Newsletter | Privacy Policy | Terms of Service