I wonder whether someone can help me please.
I'm trying to put together a form and PHP script (below) which allows an administrator to search and update member details via the email address, populating a second email address, forename and surname fields with the retrieved information ready for them to be amended.
<?php
mysql_connect ("hostname","username","password") or die (mysql_error());
mysql_select_db ("databasename");
if ($_POST['search'])
{
$searchemailaddress = $_POST['searchemailaddress'];
$sql = mysql_query("select * from userdetails where emailaddress like '$searchemailaddress'");
while ($row = mysql_fetch_array($sql))
{
$emailaddress = $_POST['emailaddress'];
$forename = $row['forename'];
$surname = $row['surname'];
}
elseif ($_POST[['update'])
{
$userid = $_POST['userid'];
$emailaddress = $_POST['emailaddress'];
$forename = $_POST['forename'];
$surname = $_POST['surname'];
//replace TestTable with the name of your table
$sql = ("UPDATE `userdetails` SET `emailaddress` = '$emailaddress', `forename` = '$forename',`surname` = '$surname' WHERE `userdetails`.`userid` = '$userid' LIMIT 1");
}
}
}
?>
I'm receiving the following error:
Parse error: syntax error, unexpected T_ELSEIF in /homepages/2/d333603417/htdocs/development/searchandamend.php on line 13
with line 13 being this line in my script. elseif ($_POST[['update'])
Could someone perhaps take a look at this please and let me know where I'm going wrong.
Many thanks
The line
$surname = $row['surname'];}
should have another } afterwards. The one you have only closes the while loop. You also may want to consider using some indentation - that really helps seeing errors like this one.
Also, the error basically says it all - the else if appears unexpectedly there, so the PHP processor expects something else (in this case a closing brace).
As was mentioned in a comment to your answer your closing } are improperly placed and it appears you have too many of them.
if
{
// stuff here
}
elseif
{
// other stuff here
}
As was also mentioned in a previous answer if you properly format your code, similar to how it appears in the edited question, you will have a much easier time finding errors like this.
I also feel obliged to point you to the PHP documentation on choosing the correct MySQL API as the extension you are using is outdated and is not recommended for new project use.
Related
I am having an issue echoing or printing from my PHP to my HTML. I am sure I am missing something basic with how PHP works, however I have been unable to find anything about this issue on the internet or on here. I am very confused, because I am not receiving an errors or any context to the problem at all. The rest of my code works fine, except for echo.
I normally use echo() for testing to ensure stuff exists, however this issue has plagued me during the entire development of this application. It only now bothers me because I will need to echo out a script to load in data (Which I will hide after the load using Vue).
This issue oddly enough only has happened inside of areas where I am using if to do things, especially when it has array_key_exists.
If anyone could help I would appreciate it (Or if someone could provide a better idea for me to transfer json data from PHP to JavaScript other than having to echo it out, since that opens a weak spot in my code for users to cheat my clicker game).
I have tried to test this in other parts of my code with the same results. I cannot use echo() or print() within any if statement. I can use it elsewhere however.
All of my PHP files end up inside of my index.php by usage of require
<?php
if (array_key_exists("saveData", $_POST)) {
$saveData = $_POST['saveData'];
$token = $_COOKIE['validToken'];
$token = mysqli_real_escape_string($link, $token);
$query = "UPDATE userData SET saveData = '$saveData' WHERE token = '$token' LIMIT 1";
mysqli_query($link, $query);
}
if (array_key_exists("logSubmit", $_POST)) {
$email = $_POST["logEmail"];
$email = filter_var($email, FILTER_SANITIZE_EMAIL); // Clean Email
$email = filter_var($email, FILTER_VALIDATE_EMAIL); // Confirm Valid Email
$query = "SELECT saveData FROM userData WHERE email = '$email' LIMIT 1";
$loadData = mysqli_query($link, $query);
echo("SALO Ready!");
}
?>
I would expect for this to echo out "SALO Ready" however I get nothing instead.
EDIT: PHP's white screen of death does not work or apply. Everything else in my application works as expected
UPDATE #1: I have done some testing as recommended, and found that when I echo out of my if statements, one of two things happen
1) The echo() fires, and in the preview under Network on Chrome you can see it their however it does not display in the DOM. This is the case for any if statement that does not meet the below situation.
2) If the echo() is fired from a block used for registering or logging in, it will not display in the preview either. I will be restructuring my code to have those be functions called by the forms when submitted, instead of them just being conditional blocks. While this code is not included in this question, the initial login runs the code below as well to load up user data.
UPDATE #2: I have consolidated my code and followed some recommendations. My code is now inside of functions, that are fired by some if isset conditions. This actually PARTLY fixed my issue. I can echo from all of my functions (Register, Login, Save, Load). Now my issue would appear to be a comment below in relations to output buffering. While my initial question is (Mostly) solved, would anyone be able to help explain how to solve this? I only have ob_start() right now, followed by my functions, if isset conditions, and then everything else in my application. How can I get the echo go to them DOM? I will include the chunk of my code below that will absolutely need to echo out down the road.
EDIT: I have changed how I have ob_start() setup within my code. I call it in the functions that need it and then flush it afterwards. I will be testing with my load script later tonight to try to force the echo() out of the function. Genuinely confused as to why it had not worked in functions but works outside of them, even before this edit
function load() {
$link = // Link Excluded for Security ;
if (mysqli_connect_error()) {
die ("DB Connection Error");
}
$email = $_POST["logEmail"];
$email = filter_var($email, FILTER_SANITIZE_EMAIL); // Clean Email
$email = filter_var($email, FILTER_VALIDATE_EMAIL); // Confirm Valid Email
$query = "SELECT saveData FROM userData WHERE email = '$email' LIMIT 1";
$loadData = mysqli_query($link, $query);
mysqli_close($link);
echo("Loading Triggered!");
}
if(isset($_POST['logSubmit'])) {
login();
load();
}
As mentioned, this shows the echo() inside of the network tab when I click on primary.php and click preview, it just isn't going to the DOM
Just use keep your code inside a function and call the function name while post your input
Ex:
function yourFunctionName(){
if (array_key_exists("saveData", $_POST)) {
$saveData = $_POST['saveData'];
$token = $_COOKIE['validToken'];
$token = mysqli_real_escape_string($link, $token);
$query = "UPDATE userData SET saveData = '$saveData' WHERE token = '$token' LIMIT 1";
mysqli_query($link, $query);
}
if (array_key_exists("logSubmit", $_POST)) {
$email = $_POST["logEmail"];
$email = filter_var($email, FILTER_SANITIZE_EMAIL); // Clean Email
$email = filter_var($email, FILTER_VALIDATE_EMAIL); // Confirm Valid Email
$query = "SELECT saveData FROM userData WHERE email = '$email' LIMIT 1";
$loadData = mysqli_query($link, $query);
echo("SALO Ready!");
}
}
There is a way to output contents to the DOM when using ob_start by using ob_flush();
ob_start(), when called stores all outputs buffer until instructed to be sent to the browser.
See:
What is Output Buffering?
(The suggested solution provides a re usable function to empty the buffer, sending contents to browser)
How to flush output after echo call
This register form was made by me, but it doesn't do what I want it to do.
I want it to connect to a mysql database and store the information that was given by the form. I want it to hash the $password in md5 and store it in the "gebruikers" table. Please don't reply with "Damn, you have no idea what you are doing" or something like that. I am learning PHP by looking to examples and following tutorials. Please keep in mind that the mysql insert code is not filled in right, because I got stuck a few lines above.
So, my question is: I want to check if the mysql table already contains $email. If it IS already in the mysql table, I want to display an error message that I can place somewhere else in my PHP page. If the email adress given is unique, than the $password should hash into md5 and store into the mysql database, just like the other form entries.
How do I do that?
<?php
// Fetching all the form details
$email = $_POST["email"];
$password = $_POST["password"];
$voornaam = $_POST["voornaam"];
$tussenvoegsel = $_POST["tussenvoegsel"];
$achternaam = $_POST["achternaam"];
$dag = $_POST["dag"];
$maand = $_POST["maand"];
$jaar = $_POST["voornaam"];
$straat = $_POST["straat"];
$postcode = $_POST["postcode"];
$woonplaats = $_POST["woonplaats"];
$cniveau = $_POST["cniveau"];
$oniveau = $_POST["oniveau"];
$voornaam = $_POST["voornaam"];
$aboutme = $_POST["aboutme"];
//Here's where I don't know how to continue
$check = mysql_query("SELECT * FROM `gebruikers` WHERE `email` = '$email'");
if($check === FALSE) {
//there is a user already registered
echo("$email is al in gebruik. <a href='login.php'>Inloggen</a>?");
} else {
//There isn't a username
//mysql_query("INSERT INTO `user` (`id` ,`username` ,`password`) VALUES (NULL , '{$_POST['email']}', MD5( '{$_POST['password']}' ))");
echo("You have been registered!");
}
P.S.: I'm not a native English speaker, so please ignore my grammar mistakes/typos.
First of all, you made a major mistake: There is a SQL-Injection security hole.
Please read this: http://php.net/manual/en/security.database.sql-injection.php
Second, you should use mysqli instead of mysql, because mysql is deprecated.
Your error is that SQL does only return false if the query is invalid, not if there are no results. So the correct way of checking if there are results is to use http://php.net/manual/en/mysqli-result.num-rows.php
$result = mysql_query("SELECT * FROM `gebruikers` WHERE `email` = '$email' LIMIT 1");
if(mysql_fetch_array($result) !== false)
{
...
} else {
....
}
You should also read up on preventing SQL injection.
Maybe you've forgot to set the mysql_connect statement.
But I strongly recommend you stick from now on, with the mysqli_ functionality, since, as Aragon0 said, mysql is deprecated in PHP's newest versions.
Besides, mysqli statements are simpler than the mysql ones, for example you use one statement (mysqli_connect) to connect to your host and select your database at the same time, instead of using separated statements (both mysql_connect and mysql_select_db).
Oh, and no additional service package is required to use it. :)
There are not really and direct answers on this, so I thought i'd give it a go.
$myid = $_POST['id'];
//Select the post from the database according to the id.
$query = mysql_query("SELECT * FROM repairs WHERE id = " .$myid . " AND name = '' AND email = '' AND address1 = '' AND postcode = '';") or die(header('Location: 404.php'));
The above code is supposed to set the variable $myid as the posted content of id, the variable is then used in an SQL WHERE clause to fetch data from a database according to the submitted id. Forgetting the potential SQL injects (I will fix them later) why exactly does this not work?
Okay here is the full code from my test of it:
<?php
//This includes the variables, adjusted within the 'config.php file' and the functions from the 'functions.php' - the config variables are adjusted prior to anything else.
require('configs/config.php');
require('configs/functions.php');
//Check to see if the form has been submited, if it has we continue with the script.
if(isset($_POST['confirmation']) and $_POST['confirmation']=='true')
{
//Slashes are removed, depending on configuration.
if(get_magic_quotes_gpc())
{
$_POST['model'] = stripslashes($_POST['model']);
$_POST['problem'] = stripslashes($_POST['problem']);
$_POST['info'] = stripslashes($_POST['info']);
}
//Create the future ID of the post - obviously this will create and give the id of the post, it is generated in numerical order.
$maxid = mysql_fetch_array(mysql_query('select max(id) as id from repairs'));
$id = intval($maxid['id'])+1;
//Here the variables are protected using PHP and the input fields are also limited, where applicable.
$model = mysql_escape_string(substr($_POST['model'],0,9));
$problem = mysql_escape_string(substr($_POST['problem'],0,255));
$info = mysql_escape_string(substr($_POST['info'],0,6000));
//The post information is submitted into the database, the admin is then forwarded to the page for the new post. Else a warning is displayed and the admin is forwarded back to the new post page.
if(mysql_query("insert into repairs (id, model, problem, info) values ('$_POST[id]', '$_POST[model]', '$_POST[version]', '$_POST[info]')"))
{
?>
<?php
$myid = $_POST['id'];
//Select the post from the database according to the id.
$query = mysql_query("SELECT * FROM repairs WHERE id=" .$myid . " AND name = '' AND email = '' AND address1 = '' AND postcode = '';") or die(header('Location: 404.php'));
//This re-directs to an error page the user preventing them from viewing the page if there are no rows with data equal to the query.
if( mysql_num_rows($query) < 1 )
{
header('Location: 404.php');
exit;
}
//Assign variable names to each column in the database.
while($row = mysql_fetch_array($query))
{
$model = $row['model'];
$problem = $row['problem'];
}
//Select the post from the database according to the id.
$query2 = mysql_query('SELECT * FROM devices WHERE version = "'.$model.'" AND issue = "'.$problem.'";') or die(header('Location: 404.php'));
//This re-directs to an error page the user preventing them from viewing the page if there are no rows with data equal to the query.
if( mysql_num_rows($query2) < 1 )
{
header('Location: 404.php');
exit;
}
//Assign variable names to each column in the database.
while($row2 = mysql_fetch_array($query2))
{
$price = $row2['price'];
$device = $row2['device'];
$image = $row2['image'];
}
?>
<?php echo $id; ?>
<?php echo $model; ?>
<?php echo $problem; ?>
<?php echo $price; ?>
<?php echo $device; ?>
<?php echo $image; ?>
<?
}
else
{
echo '<meta http-equiv="refresh" content="2; URL=iphone.php"><div id="confirms" style="text-align:center;">Oops! An error occurred while submitting the post! Try again…</div></br>';
}
}
?>
What data type is id in your table? You maybe need to surround it in single quotes.
$query = msql_query("SELECT * FROM repairs WHERE id = '$myid' AND...")
Edit: Also you do not need to use concatenation with a double-quoted string.
Check the value of $myid and the entire dynamically created SQL string to make sure it contains what you think it contains.
It's likely that your problem arises from the use of empty-string comparisons for columns that probably contain NULL values. Try name IS NULL and so on for all the empty strings.
The only reason $myid would be empty, is if it's not being sent by the browser. Make sure your form action is set to POST. You can verify there are values in $_POST with the following:
print_r($_POST);
And, echo out your query to make sure it's what you expect it to be. Try running it manually via PHPMyAdmin or MySQL Workbench.
Using $something = mysql_real_escape_string($POST['something']);
Does not only prevent SQL-injection, it also prevents syntax errors due to people entering data like:
name = O'Reilly <<-- query will bomb with an error
memo = Chairman said: "welcome"
etc.
So in order to have a valid and working application it really is indispensible.
The argument of "I'll fix it later" has a few logical flaws:
It is slower to fix stuff later, you will spend more time overall because you need to revisit old code.
You will get unneeded bug reports in testing due to the functional errors mentioned above.
I'll do it later thingies tend to never happen.
Security is not optional, it is essential.
What happens if you get fulled off the project and someone else has to take over, (s)he will not know about your outstanding issues.
If you do something, finish it, don't leave al sorts of issues outstanding.
If I were your boss and did a code review on that code, you would be fired on the spot.
I'm try to get cookies on to a browser. It's giving me parameter 1 error and parameter 3. This code works elsewhere on my site but not here. Can someone help me?
if ((!isset($_POST["uname"])) || (!isset($_POST["password"])))
{
header ("Location: wddnt/clients/'. $tattoo_extern_acct . '/index.html");
exit;
}
$userpass = md5($_POST['password']);
#$db = mysqli_connect("$dbc_ser", "$dbc_usr", "$dbc_pwd", "$dbc_db");
$sql = "SELECT id, name, company, job_title, cell_num, office_num, office_email,
login_right, first_run, attempts, locked_out FROM login
WHERE email = '".$_POST["email"]."'
AND password = PASSWORD('$userpass')";
if (mysqli_connect_errno())
{
echo 'Cannot connect to database: ' . mysqli_connect_error();
}
else
{
$result = mysqli_query($db, $sql);
while ($info = mysqli_fetch_array($result))
{
$id = stripslashes($info['id_files']);
$u_acct = stripslashes($info['uname']);
$name = stripslashes($info['name']);
$job_title = stripslashes($info['job_title']);
$location = stripslashes($info['company']);
$cell_num = stripslashes($info['cell_num']);
$office_num = stripslashes($info['office_num']);
$office_email = stripslashes($info['office_email']);
$login_right = stripslashes($info['login_right']);
$first_run = stripslashes($info['first_run']);
$attempts = stripslashes($info['attempts']);
$locked_out = stripslashes($info['locked_out']);
$land_page = stripslashes($info['land_page']);
}
}
Try debugging some of the individual variables. What is in $sql, for example? Is it correct?
Is the "Cannot connect" clause executed, or does it get to the query and fail there? (I am not sure what "parameter 1 error and parameter 3" means).
Don't forget to escape the 'email' value by the way - this code has an SQL injection hole.
header ("Location: wddnt/clients/'. $tattoo_extern_acct . '/index.html");
This is not going to work the way you expect.
$sql = "SELECT id, name, company, job_title, cell_num, office_num, office_email,
login_right, first_run, attempts, locked_out FROM login
WHERE email = '".$_POST["email"]."'
You need to read up on SQL injection.
while ($info = mysqli_fetch_array($result))
You allow multiple accounts with the same email address / password?????
It's giving me parameter 1 error and parameter 3
Couldn't you post the actual error message you get?
$id = stripslashes($info['id_files']);
WTF? Smartquotes?
I'm not sure i understand your question but the last time i checked anyone who wants to use cookies uses the $_COOKIE global variable, either for setting them or accessing them. $_POST is made to get stuffs from forms, not cookies.
Please check the manual for more details about $_COOKIE
Regards
I am validating a form (checking if field are empty etc and at the end I am using my last validation rule:
//Database Information
//Connect to database
mysql_connect($dbhost, $dbuser, $dbpass)or die("Could not connect: ".mysql_error());
mysql_select_db($dbname)or die(mysql_error());
$email = mysql_real_escape_string($_POST['email']);
$cust_code = mysql_real_escape_string($_POST['cust_code']);
//validation e.g.
if (empty($email) + empty($cust_code) > 1){
....
//if everything is ok
$sql = "SELECT * FROM clients WHERE ID='$cust_code'";
$result = mysql_query($sql);
if(mysql_num_rows($result) > 0){
$data = mysql_num_rows($result);
//get all fields from db and do something
}else{
//My error that is showing up
echo "<span class=\"difftext\">The customer code you have entered is not valid!
<br />
Please enter a valid Customer Code to procceed!
</span>";
Is anything wrong with that because even if I enter the correct cust_code I am getting my error msg instead of my data...
Thank you
EDIT...(I removed, as it is wrong) AND YOU DID WELL... I JUST REALISE WHAT I DID... SORRY...
I have corrected it above.
Thank you
HOW TO DEBUG
Do not put the query string immediately into the mysql method, echo it first
$sql = "SELECT * FROM clients WHERE ID='$cust_code'";
echo $sql;
$res=mysql_query($sql);
Are you even connected to the DB?
Error messages are written in English (if it is not MS error messages). Why would you ignore them? Put the error message, read it, try to understand what it says.
An advice, if you will write code that way, it is ok for very small application, for big ones, you need to take a different approach completely to code organization. Which is one of the problems/main problem frameworks are trying to solve for you.
Actually, you are wrong, your error is here, in this two lines:
$sql = mysql_query("SELECT * FROM clients WHERE ID='$cust_code'");
$result = mysql_query($sql);
You are running the query twice.
After the first time $sql holds the resource, then you refer to the resource as if it was a query string. To fix it, change it to:
$sql = "SELECT * FROM clients WHERE ID='$cust_code'";
$result = mysql_query($sql);
You might have more underlying errors, but fix this one first.