Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
Zorilla
Mar 23, 2005

GOING APE SPIT

drcru posted:

Would it be very memory/cpu intesive if I looped through this and checked for conditions?

PHP has quite a few functions for searching for things in arrays or running callbacks for things in arrays, etc. Would in_array() work for what you need?

Adbot
ADBOT LOVES YOU

Acer Pilot
Feb 17, 2007
put the 'the' in therapist

:dukedog:

Zorilla posted:

PHP has quite a few functions for searching for things in arrays or running callbacks for things in arrays, etc. Would in_array() work for what you need?

I actually need to run through everything in the array and output something, if the value is less than 1 it's supposed to output something as well.

I'm thinking two for loops and some conditional statements but that doesn't sound too memory efficient.

oryx
Nov 14, 2004




Fun Shoe

drcru posted:

I actually need to run through everything in the array and output something, if the value is less than 1 it's supposed to output something as well.

I'm thinking two for loops and some conditional statements but that doesn't sound too memory efficient.

If you have a 2 dimensional list of unsorted elements, then you have to look through every element in the array. You don't really have any other strategy if you're not sorting the arrays, so it's hard to say that it's intensive.

Begby
Apr 7, 2005

Light saber? Check. Black boots? Check. Codpiece? Check. He's more machine than kid now.

drcru posted:

Would it be very memory/cpu intesive if I looped through this and checked for conditions?

Looping through an array is not that memory intensive in php. You can probably increase that array to include a couple of thousand elements and not notice too much of a hit. Try creating a loop from 1 to 10,000 that generates an array like this, then loop through it and see how much of a difference it makes.

Bottlenecks typically appear in database queries and file access.

Acer Pilot
Feb 17, 2007
put the 'the' in therapist

:dukedog:

Begby posted:

Looping through an array is not that memory intensive in php. You can probably increase that array to include a couple of thousand elements and not notice too much of a hit. Try creating a loop from 1 to 10,000 that generates an array like this, then loop through it and see how much of a difference it makes.

Bottlenecks typically appear in database queries and file access.

Thanks to all for the replies.

LP0 ON FIRE
Jan 25, 2006

beep boop
mysql_real_escape_string is making variables blank for me. For instance, I have:

$nameVar="test";
$nameVar=mysql_real_escape_string($nameVar);
echo "name".$nameVar;


I found was now inserting nothing into my database and echos nothing back. Anyone know what could cause this issue?

Strong Sauce
Jul 2, 2003

You know I am not really your father.





awdio posted:

mysql_real_escape_string is making variables blank for me. For instance, I have:

$nameVar="test";
$nameVar=mysql_real_escape_string($nameVar);
echo "name".$nameVar;


I found was now inserting nothing into my database and echos nothing back. Anyone know what could cause this issue?

Possibly this,

quote:

Note: A MySQL connection is required before using mysql_real_escape_string() otherwise an error of level E_WARNING is generated, and FALSE is returned. If link_identifier isn't defined, the last MySQL connection is used.

LP0 ON FIRE
Jan 25, 2006

beep boop

Strong Sauce posted:

Possibly this,

Ah! I remember reading that somewhere. Thanks!

Vedder
Jun 20, 2006

I am currently updating our very old website at work. I have experience with static pages and I have mostly used ASP.NET if I am doing any scripting/database work but for this project decided to construct it in PHP with a mySQL database (due to the facts that I have never tried PHP and our ASP.NET hosting isn't very good). I have a couple of questions if thats ok.

The website is for a law practice that I work at. This site is constructed with some of the following pages:

1. News and events (index)
2. Lawyer profiles (pretty much all the same, picture for each one and a small biography)
3. Contact us
4. Specialisations of a certain department (with links to the profiles of whoever does these)

The questions:

1. Can this be done in PHP and how difficult would it be? how do you but, say a whole paragraph of text in a database, and is that wise? Or should it be left static?

2. The lawyers profile I imagine would be done in PHP, I have done similar in ASP.NET, where you have one page set up and the lawyers name or id passed to a database query, which then decides which profile to show on screen. Again I ask about the text paragraphs like I have above.

3. Contact us I am thinking would be an input form type thing which should'nt be much different from ASP.NET?

4. Specialisations would be a series of bullet points and a query to get the relevant lawyer which shouldn't be too hard.

Basically I am asking would I be on the right lines here or am I completely way off?

Thanks people.

jasonbar
Apr 30, 2005
Apr 29, 2005

Vedder posted:

I am currently updating our very old website at work.

This can be done quite easily in PHP, however you may want to consider the following:

1. Unless you are writing a CMS (or implementing an existing framework) or providing multi-language support, much of this data can be static. Profiles and specializations are not likely to change often enough to warrant being in a database.
2. The contact form should be similar to one in ASP. Make sure you aren't leaving an open relay out, though. Validate *everything* the user can enter.
3. News and events can be taken care of with a simple management script for input, and an even simpler view for output. You probably want this in the DB. As for getting the data there, look into http://us.php.net/mysqli. It would be beneficial to get used to using prepared statements early in your learning.

LastCaress
May 8, 2004

bonobo
Is there a way for a page to send me an email each time it is accessed with the IP/referral of the user? Obviously the page would not be linked elsewhere or I'd get a million mails. Thanks.

Strong Sauce
Jul 2, 2003

You know I am not really your father.





LastCaress posted:

Is there a way for a page to send me an email each time it is accessed with the IP/referral of the user? Obviously the page would not be linked elsewhere or I'd get a million mails. Thanks.

If the mail server is setup then you could just put
code:
<?php mail('YOUR EMAIL ADDRESS','SUBJECT','MESSAGE','From: name <email@email.com\nOTHER HEADERS'); ?>
Edit: Added close tag

Strong Sauce fucked around with this message at 23:14 on Oct 28, 2008

Zorilla
Mar 23, 2005

GOING APE SPIT

Strong Sauce posted:

If the mail server is setup then you could just put
code:
<?php mail('YOUR EMAIL ADDRESS','SUBJECT','MESSAGE','From: name <email@email.com\nOTHER HEADERS'); ?>

mail() doesn't work consistently across servers and you have to set up headers, attachements, etc. totally by hand, so I would recommend using the PHPMailer class to make setting up and sending emails a lot easier. You'll need it anyway if you want to use SSL/TLS since PHP doesn't handle any of that on its own.

You can also take a look at SwiftMailer, but I don't prefer it because it's way too huge and suffers from class-itis.

Zorilla fucked around with this message at 00:43 on Oct 29, 2008

LastCaress
May 8, 2004

bonobo
<?php mail('YOUR... worked great, I'll look into phpmailer as well but it seems a bit more complex :) Any idea how to insert functions like $HTTP_USER_AGENT in the mail I get?

Zorilla
Mar 23, 2005

GOING APE SPIT

LastCaress posted:

<?php mail('YOUR... worked great, I'll look into phpmailer as well but it seems a bit more complex :) Any idea how to insert functions like $HTTP_USER_AGENT in the mail I get?

You mean like passing it on in the message body? It should just be $_SERVER["HTTP_USER_AGENT"].

Also, PHPMailer is loads more simple with anything more complex than a small text-only message:

php:
<?
[sub]
<?php

require("class.phpmailer.php");

$mail = new PHPMailer();

$mail->IsSMTP();  // telling the class to use SMTP
$mail->Host     "smtp.example.com"// SMTP server

$mail->From     "from@example.com";
$mail->AddAddress("myfriend@example.net");

$mail->Subject  "First PHPMailer Message";
$mail->Body     "Hi! \n\n This is my first e-mail sent through PHPMailer.";
$mail->WordWrap 50;

if(!$mail->Send()) {
    echo 'Message was not sent.';
    echo 'Mailer error: ' $mail->ErrorInfo;
} else {
    echo 'Message has been sent.';
}
?>
[/sub]?>
Adding attachments is as simple as using $mail->AddAttachment($somefile) instead of having to figure out how to MIME-encode it and adding it to the message body.

LastCaress
May 8, 2004

bonobo
Thanks, these solutions work great :)

Laserjet 4P
Mar 28, 2005

What does it mean?
Fun Shoe
If part of this is old news or obvious to you, feel free to ignore it.

Vedder posted:

1. News and events (index)
Make 2 tables for these in MySQL. I'm thinking something like
EventId (int, auto_increment)
DatePublished (datetime)
EventStartDate (datetime)
EventEndDate (datetime)
Visible (tinyint(1)
Deleted (tinyint(1)
Title (varchar(255))
Content (text or mediumtext)
Url (varchar(255)) to store something like "php-questions-that-dont-need-their-own" for SEO.

NewsId (int, auto_increment)
DatePublished (datetime)
Visible (tinyint(1)
Deleted (tinyint(1)
Title (varchar(255))
SubTitle (varchar(255))
Content (text or mediumtext)
Url (varchar(255))

If you've never worked with the stuff the Smarty templating system is probably a bit overkill, but try to keep your viewing/displaying code separated (basically, Smarty makes it nearly impossible for you do to clever poo poo so your display code is readable).

quote:

2. Lawyer profiles (pretty much all the same, picture for each one and a small biography)
Another table called Lawyer (with LawyerId, Biography, Dob, Address, etc.). While the profiles themselves may not change a lot, if a new associate is added or the layout changes all you should have to do is add one in the database.

quote:

1. Can this be done in PHP and how difficult would it be? how do you but, say a whole paragraph of text in a database, and is that wise? Or should it be left static?
Paragraphs are not a problem at all, while SQL Server's "TEXT" datatype goes up to 4 billion characters, MySQL's "TEXT" goes up to 65k. "BIGTEXT" does the 4 bil.

quote:

2. The lawyers profile I imagine would be done in PHP, I have done similar in ASP.NET, where you have one page set up and the lawyers name or id passed to a database query, which then decides which profile to show on screen. Again I ask about the text paragraphs like I have above.
Not an issue at all. You can cram shitloads of text in there and unless someone's going to copy the Bible in there 4 times it's not going to be an issue.

quote:

4. Specialisations would be a series of bullet points and a query to get the relevant lawyer which shouldn't be too hard.
Make a table with LawyerSpecialization that has an LawyerId and a SpecializationId, if you know how JOINs work you're good.

quote:

3. Contact us I am thinking would be an input form type thing which should'nt be much different from ASP.NET?

Yes and no.

With ASP.NET each form posts back to itself. With PHP, this is not always desirable as it means you'll mix presentation (the form textboxes) with logic (what has to be done with whatever's been typed afterwards?)

With ASP.NET you have Page_Load and OnClick events pretty clearly defined. With PHP you don't.

Your host is probably going to give you a public_html directory. When you set up the site structure, make a separate directory called "postback" where you put your contact.php form. This makes it obvious (by name) that contact.php in the root and /postback/contact.php are related, which means no tortured naming conventions.

With ASP.NET you have a nice web.config file where you store all kinds of stuff in. With PHP, you probably make a config.php file that is included right at the start and not accessible for anyone else except Apache (use .htaccess for this).

Seconding the validation by the way; mysql_real_escape_string is your friend. If it's yes or no, a single checkbox or 2 radiobuttons. If it's 3 choices, 3 radiobuttons - for more, use a dropdown. Also, the user should never see more than a friendly error message; once your forms are spewing back "query failed - could not perform INSERT INTO User (user_id, pass)" poo poo, you're doing it wrong.

Laserjet 4P fucked around with this message at 21:41 on Oct 29, 2008

Stephen
Feb 6, 2004

Stoned
My script is supposed to loop through a series of files and FTP each of those files to a specified address.
php:
<?
for($i=0; $i<count($array['filenames']); $i++) {
    $sent = $this->ftpPublishPhoto($array['filenames'][$i]);
    if($sent) {
        //echo 'Photo: '.$i.' sent';
    } else {
        //echo 'Photo: '.$i.' failed';
    }
}

//Here's the method stripped down
function ftpPublishPhoto($file) {
    //Function Returns: true on success, false on failure
    $conn_id = ftp_connect($ftpaddress);
    $login_result = ftp_login($conn_id, $username, $pass);
    //check connection
    if (($conn_id) && ($login_result)) {
        $sent = ftp_put($conn_id, $file, $file, FTP_BINARY);
    } else {
        return false;
    }
    ftp_close($conn_id);
    return $sent;
}
?>
Now this is working perfectly for about 95% of the files that I try to upload, however 1/20 files fails and returns false. It's never the same files, it seems totally random each time.

Is there some kind of timeout or restriction that I may be hitting in PHP or perhaps even on the FTP server?

Zorilla
Mar 23, 2005

GOING APE SPIT

Stephen posted:

Is there some kind of timeout or restriction that I may be hitting in PHP or perhaps even on the FTP server?

Maybe you'd get better performance by logging in once, uploading all the files, then disconnecting instead of connecting/disconnecting for each file.

oryx
Nov 14, 2004




Fun Shoe

Stephen posted:

Now this is working perfectly for about 95% of the files that I try to upload, however 1/20 files fails and returns false. It's never the same files, it seems totally random each time.

Is there some kind of timeout or restriction that I may be hitting in PHP or perhaps even on the FTP server?

In the past, timeout errors stopped the script entirely, so I would have thought a time out issue would have caused a cascade of errors. Still, if you want to rule that out, you can increase the time out duration using ini_set or set_time_limit.

Have you checked to see if $sent is being set to false, or if it's failing because $conn_id and $login_result are being false? I agree with Zorilla, you might want to rewrite that code so that the connection and log in are outside the function, and just pass the file handle as into the function.

It also could be a lovely ftp if it's not a great server?

Stephen
Feb 6, 2004

Stoned

oryx posted:

In the past, timeout errors stopped the script entirely, so I would have thought a time out issue would have caused a cascade of errors. Still, if you want to rule that out, you can increase the time out duration using ini_set or set_time_limit.

Have you checked to see if $sent is being set to false, or if it's failing because $conn_id and $login_result are being false? I agree with Zorilla, you might want to rewrite that code so that the connection and log in are outside the function, and just pass the file handle as into the function.

It also could be a lovely ftp if it's not a great server?

I changed around the server connection to only connect/disconnect once and I'm still getting the same issue. Out of 100 files all under 100k, anywhere between 5-10 will not go through. $sent does come back as false when it fails, however.

php:
<?
for($i=0; $i<count($array['filenames']); $i++) {
     $sent = $this->ftpPublishPhoto($array['filenames'][$i]);
     if($sent) {
         //echo 'Photo: '.$i.' sent';
     } else {
         $this->ftpPublishPhoto($array['filenames'][$i]);
     }
} 
?>
This is obviously not fixing the problem, but when I tested it, it's working 100/100 files now. So I guess instead of 5% of the files not being uploaded it will only be 0.25% of the files.

Munkeymon
Aug 14, 2003

Motherfucker's got an
armor-piercing crowbar! Rigoddamndicu𝜆ous.



Stephen posted:

This is obviously not fixing the problem, but when I tested it, it's working 100/100 files now. So I guess instead of 5% of the files not being uploaded it will only be 0.25% of the files.

Stuff the failures into an array and iterate over it in a second loop, removing files that succeed, until it's empty.

Stephen
Feb 6, 2004

Stoned

Munkeymon posted:

Stuff the failures into an array and iterate over it in a second loop, removing files that succeed, until it's empty.
I wanted to do this, however I'm afraid of creating an infinite loop in the event that one of the files is broken or invalid.

waffle iron
Jan 16, 2004

Stephen posted:

I wanted to do this, however I'm afraid of creating an infinite loop in the event that one of the files is broken or invalid.
Then count how many times you loop and stop at a sane number of retries. Log the ones that still fail for followup.

Munkeymon
Aug 14, 2003

Motherfucker's got an
armor-piercing crowbar! Rigoddamndicu𝜆ous.



Stephen posted:

I wanted to do this, however I'm afraid of creating an infinite loop in the event that one of the files is broken or invalid.

What waffle iron said and your script would time out at some point, so infinite isn't actually all that long. You could also insert a short delay between each file in the recovery loop just in case the FTP server thinks it's getting hammered.

microwave casserole
Jul 5, 2005

my god, what are you doing
I'm thinking about writing a very simple content-management system that reads articles from an RSS file instead of a database. It would basically be a site-specific RSS reader, with manual editing of the RSS file instead of something where you log into the site to make new entries.

Is this a decent idea code-wise? I'm pretty new to PHP and programming for the internet, so I don't know if this would be horribly inefficient or have any other conceptual problems.

DaTroof
Nov 16, 2000

CC LIMERICK CONTEST GRAND CHAMPION
There once was a poster named Troof
Who was getting quite long in the toof

microwave casserole posted:

I'm thinking about writing a very simple content-management system that reads articles from an RSS file instead of a database. It would basically be a site-specific RSS reader, with manual editing of the RSS file instead of something where you log into the site to make new entries.

Is this a decent idea code-wise? I'm pretty new to PHP and programming for the internet, so I don't know if this would be horribly inefficient or have any other conceptual problems.

That sounds really impractical. RSS is an okay format for distributing data, but a terrible way to store and manage content.

Zorilla
Mar 23, 2005

GOING APE SPIT

microwave casserole posted:

I'm thinking about writing a very simple content-management system that reads articles from an RSS file instead of a database. It would basically be a site-specific RSS reader, with manual editing of the RSS file instead of something where you log into the site to make new entries.

Is this a decent idea code-wise? I'm pretty new to PHP and programming for the internet, so I don't know if this would be horribly inefficient or have any other conceptual problems.

PHP has support for DOM, so reading items from XML files should be pretty easy. Reading from a WordPress feed would look something like this (yeah, the filename is totally wrong, I know):

php:
<?php
$xml = new DOMDocument();
$xml->load("rss.xml");

$items $xml->getElementsByTagName("item");

foreach ($items as $item) {
?>
<p>Article Name: <?php echo $item->getElementsByTagName("title")->item(0)->nodeValue?><br />
Link: <?php echo $item->getElementsByTagName("link")->item(0)->nodeValue?><br />
Published: <?php echo $item->getElementsByTagName("pubDate")->item(0)->nodeValue?></p>
<?php
}
?>

Like the guy before me said, it's probably fine for read-only stuff, but a database is much, much more appropriate if you're going to be making frequent changes.

Zorilla fucked around with this message at 23:31 on Nov 1, 2008

microwave casserole
Jul 5, 2005

my god, what are you doing
Cool, thanks for the help. This is mainly a learning process thing, so even if it turns out impractical at least I'll have learned what not to do. :)

Strong Sauce
Jul 2, 2003

You know I am not really your father.





Yeah if for some reason you can't access a database using flatfiles is probably a better solution than using an XML document to handle it.

Hammerite
Mar 9, 2007

And you don't remember what I said here, either, but it was pompous and stupid.
Jade Ear Joe
EDIT: My silly fault for not uploading some file or other. Ignore this post.

I'm having a problem passing a variable created by a MySQL query to a function.

I've defined the following function, getdata, to make life easy:

php:
<?
function getdata ( $cxn, $fetchassoc, $query ) {
    $QueryResult = mysqli_query($cxn,$query);
    if ( !$QueryResult ) { $NoResults = 1; }
    else if ( mysqli_num_rows($QueryResult) == 0 ) { $NoResults = 1; }
    else { $NoResults = 0; }
    if ( $NoResults ) {
        return "NONE";
    } else if ( $fetchassoc ) {
        return mysqli_fetch_assoc($QueryResult);
    } else {
        return $QueryResult;
    }
}?>
I've also defined this function, gamelistdisplayp, which is supposed to take the output from a MySQL query obtained using getdata, and put it into a pretty little table:

php:
<?
function gamelistdisplayp ($cxn,$QueryResult) {

    echo "<table border=1><tr><td><b>Name</b></td><td><b>Creator</b></td>
<td><b>Original</b></td><td><b>Current</b></td><td><b>Phase</b></td>
<td><b>Round</b></td><td><b>Num rounds</b></td>
<td><b>Last Move</b></td><td><b>Player To Move</b></td></tr>";
    if ( $QueryResult == "NONE" ) {
        echo "<tr><td colspan=9 align=center>None</tr>";
    } else {
        while( $row = mysqli_fetch_assoc( $QueryResult ) ) { // LINE 36
            if ( $row[GTitleDeletedByAdmin] ) { $CleanGameTitle = "The
title of this game has been cleared by an Administrator"; }
            else { $CleanGameTitle = $row[GameName]; }
            if ( $row[RailPhase] ) { $phasename = "Rail"; }
else { $phasename = "Canal"; }
            $QueryResultB = mysqli_query ($cxn,"SELECT Name FROM User
WHERE UserID = '{$row[GameCreator]}'")
or die($readerrormessage);
            $rowB = mysqli_fetch_assoc( $QueryResultB );
            $QueryResultC = mysqli_query ($cxn,"SELECT Name FROM User
WHERE UserID = '{$row[PlayerToMove]}'")
or die($readerrormessage);
            $rowC = mysqli_fetch_assoc( $QueryResultC );
            $lastmovetime = date("Y-m-d H:i:s",strtotime($row[LastMove]));
            echo "<tr><td><a href=\"board.php?GameId={$row[GameID]}\">
{$CleanGameTitle}</a></td>
<td><a href=\"userdetails.php?UserID={$row[GameCreator]}\">{$rowB[Name]}</a></td>
<td>{$row[OriginalPlayers]}</td><td>{$row[CurrentPlayers]}</td>
<td>{$phasename}</td>
<td>{$row[Round]}</td>
<td>{$row[NumRounds]}</td><td>{$lastmovetime}</td>
<td><a href=\"userdetails.php?UserID={$row[PlayerToMove]}\">{$rowC[Name]}
</a></td></tr>";
        }
    }
    echo "</table>";
}?>
(Ignore the ugly line breaks, they are just there to avoid breaking tables.) But when I run the following code:

php:
<?
$QueryResult = getdata ($cxn,0,"SELECT GameID, GameName,
GTitleDeletedByAdmin, LastMove, GameCreator,
OriginalPlayers, CurrentPlayers, RailPhase, Round, NumRounds, PlayerToMove
FROM Game WHERE GameStatus = 'Recruiting Replacement'") or
die($readerrormessage);
gamelistdisplayp ($cxn,$QueryResult);?>
I get the error message

Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, object given in /(path to file excluded)/gamelistdisplay.php on line 36

I can't see what is wrong.

Hammerite fucked around with this message at 23:06 on Nov 7, 2008

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Hammerite posted:


I get the error message

Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, object given in /(path to file excluded)/gamelistdisplay.php on line 36

I can't see what is wrong.

Can you indicate to us which line is line 36 in your code?

Hammerite
Mar 9, 2007

And you don't remember what I said here, either, but it was pompous and stupid.
Jade Ear Joe

Lumpy posted:

Can you indicate to us which line is line 36 in your code?

Yeah, sorry. It's now indicated in the post.

Hammerite
Mar 9, 2007

And you don't remember what I said here, either, but it was pompous and stupid.
Jade Ear Joe
I apologise, it seems like I must just have failed to upload the latest version of one or other of my files - the problem spontaneously fixed itself when I undid some test changes I made.

Zorilla
Mar 23, 2005

GOING APE SPIT

Hammerite posted:

(Ignore the ugly line breaks, they are just there to avoid breaking tables.)

Well maybe if your code was tabbed sanely...

php:
<?
[sub]
<?php
function gamelistdisplayp ($cxn$QueryResult) {
    if ( (!isset( $cxn )) || (!isset($QueryResult)) )
        return false;
    
?>
<table style="border-width: 1px;">
    <tr>
        <th>Name</th>
        <th>Creator</th>
        <th>Original</th>
        <th>Current</th>
        <th>Phase</th>
        <th>Round</th>
        <th>Num rounds</th>
        <th>Last Move</th>
        <th>Player To Move</th>
    </tr>
<?php
    if ( mysqli_num_rows($QueryResult) === ) {
?>
    <tr>
        <td colspan="9" style="text-align: center;">None</td>
    </tr>
<?php
    } else {
        while ( $row mysqli_fetch_assoc$QueryResult ) ) {
            $CleanGameTitle = ( $row[GTitleDeletedByAdmin] ) ?
                "The title of this game has been cleared by an Administrator"
            :
                $row[GameName];
            $phasename = ( $row[RailPhase] ) ?
                "Rail"
            :
                "Canal";

            $QueryResultB mysqli_query($cxn"SELECT Name FROM User WHERE UserID = '{$row[GameCreator]}'")
                or die($readerrormessage);
            $rowB mysqli_fetch_assoc$QueryResultB );
            $QueryResultC mysqli_query($cxn"SELECT Name FROM User WHERE UserID = '{$row[PlayerToMove]}'")
                or die($readerrormessage);
            $rowC mysqli_fetch_assoc$QueryResultC );
            $lastmovetime date("Y-m-d H:i:s"strtotime($row[LastMove]));
?>
    <tr>
        <td><a href="board.php?GameId=<?= $row[GameID?>"><?= $CleanGameTitle ?></a></td>
        <td><a href="userdetails.php?UserID=<?= $row[GameCreator?>"><?= $rowB[Name?></a></td>
        <td><?= $row[OriginalPlayers?></td>
        <td><?= $row[CurrentPlayers?></td>
        <td><?= $phasename?></td>
        <td><?= $row[Round?></td>
        <td><?= $row[NumRounds?></td>
        <td><?= $lastmovetime ?></td>
        <td><a href="userdetails.php?UserID={$row[PlayerToMove]}"><?= $rowC[Name?></a></td>
    </tr>
<?php
        }
    }
?>
</table>
<?php
}
?>
[/sub]?>
Also, is there no way for you to perform those queries outside of a loop instead of potentially hundreds of times, each one for a single row of results? The current way seems really inefficient (e.g. you could instead do "SELECT blah FROM table WHERE UserID IN(w, x, y, z)" and put them into an array).

Zorilla fucked around with this message at 03:08 on Nov 8, 2008

roachfiend
Mar 5, 2002
Hello, PHP peeps. I have a question that I think is easily solved- the problem is I don't know what the hell I'm doing.

I have a web page that has a password login screen. It's a simple form field and a submit button. Code is as follows:

php:
<?
<H3>Login</H3>
<FORM METHOD="post" ACTION="http://erichamiter.com/news/fastnews-code.php">
<INPUT TYPE="hidden" NAME="fn_action" VALUE="login">
Password: <INPUT TYPE="password" SIZE="24" NAME="password" VALUE=""><BR>
<INPUT TYPE="submit" VALUE="Login">
</FORM>
?>
This works fine- but I would like for it to forward you to another page after submission.

I've googled a few things to help me solve it, and everyone generally recommends the use of a header. So, I added

php:
<?
header ("Location: http://www.example.com/next-page");
?>
to the top but it just immediately sends me to the next page- there's no time to enter data and hit submit.

I know it's something trivial but I don't know really the first drat thing about PHP. Obviously. I have a feeling I have to do something else with that login screen besides just giving it the .php suffix.

SuckerPunched
Dec 20, 2006

You need to wrap it in your processing code first:

php:
<?php
if ( isset($_POST['fn_action']))
{
  // do your form handling
  
  // ...
  
  // way down after all the form handling
  header('location:  http ://www.example.com/next-page');
  die(); // << this die is important as well.
}
?>

roachfiend
Mar 5, 2002
Parse error: syntax error, unexpected '<' in /home/news/login.php on line 5

Do I need to wrap up the form with some php magical thing? Remember, I'm an idiot.

jasonbar
Apr 30, 2005
Apr 29, 2005

roachfiend posted:

Parse error: syntax error, unexpected '<' in /home/news/login.php on line 5

Do I need to wrap up the form with some php magical thing? Remember, I'm an idiot.

You probably have something like this in your code:
php:
<?php
<form ....>
<input ...>

if ($...) // the login is valid
{
    header("your redirect url here");
    exit;
} 
?>

What you want is:

code:
<form ...>
<input...>
...
<?php
if ($...) // the login is valid
{
    header("wyour redirect url here");
    exit;
}
?>
Your HTML needs to be outside of the PHP tags.
edit: If not, paste your code so we can see.

jasonbar fucked around with this message at 04:59 on Nov 9, 2008

Adbot
ADBOT LOVES YOU

roachfiend
Mar 5, 2002
That fixed the syntax error, but now it doesn't redirect.

php:
<?
<H3>Login</H3>
<FORM METHOD="post" ACTION="http://erichamiter.com/news/fastnews-code.php">
<INPUT TYPE="hidden" NAME="fn_action" VALUE="login">
Password: <INPUT TYPE="password" SIZE="24" NAME="password" VALUE=""><BR>
<INPUT TYPE="submit" VALUE="Login">
</FORM>

<?php
if ( isset($_POST['fn_action'])) 
 {
 header('location:  http ://erichamiter.com/news/');
 die();
 } 
?> 
?>

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply