View Full Version : Random PHP Questions
Hunter
January 18th, 2010, 02:02 PM
I will probably have a few problems with PHP, as I am trying to learn it. So I have just made a thread, post your own problems if you have any.
I am getting an error, saying unexpected "}" on line 55. But I see no problem with it as it is closing both function/what ever you call them.
PHP:
<?php
//Delete
if (isset($_POST['deleteID'])) {
$id = mysql_real_escape_string($_POST['deleteID']);
$deleteFile = mysql_query("SELECT Nfilename FROM uploaded_files
WHERE ID ='$id'") or die(mysql_error());
$row = mysql_fetch_array( $deleteFile );
echo $row['DeleteFile'];
if (!deleteFile)
{
die('Error: ' .mysql_error())
}}
$delete = "DELETE FROM uploaded_files WHERE ID='$id'";
$result = mysql_query ($delete);
if (!$result)
{
die('Error: ' .mysql_error());
}
echo "<center><div style=\"background-color:#999999; border:0px; color:#339900; font-family:Calibri; font-weight:bold;\">Deleted entry number: $id. And Deleted image related to that entry.</div></center>";
}
?>
Just trying to see if the correct values are being pulled in, so I don't want the $delete query to be run, hense the reason I am closing the id statement before it gets to that.
legionaire45
January 18th, 2010, 02:16 PM
First off, I'd reccomend changing your formating to something more readable (not sure if it's just the quote tags that maimed it, but what you have isn't pretty to look at).
//Delete
<?php
if ( isset( $_POST[ 'deleteID' ] ) )
{
$id = mysql_real_escape_string( $_POST[ 'deleteID' ] );
$deleteFile = mysql_query( "SELECT Nfilename FROM uploaded_files WHERE ID ='$id'" ) or die( mysql_error() );
$row = mysql_fetch_array( $deleteFile );
echo $row[ 'DeleteFile' ];
if ( !deleteFile )
{
die( 'Error: ' .mysql_error() ); // Keep track of your semicolons...
}
}
$delete = "DELETE FROM uploaded_files WHERE ID='$id'";
$result = mysql_query( $delete );
if ( !$result )
{
die( 'Error: ' .mysql_error() );
}
echo "<center><div style=\"background-color:#999999; border:0px; color:#339900; font-family:Calibri; font-weight:bold;\">Deleted entry number: $id. And Deleted image related to that entry.</div></center>";
// Why is this bracket here if it isn't actually closing anything? Problem #2
// }
?>
This may just be a problem with your code's readability, but try and keep track of your semicolons. Stupid little mistakes like that are easily avoided by keeping your code clean.
Hunter
January 18th, 2010, 02:28 PM
I am guessing that bracket was causing the problem. Works now cheers :)
And the correct value is being pulled in, yey, bonus.
Another question:
When using the unlink() function I get an error. It is basically telling me that the directory does not exist:
Warning: unlink(../upload/images/1263842968.jpg) [function.unlink (http://martynleeball.x10hosting.com/portfolio/admin/function.unlink)]: No such file or directory in /home/martynba/public_html/portfolio/admin/delete.php on line 51PHP
//Delete
if (isset($_POST['deleteID'])) {
//Display filename
$id = mysql_real_escape_string($_POST['deleteID']); // Get value from button
$deleteFile = mysql_query("SELECT Nfilename FROM uploaded_files WHERE ID ='$id'") or die(mysql_error()); // Select database value
$row = mysql_fetch_array( $deleteFile ); // Run mysql_query
unlink("../upload/images/".$row['Nfilename']); //Delete file?
The directory which the images are contained in are below where the actual script is run, from my understanding you put "../" so that directories below where the script are searched.
Hunter
January 18th, 2010, 07:13 PM
Another problem, just figured out how to do this, proud of my self :)
But, the last record which I checked does not delete, and the top record will not delete either. :(
PHP
<?php
//**************************//
// Delete Selected Files //
//**************************//
//Variables
$values = $_POST['value'];
$i = 0;
//Select checked items
if (isset($_POST['DelSel'])) {
$count = count($values);
echo "Deleted records: ";
while ($i < $count) {
//unlink("../upload/images/".$values[$i]);
echo "$values[$i], ";
$i++;
//Delete record
$delete = "DELETE FROM uploaded_files WHERE ID='$values[$i]'";
$result = mysql_query ($delete);
if (!$result)
{
die('Error: ' .mysql_error());
}
}
}
?>
I am guessing that there is something wrong with the maths :/
GinjaNinja
January 19th, 2010, 09:36 PM
Hunter, in the delete selected files code, it looks like you need to move your:
$i++;to the bottom of the loop.
EDIT:
you might also want to change the while line to:
while($i < ($count + 1))
Hunter
January 20th, 2010, 05:03 AM
Works now, cheers :)
Rob Oplawar
January 20th, 2010, 07:38 PM
Be careful when using relative file paths. It is relative to the file that firsts starts executing, not to the file it appears in. Say you have this structure:
/etc/www/include/
/etc/www/include/process.php
/etc/www/index.php
/etc/www/photos/
/etc/www/photos/1.jpg
index.php includes process.php, and process.php has unlink('../photos/1.jpg'). That resolves to /etc/www/../photos/1.jpg, since index.php was where execution started. To avoid that, use absolute paths, or do this:
unlink(dirname(__FILE__) . '/../photos/1.jpg')
which resolves to /etc/www/include/../photos/1.jpg.
Hunter
January 21st, 2010, 04:09 PM
Cheers Rob. Here is another problem:
First of all the session ID value is checked, and exploded into two sections. These two parts are then checked with the database to see if they match.
If they do not match then the next if statement is run, which waits until the form fields are valid. Once valid the rest of the code (PROTECTED HTML) should be displayed. At the moment no code is being loaded once login fields are valid.
The problem I am having is with closing the if statements and where to put the "else" statements. What do I do? :(
<?php
session_start();
//Get database data and pull in
include "scripts/php/getData.php";
//Check if session exists
$session = $_SESSION['session'];
$session = explode (".", $session);
//Restart session
if (isset($_POST['logout'])) {
$_SESSION['session'] = "ANONYMOUS";
}
//Detect session
if ($session[1] != $rid && $session[0] != $uname ) {
//Check value of text field
if ($_POST['txtUsername'] != $uname || $_POST['txtPassword'] != $pass) { ?>
*LOGIN FORM*
<?php
}
}
else {
$_SESSION['session'] = $uname.".".$rid;
?>
*PROTECTED HTML*
<?php
}
?>
Rob Oplawar
January 21st, 2010, 07:21 PM
First,
$session = $_SESSION['session'];
When you have something like this, it's time to rename your variables.
Second, the line labeled "Restart Session" should appear before your "Check if Session Exists"; otherwise the server will track them as logged out but then go ahead and display the protected page when it gets to "Detect Session" because $session is already defined.
Third, where are $rid, $uname, and $pass set? I assume in getData.php... generally it is frowned upon to use globals like that (for this exact reason- people don't know where they come from or what their values might be)
Fourth, let's take a look at that in pseudocode
//Check if session exists
assign $sections from SESSION
//Restart session
if POST['logout']
reset sections in SESSION
//Detect session
if $section does not match $rid and $uname
if POST does not match $uname and $pass
display login form
[else do nothing]
else
assign sections in SESSION from $rid and $uname
display protected page
Try to mentally trace your program logic. Once you enter a "then" block, ignore all the other "then" blocks associated with those "if"s and "else"s. If you don't enter any of the "then"s for a whole "if/then/else" block, keep going, and note what happens after that block. (I'm specifically looking at the "do nothing" that appears in the pseudocode)
Does that make sense, or am I speaking gibberish?
Hunter
January 22nd, 2010, 01:21 PM
Makes sense, but it is all working now. Forgot to post here, cheers though :) Having a JavaScript problem now. I have never had to recode anything to work in firefox before, but I need to now :/
The below JavaScript works fine in InternetShizen, but not in Firefox... any idea why?
<script type="text/javascript">
//Check field values on load
window.onload=function(){
validateNow('txtUsername','3', 'usernameCheck', 'submit');
validateNow('txtPassword','3', 'passwordCheck', 'submit');
}
//Global variables
var elem = document.getElementById;
//Check if fields have defined amount of characters
function validateNow(id, num, id2, button)
{
if (elem(id).value.length < num) {
elem(id2).value="Empty!";
elem(id2).style.color="#CC3300";
var complete = nope;
}
else {
elem(id2).value="OK!";
elem(id2).style.color="#009900";
var complete = yup;
}
}
// Set all fields to NULL
function restartForm()
{
document.form.txtUsername.value= "";
document.form.txtPassword.value= "";
validateNow('txtUsername','3', 'usernameCheck', 'submit');
validateNow('txtPassword','3', 'passwordCheck', 'submit');
}
// Detect if fields complete and activate button
function debutton(elemID1, elemID2, num, buttonID) {
if (complete == yup) {
elem(buttonID).disabled=false;
else {
elem(buttonID).disabled=true;
}
}
</script>
I wrote it at college so I only had IE. (The validateNow() function is the one with the problem btw. )
Edit: The debutton() function is also being a prick and stopping the other functions from working, which means the function is not actually functioning properly. Updated code with that function as well. (That is not the cause of the first problem.)
Rob Oplawar
January 22nd, 2010, 02:54 PM
Added comments in green
<script type="text/javascript">
//iirc, window.onload doesn't work in Firefox. It's document.load or something like that... I
//can't remember, because I use prototype, so it's always document.listen('load') or some such. Search
//on this and you'll probably find your problem.
window.onload=function(){
validateNow('txtUsername','3', 'usernameCheck', 'submit');
validateNow('txtPassword','3', 'passwordCheck', 'submit');
}
//the convention established by prototype is to name this function "$", but I don't see that
//being any better than your convention. just thought I'd mention it
var elem = document.getElementById;
function validateNow(id, num, id2, button)
{
if (elem(id).value.length < num) {
elem(id2).value="Empty!";
elem(id2).style.color="#CC3300";
//poor practice in multiple ways. first, by using the var keyword here, you're
//specifying that the scope of complete is just within this function, so debutton won't necessarily
//be able to get this value
//second, you should assign it to true or false, if anything. right now you're assigning
//it to the value of the variable "nope", which is undefined. if you want you can put quotes around
//nope to make it a string, ie, var complete = "nope";
var complete = nope;
}
else {
elem(id2).value="OK!";
elem(id2).style.color="#009900";
var complete = yup;
}
}
// Set all fields to NULL
function restartForm()
{
document.form.txtUsername.value= "";
document.form.txtPassword.value= "";
validateNow('txtUsername','3', 'usernameCheck', 'submit');
validateNow('txtPassword','3', 'passwordCheck', 'submit');
}
// Detect if fields complete and activate button
function debutton(elemID1, elemID2, num, buttonID) {
if (complete == yup) {
elem(buttonID).disabled=false;
else {
elem(buttonID).disabled=true;
}
}
</script>
Hunter
January 22nd, 2010, 05:29 PM
Eh, can't get it working.
*Deletes code.
Only little add-on anyway, its nothing that is needed. (The button thing that is, still working on the validation type thing).
Edit:
Code now works in FireFox. Just removed the variable... but one thing I do not understand is:
The input field which is called txtPassword did NOT have an id before, when it was working... just give it the id which the JavaScript was using... So how the fuck was it working before :S
Code as of now if you are interested:
function validateNow(id, num, id2)
{
if (document.getElementById(id).value.length < num) {
document.getElementById(id2).value="Empty!";
document.getElementById(id2).style.color="#CC3300";
}
else {
document.getElementById(id2).value="OK!";
document.getElementById(id2).style.color="#009900";
}
}
Rob Oplawar
January 22nd, 2010, 07:16 PM
:iiam:
By the way, I hope you know not to rely on Javascript for validation- if your PHP script needs input formatted a certain way, make sure it checks for that, because you can never count on your users to behave.
Also, I suggest looking into the Prototype Javascript framework. It would make a lot of the things you seem to want to do here easier and cleaner (although there is the overhead of including the prototype.js file along with your custom Javascript, and prototype is a few thousand lines long).
Hunter
January 22nd, 2010, 08:13 PM
That JavaScript is just to dynamically tell the user if he/she has typed enough characters, so they know they have to type something. It doesn't actually validate the form itself.
I don't really want to use JavaScript to validate the form as the user may have it disabled, that's why all my forms are validated server side with PHP.
And I like to do everything my self, although sometimes that isn't possible. Still accept help of course otherwise I would be stuck Lol. I fell like I have achieved more if I code it all. I won't get as high standards as I would if I used a professional piece of code, but I don't mind :)
That is why I hate ripping, because I prefer to do everything my self.
Another problem:
The data is not being pulled in from the table, I have had to remove the "while" which most people use so that I cna use the variables when the submitPass button is pressed. Is the while needed?
<?php
include "scripts/php/db.connect.php";
//Get data...
$result = mysql_query("SELECT * from users WHERE rid='$srid'") or die ('Error: '.mysql_error());
$row = mysql_fetch_array($result);
//Variables
$username=$row["username"];
$fname=$row["fname"];
$lname=$row["lname"];
$email=$row["email"];
$pass=$row["password"];
?>
</p></div>
<div class="container">
<a href="scripts/php/logout.php" style="float:right;">-Logout-</a>
<?php include "includes/menu.php"; ?>
<h1>User Control Panel</h1>
<h2>Account Information: </h2>
<?php
//Display Data
echo "Username: $username <br />First Name: $fname<br />Last Name: $lname<br />Email: $email<br />";
?>
Rob Oplawar
January 23rd, 2010, 11:02 AM
I don't really want to use JavaScript to validate the form as the user may have it disabled, that's why all my forms are validated server side with PHP.
cool
And I like to do everything my self, although sometimes that isn't possible. Still accept help of course otherwise I would be stuck Lol. I fell like I have achieved more if I code it all. I won't get as high standards as I would if I used a professional piece of code, but I don't mind :)
That is why I hate ripping, because I prefer to do everything my self.
I Know exactly what you mean- that's why I'm building Greeble while Drupal is staring me in the face. I just want to point out that using a framework is far from ripping- it's no different than using the mysql extension in PHP. You wouldn't want to implement all the socket communication yourself, would you? At a certain point it's good to want to implement something yourself for the experience, though. The reason I recommend using Prototype is because Javascript is so fucking finicky on so many different browsers that I don't see the benefit in working all that shit out for a complex piece of code. Prototype is cross-browser; it encapsulates just about all the complex things you want to do and makes them work on every modern browser without you having to worry about it at all.
Another problem:
The data is not being pulled in from the table, I have had to remove the "while" which most people use so that I cna use the variables when the submitPass button is pressed. Is the while needed?
Think about what the while loop does. It executes the test expression, which is setting $row to the return value of mysql_fetch_array, and if that doesn't evaluate to false, it executes the inner part, then goes back, effectively checking if there are any more results. If you expect to have exactly one result, then no, the while is not needed. You should however check for zero results, which is rather likely with that sort of query.
As for your problem: your query is probably returning results, but you can't get at them, because mysql_fetch_array returns something like this:
array(0=>'my_username', 1=>'my_first_name', 2=>'my_last_name', 3=>'me@example.com', 4=>'my_password')
If you were to use mysql_fetch_assoc instead, you would get what you're expecting to get here:
array('username'=>'my_username', 'fname'=>'my_first_name', 'lname'=>'my_last_name', 'email'=>'me@example.com', 'password'=>'my_password')
e: Just keep in mind, 'array' by itself more often refers to an enumerated array (values accessed by integers) and 'assoc' always refers to an associative array (values accessed by keys which are usually strings). In PHP all arrays are technically associative arrays, but by default the keys used are integers to make it look like the traditional c/c++ idea of an array, which stores all your data points next to each other in memory so you simply specify integer i to get the ith value in that sequence.
hth
Hunter
January 23rd, 2010, 06:47 PM
Cheers for the information :)
All I needed to do is move the $rid variable above the code which pulls in the database data, as the rid (Random ID) is used to select the data lmao.
Another problem:
I want this script to change BOTH values if it detects values added in both fields. But if not, then it will just change the value in the database of which ever field has data in.
<?php
if ($_POST['fName'] && $_POST['lName'] != "") {
echo "Got here";
//Add BOTH
$nfname = mysql_real_escape_string($_POST['fName']);
$nlname = mysql_real_escape_string($_POST['lName']);
$query = "UPDATE users SET fname='$nfname' lname='$nlname' WHERE rid=$srid";
$result = mysql_query ($query);
if (!$result) {
echo "$resErr Error updating first name and last name!";
}
else {
echo "$resSucc Successfully updated last and second name!";
}
}
elseif ($_POST['fName'] != "") && $_POST['lName'] == "") {
//Add first name only
$nfname = mysql_real_escape_string($_POST['fName']);
$query = "UPDATE users SET fname='$nfname' WHERE rid=$srid";
$result = mysql_query ($query);
if (!$result) { echo "$resErr Error updating first name!"; }
else { echo "$resSucc Successfully updated first name!"; }
}
elseif {
//Add last name only
$nlname = mysql_real_escape_string($_POST['lName']);
$query = "UPDATE users SET lname='$nlname' WHERE rid=$srid";
$result = mysql_query ($query);
if (!$result) { echo "$resErr Error updating last name!"; }
else { echo "$resSucc Successfully updated last name!"; }
}
}
else {
echo "Damn";
}
?>
Only problem I am getting at the moment is:
Parse error: syntax error, unexpected T_BOOLEAN_AND in /home/martynba/public_html/stokeGTA/ucp/changeName.php on line 16
But I so no problem :S
Rob Oplawar
January 23rd, 2010, 08:42 PM
line 16
elseif ($_POST['fName'] != "") && $_POST['lName'] == "") {
has an extra (or alternatively, a missing) parenthesis.
should be:
elseif ($_POST['fName'] != "" && $_POST['lName'] == "") {
Powered by vBulletin® Version 4.2.5 Copyright © 2025 vBulletin Solutions Inc. All rights reserved.