Jump to content

Having a problem with my first PHP script


Freedom-n-Democrazy

Recommended Posts

Previously, the PHP codebase I was using was that written by others, and I used their code to tinker with so I could get an understanding how PHP works.

Now that I am comfortable using PHP, I have written my own short PHP script from scratch with the aim of it seeing my newsletter system functioning at minimal, for the first time.

The newsletters system is made with HTML/PHP/MySQL.

 

I am having a problem with the PHP side of things where I am getting an error:

PHP Parse error: syntax error, unexpected T_IF on line 50

... which is:

if $_POST['action'] == 'Register' {

 

I am hoping someone that knows allot about PHP could take a look at my code and see whats wrong with it?

 

PHP code within confirm.html:

<?php
$link = mysql_connect('localhost', 'testusr', 'testpw');
mysql_select_db('testdb', $link);
$email = $_POST['e-mail'];
$query = 
	if $_POST['action'] == 'Register' {
		if $_POST['newsletter'] == 'Mens' {
			"INSERT INTO newsletters(mens) VALUES('$email')";
		}
		elseif $_POST['newsletter'] == 'Mens & Womens' {
			"INSERT INTO newsletters(mensandwomens) VALUES('$email')";
		}
		elseif $_POST['newsletter'] == 'Womens' {
				"INSERT INTO newsletters(womens) VALUES('$email')";
		}
	;}
mysql_query ($link, $query);
mysql_close($link);
?>

 

HTML FORM code within index.html:

<FORM action="confirm.html" method="post">
<DIV>
	<SPAN class="input">
		Action:	
			<SELECT name="action">
				<OPTION>Register</OPTION>
				<OPTION>Unregister</OPTION>
			</SELECT>&nbsp&nbsp&nbsp
		E-mail:	<INPUT name="e-mail" type="text"></INPUT>&nbsp&nbsp&nbsp
		Newsletter: 
			<SELECT name="newsletter">
				<OPTION>Mens</OPTION>
				<OPTION>Mens & Womans</OPTION>
				<OPTION>Womens</OPTION>
			</SELECT>&nbsp&nbsp&nbsp
		<INPUT class="submit" type="submit" value="Submit">
	</SPAN>
</DIV>
</FORM>

Link to comment
Share on other sites

try this

 


<?php
$link = mysql_connect('localhost', 'testusr', 'testpw');
mysql_select_db('testdb', $link);
$email = $_POST['e-mail'];
$query = "";
	if ($_POST['action'] == 'Register') {
		if ($_POST['newsletter'] == 'Mens') {
			$query = "INSERT INTO newsletters(mens) VALUES('$email')";
		}
		elseif ($_POST['newsletter'] == 'Mens & Womens') {
			$query = "INSERT INTO newsletters(mensandwomens) VALUES('$email')";
		}
		elseif ($_POST['newsletter'] == 'Womens') {
			$query = "INSERT INTO newsletters(womens) VALUES('$email')";
		}
	;}
mysql_query ($link, $query);
mysql_close($link);
?>

Link to comment
Share on other sites

Some problems are now fixed. :)

 

I now get only one error.

 

The code sits at this:

<?php
$link = mysql_connect('localhost', 'testusr', 'testpw');
mysql_select_db('testdb', $link);
$email = $_POST['e-mail'];
if ($_POST['action'] == 'Register') {
	if ($_POST['newsletter'] == 'Mens') {
		"INSERT INTO newsletters(mens) VALUES('$email')";
	}
	elseif ($_POST['newsletter'] == 'Mens & Womens') {
		"INSERT INTO newsletters(mensandwomens) VALUES('$email')";
	}
	elseif ($_POST['newsletter'] == 'Womens') {
		"INSERT INTO newsletters(womens) VALUES('$email')";
	}
}
mysql_query ($link);
mysql_close($link);
?>

 

The error:

PHP Warning:  mysql_query() expects parameter 1 to be string on line 57:

mysql_query ($link);

 

One problem I can see here is that PHP does not know its suppose to execute that code as a MySQL query. As can be seen in my initial post, I tried to set the "if" command to $query, and then inserted $query into "mysql_query ()", but PHP was not liking me using $query with the "if" statement. Why is that?

Link to comment
Share on other sites

Hey guys!

 

What I did was:

 

if ($_POST['action'] == 'Register') {

if ($_POST['newsletter'] == 'Mens') {

$query = "INSERT INTO newsletters(mens) VALUES('$email')";

 

... and set mysql_query to "mysql_query ($query);" and it worked!!!!!!!!

 

Thanks so much for your help guys. Any time you need a favor (even if its not related to PHP) just send me through a PM and ask. :)

Link to comment
Share on other sites

Arghhhhhhh!!!

 

Now I am getting another error. I can register an e-mail address for the mens newsletter, but cannot register an e-mail address for the Mens & Womens or Womens newsletters.

 

I get the error:

PHP Notice:  Undefined variable: query on line 57

mysql_query ($query);

 

The code sits at this:

<?php
$link = mysql_connect('localhost', 'testusr', 'testpw');
	mysql_select_db('testdb', $link);
	$email = $_POST['e-mail'];
	if ($_POST['action'] == 'Register') {
		if ($_POST['newsletter'] == 'Mens') {
			$query = "INSERT INTO newsletters(mens) VALUES('$email')";
		}
		elseif ($_POST['newsletter'] == 'Mens & Womens') {
			$query = "INSERT INTO newsletters(mensandwomens) VALUES('$email')";
		}
		elseif ($_POST['newsletter'] == 'Womens') {
			$query = "INSERT INTO newsletters(womens) VALUES('$email')";
		}
	}
mysql_query ($query);
mysql_close($link);
?>

Link to comment
Share on other sites

The mysql_query() statement is outside/after the end of the if($_POST['action'] == 'Register'){} conditional statement where the $query variable is defined, so, every time the page is requested, regardless of the $_POST['action'] value, $query is referenced, resulting in a php error being generated.

 

The mysql_query() statement should be inside the  if($_POST['action'] == 'Register'){...} conditional statement where the $query variable is defined so that it is only executed when the form was submitted and the $query variable has a value.

 

Also, your if/elseif logic testing the $_POST['newsletter'] value allows the query to be executed when the $_POST['newsletter'] value does not match any of the possible choices. You should make sure that value is one of the choices. If it is not, you should output a user messages alerting them that an invalid value was selected and don't execute the query.

 

Finally, if after making those changes to the logic, you think you are submitting one of the choices but your code did not match it, you would need to troubleshoot what the actual submitted value is. Using echo or var_dump on the $_POST['newsletter'] variable would display what it contains.

Link to comment
Share on other sites

Comments, comments, comments - Use Them! A good programmer writes just as many lines of comments as he does of code (if not more). By adding comments, it gives context to the code and many times you can "see" logical mistakes that have been done.

 

In addition to what PFMaBiSmAd stated I think there must be another problem if you cannot register for the other two options. But, I have to ask, why are there THREE values and not TWO? You only need a "mens" value and a "womens" value - both in your form and in the database. The database table should have a field for the email address and then two fields to specify mens and womens which would be 0 (not selected) or 1 (selected). I don't know what your form looks like but, personally, I would use two checkboxes.

 

Also, if something doesn't operate as you expect - add debugging code to echo variables and results to the page to see what went wrong where.

 

Here is some updated code - I give no warranty as to whether it fixes your problems, but it should help identify the problem.

<?php

if ($_POST['action'] == 'Register')
{
    #Only need to connect to database if there was data submitted
    //Connect to DB server
    $link = mysql_connect('localhost', 'testusr', 'testpw');
    if(!$link)
    {
        die("Unable to connect to database");
    }
    //Select database
    if(!mysql_select_db('testdb', $link))
    {
        die("Unable to select database";
    }

    //Validate email address
    $email = mysql_real_escape_string(trim($_POST['e-mail']));
    if(empty($email))
    {
        echo "Error: Email address is required";
    }
    else
    {
        //Generate query based upon newsletter selection
        $query = false;
        if ($_POST['newsletter'] == 'Mens')
        {
            $query = "INSERT INTO newsletters(mens) VALUES('$email')";
        }
        elseif ($_POST['newsletter'] == 'Mens & Womens')
        {
            $query = "INSERT INTO newsletters(mensandwomens) VALUES('$email')";
        }
        elseif ($_POST['newsletter'] == 'Womens')
        {
            $query = "INSERT INTO newsletters(womens) VALUES('$email')";
        }

        //Check that a valid selection was made
        if(!$query)
        {
            echo "Error: No valid newsletter selection made: '{$_POST['newsletter']}'";
        }
        else
        {
            //Run query
            if(!mysql_query($query))
            {
                echo "Error: Unable to add record.";
                echo "<br>Query: {$query}<br>Error: " . mysql_error(); #only enable this line for debugging
            }
            else
            {
                echo "Your submission has been registered";
            }
        }
    }
    //Close DB connection
    mysql_close($link);
}

?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.