I have searched a lot but can't find my solution. I am new to php so I hope I can explain my question clearly.
I am trying to build a system that allows the user to update his/her information.
There are some inputs in the form which are; username, email, old-new password...
What I want to achieve is updating only the changed inputs. (blank inputs will be ignored)
So I want the username input to be checked if it is blank and keep the process working regardless of the result if username is blank or not.
By that way ı can update the table with only changed/typed inputs.
How can I achieve that?
if($username != "") {
//update the username
}
// keep process going even if username condition is true.
if($email != "") {
// update the email
}
PS: I didn't write the whole codes because there are at least 10 inputs and 3 selects. I tried lots of nested if,elseif,else statements so the codes I tried is so complicated and long.
I just wonder If there is a way to keep the process going after an "if statement" even if the condition is true.
UPDATE
I tried using just ifs, I was expecting the process will be continue but, for example;if I left blank the username and type the email, it updates the email.But if username input was typed and the email was typed; it just updates the username.
What could be the problem ?
If all the data is updated on a single table say users, then you can generate the update command on the fly using the input data and finally execute the query as
<?php
$qry_update = "UPDATE `users` SET " ;
if($username != ""){
$qry_update .= "`username` = '$username', ";
}
if($email != ""){
$qry_update .= "`email` = '$email', ";
}
....
....
$qry_update = rtrim($qry_update, ',');
$qry = $qry_update." where idusers = $idusers ";
// Execute the query
?>
The above is conventional way of doing it. But its better to use PDO with bind params.
In PHP, the code outside your if statement will be executed.
The example you provided will check both if statements, and execute the code within if your statement is true.
So have you tried the following?
if (!empty($username)) {
// Do something to username
}
// Code here will still execute
So here the if statement will run if it is true otherwise it will just skip it.
elseif will have to go after an if and catches a next scenario, but if they need to be run all then don't use elseif
if ($condition) {
// code to run if statement passes
} elseif ($condition) {
// only checks the condition if the first if is not run
} else {
// has no condition but only runs if all above does fail to run
}
// Code here will still run as long as the above does not cancel the script. As Fatals, exit() die() return etc.
Related
i Just want code for if veriable $absolute_url value is already exist in mysql then show me a message i just want this Thank you..
$_SESSION['varname'] = $absolute_url;
$mailingwork = mysql_connect("localhost","root","");
mysql_select_db("inbox",$mailingwork);
if(isset($absolute_url) && !empty($absolute_url))
{
mysql_query("Insert Into deliveredinbox(mailerss) value('$absolute_url')");
}
I think you just want to check if the $absolute_url already exists in the deliveredinbox table. If so, you can do a select query as follows to count the number of rows where the absolute url is equal to the url that you want to enter to the table.
if(isset($absolute_url) && !empty($absolute_url)){
$count=mysql_query("SELECT count(*) from deliveredinbox where mailerss='$absolute_url'");
mysqli_fetch_array($count);
if($count[0]>0){
//already exists
echo "The url already exists";
}
else{
mysql_query("Insert Into deliveredinbox(mailerss) value('$absolute_url')");
}
}
Try if (isset($absolute_url)) { your code here; }. It's not precisely the right tool, but I think that it will do the trick for you.
http://php.net/manual/en/function.isset.php.
Others are absolutely right about transitioning from old mysql calls in PHP. mysqli calls are more secure. PDO will save you time in coding and are even more secure.
UPDATE - I finally figured this out, and I've added the answer below :-) (I'll accept it as answered as soon as the system allows me to)
I think that I'm probably doing something very simple incorrectly (i.e. calling the variable incorrectly), as I've had similar issues in several situations.
I am creating a password reset form and would like to include the various steps and form sections on one page. I'm doing this using a series of elseif statements to determine which html code to display and/or php script to execute, and changing the value of the variable as a series of queries succeed or fail.
I've tested the queries and the var value changes correctly (I've echo'd the value at each step to confirm that) but the correct result isn't being displayed unless the var value is set manually.
For purposes of the question I've included 2 simplified snippets - a very basic scenario (which I can easily apply to my code), and a simplified version of my code, and I'd be happy to share the full code if that's preferable.
EDIT - I've also tried calling GLOBAL $status; before setting a new value for $status, on the off-chance that was the problem.
Basic Scenario:
<?php
//session_start and connect to database
$status="start";
?>
<?php $status="start"; ?>
<?php if ($status == "start") { ?>
Check if expiry valid & retrieve info
<?php $status = "expiry_ok"; ?>
<?php }
elseif ($status == "expiry_ok")
{ ?>
Date is Valid
<?php } ?>
Simplified Version of Query:
<?php if ($status == "start"){
//Identify the $temp_password by removing the URL
$restorepasslink="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
$new_pass = str_replace("http://click2fit.com/demo/restorepass.php/", "", $restorepasslink);
//Query db to check if expiry_date has passed
$qry="SELECT * FROM password_reset WHERE temp_password = '$new_pass'";
$result=mysql_query($qry);
if($result) {
$token = mysql_fetch_assoc($result);
$token_expiry_date = $token['expiry_date'];
// Other $token values are also set here
if($date < $token_expiry_date) {
$status = "expiry_ok";
}else {
$status = "expiry_notok";
}
}
?>
Note: Since most of the tutorial are still written for mysql queries instead of PDO, I'm first trying to get it all to work that way before switching it over to PDO.
I solved the problem by removing the initial if statement:
if ($status == "start"){...}
and simply starting the elseif statements with
if ($status == "expiry_ok"){...}
elseif (...)
I also removed the initial declaration of the $status="start";
$query = "SELECT username, email
FROM members
WHERE username = :username OR email = :email";
$stmt = $sql->prepare($query);
$stmt->execute(array(
':username' => $_POST['username'],
':email' => $email
));
$existing = $stmt->fetchObject();
if ($existing)
{
if ($existing->username == $_POST['username'])
{
$errors['username'] = "Username already in use !";
}
if ($existing->email == $email)
{
$errors['email'] = "Mail already in use !";
}
}
This is the part of register.php file. Not sure that just this part is responsible for the problem, but I suppose.
So, if table members is empty, and form is submitted - Firefox shows it's busy-gif about a half minute, but ends without registering new user, and without showing any error. Just keep freezing.
Then i press F5 - a window to approve resend information appears - click Resend - and the new user is registered.
If the tablemembersis not empty - everything works normally.
It seems - problem is because the code above is busy to find non-existing data.
If so, how to tell something like - if the table is empty - stop trying - just register the new user.
I'm pretty sure $existing = $stmt->fetchObject(); is fetching you an empty object, but one that does not implicitly evaluate to false. After that there's nothing in your code that would trigger, leading to your blank output.
Try a var_dump($existing) to see what your code is actually operating on.
edit
$existing = $stmt->fetchObject(); //this might be returning an empty object
if ($existing) { //empty objects evaluate to true
if ($existing->username == $_POST['username']) {
$errors['username'] = "Username already in use !";
} else if ($existing->email == $email) {
$errors['email'] = "Mail already in use !";
} else {
//this will trigger if something ELSE is wrong other than what you're explicitly checking for.
$errors['other'] = "Something else is wrong.\n" . var_export($existing, TRUE);
}
}
It should be noted that it is generally a bad idea from a security standpoint to confirm to a would-be attacker that a username or email address exists in your system. This presumably would give them half of the information needed to execute a dictionary attack on your login.
I would make the the username and email fields in your table have unique indexes, and just go straight to the insert. If the insert fails because one of the uniqueness constraints doesn't allow it, just give the user a generic message about not being able to register.
This will also happen to save you a lot of unnecessary queries against the database.
Should $email be $_POST['email']? And what is the full code - you don't have a closing if brace here. In that case, everything after would only execute if $existing is true. So the first time, nothing would be displayed. Also, it's better to use database constraints to ensure no duplicates like MySQL - Meaning of "PRIMARY KEY", "UNIQUE KEY" and "KEY" when used together while creating a table
I'm having a problem with the a mysqli query I'm calling from a php script. I've rewritten it many times and keep getting the error: "mysqli num_rows Commands out of sync; you can't run this command now" This is the first attempt to access the database from this page. I was previously binding the parameters and then calling: $checkAcct->num_rows() and getting the same problem. I also tried what someone suggested in a different post on this site:
do { $checkAcct->use_result(); } while( $checkAcct->next_result() );
but this didn't work either and I got the same error. After I make sure a user with these details isn't in the db I execute another query to insert the user's info into the site but the error message I get pertains to this query here. Let me know if it would help to see the other query also.
Below is the code I'm trying to use:
$checkAcct = $dbConn->stmt_init();
$existingAcct = array();
if ($checkAcct->prepare("select usrName, eAddy from usr where usrName = ? OR eAddy = ?"))
{
$checkAcct->bind_param("ss", $usr, $eml);
$checkAcct->execute();
$checkAcct->bind_result($result);
while($checkAcct->fetch())
{
$existingAcct[] = $result;
}
if ($existingAcct[0] != 0)
{
if ($usr == $inputs['usrName'] && $eml == $inputs['eAddy'])
{
$acctSetupErrors[] = "Someone with your username and email address already exists. Please use the forgot password form to reset your password";
} else if ($eml == $inputs['eAddy']) {
$acctSetupErrors[] = "Someone with your email address already exists. Please use the forgot password form to reset your password or setup an account with a different email address";
} else {
$acctSetupErrors[] = "Someone with your username already exists. Please choose a different username";
}
}
$checkAcct->free_result();
$checkAcct->close();
Edit
Alright. I tried your way and it didn't work either so I went hunting for any previous db calls. I found the offending query in a db call in an include file linked higher up in the script. Funny, it's never caused problems anywhere else but now I freed the result and it works well. Thanks for your help with this. I don't have enough points to upvote you for suggesting it must be somewhere above in the code.
Can you change the above code like this and see what you are getting
$checkAcct = $dbConn->stmt_init();
$existingAcct = array();
if ($checkAcct->prepare("select usrName, eAddy from usr where usrName = ? OR eAddy = ?"))
{
$checkAcct->bind_param("ss", $usr, $eml);
$checkAcct->execute();
$checkAcct->store_result();
printf("Number of rows: %d.\n", $stmt->num_rows);
$checkAcct->free_result();
$checkAcct->close();
}
And could you make sure prepare buffer is cleared before you use it again. I hope there is some other query which is executed prior to this statement is still active in mysqli prepare statement buffer.
I'm writing a PHP code for my website. Currently, there's some problems with my code.
Here's my code. Ignore some Malay language used, I'd tried to translate most of them.
<?php
session_start();
include "../library/inc.connectiondb.php";
$txtUser = $_POST['txtUser'];
$txtPass = $_POST['txtPass'];
if(trim($txtUser) == "") {
echo "<b>User ID</b> is empty, please fill";
include "login.php";
}
else if(strlen(trim($txtPass)) <= 5) {
echo "<b>Password</b> is less then 6 characters, please fix";
include "login.php";
}
else {
$sqlPeriksa = "SELECT userID FROM admin WHERE userID='$txtUser'";
$qryPeriksa = mysql_query($sqlPeriksa, $sambung);
$hslPeriksa = mysql_num_rows($qryPeriksa);
if($hslPeriksa == 0) {
# If username doesn't exist
echo "<b>UserID</b> doesn't exist";
include "login.php";
}
else {
$sqlPassword = "SELECT passID FROM admin WHERE (userID='$txtUser' && passID='$txtPass')";
$qryPassword = mysql_query($sqlPeriksa, $sambung);
$hslPassword = mysql_num_rows($qryPassword);
if($hslPassword < 1) {
# If password is incorrect
echo "<b>Password</b> is incorrect";
include "login.php";
}
else {
# If login successful
$SES_Admin = $txtUser;
session_register('SES_Admin');
echo "LOGIN SUCCESSFUL";
# Redirect to index.php
echo "<meta http-equiv='refresh' content='0; url=index.php'>";
exit;
}
}
}
?>
The problem is this code allows me to login even if the password is wrong. I'd done some searches and it still doesn't solve my problem. I'm pretty sure that the problem is at line 27 onwards.
So, if anyone has a solution, please tell me quickly. I'm writing this code for my school, and it had to be finished before next year.
Edit
Ok, I'd already placed the mysql_real_escape_string in the code just like what many people told me. I don't know how this will help, but the mysql table for this was named "admin". It had 2 fields; userID and passID. To test the code, I'd inserted the value "admin" and "12345678" into the table.
This is where your problem is:
$sqlPassword = "SELECT passID FROM admin WHERE (userID='$txtUser' && passID='$txtPass')";
$qryPassword = mysql_query($sqlPeriksa, $sambung);
$hslPassword = mysql_num_rows($qryPassword);
You see, your mysql_query is executing $sqlPeriksa which is:
$sqlPeriksa = "SELECT userID FROM admin WHERE userID='$txtUser'";
Instead, your code should be like this:
$sqlPassword = "SELECT passID FROM admin WHERE (userID='$txtUser' && passID='$txtPass')";
$qryPassword = mysql_query($sqlPassword, $sambung);
$hslPassword = mysql_num_rows($qryPassword);
Please try this out and let us know what happens.
[edit/additional] : I strongly suggest that you look into the following:
Using PDO:
http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/
Using stored procedures:
http://dev.mysql.com/doc/refman/5.0/en/create-procedure.html
Using PDO + stored procedures:
http://php.net/manual/en/pdo.prepared-statements.php (See example #4)
just plain troubleshoot is necessary. how many rows are returned? what are the values of userID and passID in the query that returns rows? put some breaks in and see what's going on. i don't see a problem, it but its hard to troubleshoot code posted here since it really can't be run without a db.
I don't see any reason this isn't working as you expected, I suspect the problem might be elsewhere. For example, I don't see you checking if a "SES_Admin" session is already registered. But at the very least you need to replace lines 5 and 6 with this, otherwise someone could potentially delete your entire user table, and do various other malicious things with your MySQL databases.
$txtUser = mysql_real_escape_string($_POST['txtUser']);
$txtPass = mysql_real_escape_string($_POST['txtPass']);
Please read the article on mysql_real_escape_string at http://php.net/manual/en/function.mysql-real-escape-string.php