I have two steps sign up form. From the first step I'm picking up email and username and from second step I want to pick up first name and lastname and add it into DB.
But the problem is that variables which I've got from the first POST form, $bridge_username to be exact, is not available in the IF statement below (the first one from the bottom). The thing is that they are visible anywhere else, but not inside this particular IF statement. I've tried everything, including sessions. I can clearly see that variable is still there (using vardump or just echoing it out), everywhere but not where I need it...
I'll be happy to hear your advises.
$bridge_email = $_POST['email'];
$bridge_username = $_POST['username'];
$bridge_pass = $_POST['password'];
$bridge_pass_conf = $_POST['passconf'];
$bridge_terms = $_POST['terms'];
$bridge_pass_counted = strlen($bridge_pass);
$bridge_username_counted = strlen($bridge_username);
if (isset ($_POST['email']) AND isset ($_POST['password']) AND isset ($_POST['passconf']) AND isset ($_POST['username'])) {
if ($bridge_email != '' AND $bridge_pass != '' AND $bridge_pass_conf != '' AND $bridge_username != '' AND $bridge_terms != '') {
if ($bridge_pass == $bridge_pass_conf) {
if ($bridge_pass_counted >= 33 OR $bridge_pass_counted <= 5) {
} else {
if ($bridge_username_counted >= 65 OR $bridge_username_counted <= 3) {
} else {
if (is_numeric(substr($bridge_username, 0, 1))) {
} else {
//CHECK IF USERNAME OR EMAIL ALREADY EXIST
$checkreguser = $mysqli->query("SELECT username FROM `engine_users` WHERE username = '$bridge_username' OR email = '$bridge_email' LIMIT 0, 1 ");
$checkreguser = $checkreguser->fetch_assoc();
if ($checkreguser == '') {
//CREATING A NEW USER
$mysqli->query("INSERT INTO `users` (`id`, `username`, `password`, `email`, `fname`, `lname`, `company`, `address`, `city`, `state`, `zip`, `country`, `currency`, `phone`, `vat`, `userlevel`, `created`, `notes`, `lastlogin`, `lastip`, `active`) VALUES\n"
. "(NULL, '$bridge_username', '1411678a0b9e25ee2f7c8b2f7ac92b6a74b3f9c5', '$bridge_email', '', '', NULL, '', '', '', '', '', '', '', NULL, 5, '2011-05-01 18:10:14', '', '2013-04-19 22:25:11', '127.0.0.1', 'y')");
}}}}}}}
$bridge_fname = $_POST['1_1_3'];
$bridge_lname = $_POST['1_1_4'];
if (isset ($_POST['1_1_3']) AND isset ($_POST['1_1_4'])) {
$mysqli->query("UPDATE `users` SET `fname` = '$bridge_fname',`lname` = '$bridge_lname' WHERE `users`.`username` = '$bridge_username'");
}
I fixed your code a bit to make you a good example,
main issue was how you build your query string
..." username = '$bridge_username' "
this will result in a string like you see it
(it is good debug to print the queries, before executing them)
you have to change it to:
." username = '".$bridge_username."' "
and the variable will be replaced with its value.
Also added checks for the post values, so you don't get warnings if they are not set.
$bridge_email = (isset($_POST['email']) ? $_POST['email'] : null);
$bridge_username = (isset($_POST['username']) ? $_POST['username'] : null);
$bridge_pass = (isset($_POST['password']) ? $_POST['password'] : null);
$bridge_pass_conf = (isset($_POST['passconf']) ? $_POST['passconf'] : null);
$bridge_terms = (isset($_POST['terms']) ? $_POST['terms'] : null);
//$bridge_pass_counted = strlen($bridge_pass);
//$bridge_username_counted = strlen($bridge_username);
//return early and stay back from chained IFs
if (!$bridge_email || !$bridge_username || !$bridge_pass || !$bridge_pass_conf) {
return;
}
if ($bridge_pass != $bridge_pass_conf) {
return;
}
if ($bridge_pass AND strlen($bridge_pass) > 5 AND strlen($bridge_pass) < 33) {
return;
}
if ($bridge_username AND strlen($bridge_username) > 5 AND strlen($bridge_username) < 33) {
return;
}
if (is_numeric(substr($bridge_username, 0, 1))) {
return;
}
$result = $mysqli->query("SELECT username FROM `engine_users` WHERE username = '" . $bridge_username . "' OR email = '" . $bridge_email . "' LIMIT 0, 1 ");
$checkreguser = $result->fetch_assoc(); // returns associative array of strings or NULL if there are no more rows
//if ($checkreguser == '') {
if ($checkreguser === null) {
//CREATING A NEW USER
$mysqli->query("INSERT INTO `users` (`id`, `username`, `password`, `email`, `fname`, `lname`, `company`, `address`, `city`, `state`, `zip`, `country`, `currency`, `phone`, `vat`, `userlevel`, `created`, `notes`, `lastlogin`, `lastip`, `active`) VALUES\n"
. "(NULL, '" . $bridge_username . "', '1411678a0b9e25ee2f7c8b2f7ac92b6a74b3f9c5', '" . $bridge_email . "', '', '', NULL, '', '', '', '', '', '', '', NULL, 5, '2011-05-01 18:10:14', '', '2013-04-19 22:25:11', '127.0.0.1', 'y')");
}
$bridge_fname = (isset($_POST['1_1_3']) ? $_POST['1_1_3'] : null);
$bridge_lname = (isset($_POST['1_1_4']) ? $_POST['1_1_4'] : null);
if ($bridge_fname AND $bridge_lname ) {
$mysqli->query("UPDATE `users` SET `fname` = '" . $bridge_fname . "',`lname` = '" . $bridge_lname . "' WHERE `users`.`username` = '" . $bridge_username . "'");
}
Please examine the IF structure, returning early makes the code more readable.
http://php.net/manual/en/function.isset.php
I would try and break your code down to a simple few lines and test the if statement. Better to identify where it is breaking. Maybe add some echo statements during different steps or comment and step through the code. Example below.
$bridge_email = $_POST['email'];
$bridge_pass = $_POST['password'];
if (isset($_POST['email']) AND isset($_POST['password']){
// EXECUTE AN ALERT
echo"email and pass are set";
}else {
echo"not passing";
}
Use
if(isset($_POST['bridge_username']))
To see if it exists.
You can also use the ternary operator:
$email = isset($_POST['bridge_username']) ? $_POST['bridge_username'] = false;
And ye.. "$bridge_username to be exact, is not available in the IF statement below."
Show us the exact error if you want a more detailed answer :)
Are you checking to see if the session has been started. I see that you keep mentioning that the data was passed to session. May want to set this up to make sure that it is getting handled.
Try checking that the session variable was created and if not redirect back to the registration/login page.
As an example... if the session is not registered it will move to a different script or location.
session_start();
if(!session_is_registered(myusername)){
header("location:main_login.php");
you could further test the session by echoing contents on an isset on session to keep testing. Again, I would break your code down into the most basic form to learn what is going on. Might also need to see the prior page code to see what is happening.
found another example online that might help you out. http://www.phpeasystep.com/phptu/6.html
Related
I've been trying to track down a bug in my software for months now, to no success. It all comes down to one update query in PHP PDO seeming to run, with the correct data and yet it doesn't seem to update as "rowcount" returns 0.
Seems entirely random, 99% of the time it runs perfectly. 1% just doesn't update and I've literally no idea why.
For reference, here's the code in case someone spots me doing something really dumb. The part that is having issues is where it's updating the "saved_sessions" table.
// if they have a stay logged in cookie log them in
function stay_logged_in()
{
if (isset($_COOKIE['session']))
{
$session_check = $this->db->run("SELECT `session_id`, `device-id`, `user_id`, `expires` FROM `saved_sessions` WHERE `session_id` = ? AND `expires` > NOW()", array($_COOKIE['session']))->fetch();
if ($session_check)
{
// login then
$this->user_details = $this->db->run("SELECT ".$this::$user_sql_fields." FROM `users` WHERE `user_id` = ?", array($session_check['user_id']))->fetch();
$this->check_banned();
// update IP address and last login
$this->db->run("UPDATE `users` SET `ip` = ?, `last_login` = ? WHERE `user_id` = ?", array(core::$ip, core::$date, $this->user_details['user_id']));
// update their stay logged in cookie with new details
$generated_session = md5(time() . mt_rand() . $this->user_details['user_id'] . $_SERVER['HTTP_USER_AGENT']);
$expires_date = new DateTime('now');
$expires_date->add(new DateInterval('P30D'));
$update_session_sql = "UPDATE
`saved_sessions`
SET
`session_id` = ?,
`expires` = ?
WHERE
`session_id` = ? AND `user_id` = ?";
$update_session_db = $this->db->run($update_session_sql, array($generated_session, $expires_date->format('Y-m-d H:i:s'), $_COOKIE['session'], $session_check['user_id']));
$check_update = $update_session_db->rowcount();
// database was updated, so we can update the cookie
if($check_update == 1)
{
$cookie_domain = false; // allows cookies for localhost dev env
$secure = 0; // allows cookies for localhost dev env
if (!empty($this->core->config('cookie_domain')))
{
$cookie_domain = $this->core->config('cookie_domain');
$secure = 1;
}
setcookie('session', $generated_session, time()+$this->cookie_length, '/', $cookie_domain, $secure);
}
else
{
// logging for me to attempt to check the details match up (which they always seem to do!)
error_log("Couldn't update saved session for user_id " . $session_check['user_id'] . "\n" . "Current user session data: \n" . print_r($session_check, true) . "\nUser cookie data: " . $_COOKIE['session'] . "\n Database info: " . print_r($update_session_db, true));
}
$this->register_session($generated_session, $session_check['device-id']);
return true;
}
else
{
setcookie('session', "", time()-60, '/');
setcookie('device', "", time()-60, '/');
return false;
}
}
else
{
return false;
}
}
I have the following code which is part of a function to add a user to a database in PHP. It adds a user to a database.
if($user != '' && $pass != ''){
$new_name_q = "INSERT IGNORE INTO $db_name (`User`, `Password` ,`Name`, `Medals`, `TextSize`)
VALUES ('$user','$pass','$nameComplete', '000000', '18')";
$new_name_rs = mysqli_query($connection1,$new_name_q);
if(!$new_name_rs)
{
die("No name added: " . mysql_error());
}
}
The query works fine and I don't get any duplicates.
But I would like to echo a warning to the user in case the query is ignored.
Here's the code you need:
if($user != '' && $pass != ''){
$new_name_q = "INSERT IGNORE INTO $db_name (`User`, `Password` ,`Name`, `Medals`, `TextSize`)
VALUES ('$user','$pass','$nameComplete', '000000', '18')";
$new_name_rs = mysqli_query($connection1,$new_name_q);
$affected = mysqli_affected_rows($connection1);
if(!$affected) {
die("No name added");
}
}
See http://www.php.net/manual/en/mysqli.affected-rows.php
[I'm assuming here that you've done things like ensuring the variables are properly escaped already]
I have the below code that should add user input into the db, I can't understand why its not adding to db, the email field in the table is a foreign key that references to another table, and I'm using session to store email in the $email and save it to db when user saves data, also I'm accepting date and time from user input which is exactly as per the db format but it still doesn't save, I have tried entering static data as well, not working either. Am I missing something ?
$server = "localhost";
$user = "root";
$pwd = "";
$sql_db = "cabcustomers";
$email = $_SESSION['sesName'];
$conn = #mysqli_connect($server,$user,$pwd,$sql_db);
if (isset ($_POST["name"]) && isset ($_POST["contact"]) && isset ($_POST["unitno"]) && isset ($_POST["streetno"]) && isset ($_POST["streetname"]) && isset ($_POST["suburb"]) && isset ($_POST["destsuburb"]) && isset ($_POST["pickdt"]) && isset ($_POST["picktime"]))
{
$name = $_POST["name"];
$contact = $_POST["contact"];
$unitno = $_POST["unitno"];
$streetno = $_POST["streetno"];
$streetname = $_POST["streetname"];
$suburb = $_POST["suburb"];
$destsuburb = $_POST["destsuburb"];
$pickdt = $_POST["pickdt"];
$picktime = $_POST["picktime"];
if(empty($name) || empty($contact) || empty($unitno) || empty($streetno) || empty($streetname) || empty($suburb) || empty($destsuburb) || empty($pickdt) || empty($picktime))
{
echo "<p>ONE OR MORE OF FIELDS HAVE MISSING INFORMATION, KINDLY CHECK AND TRY AGAIN!</p>";
}
elseif (!is_numeric($contact))
{
echo "<p>CONTACT NUMBER MUST BE NUMERIC!</p>";
}
else
{
$idlen = 7;
$bookingid = uniqid (rand(), true);
$bookingid = "BK" . substr($bookingid, 0, $idlen);
$status = "unassigned";
$pickdt = $pickdt . " " . $picktime;
$query = "insert into bookings (bookingid, pname, contact, unitno, streetno, streetname, suburb, destsuburb, pickupdt, bookingdt, status, email) values ('$bookingid', '$name', '$contact', '$unitno', '$streetno', '$streetname', '$suburb', '$destsuburb','$pickdt', 'NOW()','$status', '$email');";
echo $email;
$result = mysqli_query($conn, $query);
echo $result;
echo "<p>INFORMATION SAVED</p>";
}
mysqli_close($conn);
}
Based on the comments after your initial question, I don't think the connection is the problem, the problem is most likely happening during the INSERT query. Have you tried running the query from phpMyAdmin to troubleshoot the syntax of the query outside of PHP?
When you hit the "Post" button it should send the data to the database and redirect you to ?success=true but it will not redirect you or send the data to the DB.
This is suppose to do the redirecting and function calling:
if (empty($_POST['postBox']) === false && $_GET['success'] != true){
sendPost();
header("LOCATION: /offtopic.php?success=true");
exit();
}
This is sendPost:
function sendPost()
{
$postBox = '\'' . htmlentities(mysql_real_escape_string($_POST['postBox'])) . '\'';
$user_id = $_SESSION['user_id'];
mysql_query("INSERT INTO `offtopicposts` (user_id, post, reported) VALUES ($user_id, $postBox, 0)") or die(mysql_error());
}
EDIT:
You can log in to the off-topic page with the username: Test and password: Test123456789
put a return statement in function
function sendPost()
{
$postBox = '\'' . htmlentities(mysql_real_escape_string($_POST['postBox'])) . '\'';
$user_id = $_SESSION['user_id'];
mysql_query("INSERT INTO `offtopicposts` (user_id, post, reported) VALUES ($user_id, $postBox, 0)") or die(mysql_error());
return;
}
Try this if condition
if (!empty($_POST['postBox']) && $_GET['success'] != 'true')
I am so sorry... Because of the new background I was unable to see the error... In the DB something wasn't allowed to be null... So a quick fix and its working... Thank you all for the help!
if (isset($submit)) {
$getusers = mysql_query("SELECT * FROM register");
while($getrows = mysql_fetch_array($getusers)) {
$users = $getrows['username'];
if ($touser == $users) {
echo "$users";
$send = $_GET['send'];
if ($send == $one) {
$query = mysql_query(
"INSERT INTO mailtbl VALUES
(
'', '$touser', '$fromuser', '$subject',
'$message', '0', '0', '1', '$date', '$rand'
)"
);
$query2 = mysql_query(
"INSERT INTO mailtbl_admin VALUES
(
'', '$touser', '$fromuser', '$subject',
'$message', '0', '0', '1', '$date', '$rand'
)"
);
$echo = "Message successfully sent.";
}
} else {
$echo = "There is no such user with the name of '$touser'";
}
}
echo "$echo";
}
I am trying to write code that accepts the message to send to another user if the recipient is in my database. The problem is that I think my condition (if ($touser == $users) is wrong. $touser refers to my $_POST['recipient'] in my form and $users refer to the users in the database.
Could someone please review my code to ensure I'm on the right track?
Instead of looping through all the users in your table, why don't you instead add a WHERE statement in your SQL command like this:
"SELECT * FROM register WHERE username = '" . $touser . "'"
If you get results send the message. If you get no results, display the 'no such user' message.
Also, if you are having trouble evaluating $touser to $user, try outputting the contents of $touser to make sure it's what you think it is.
print_r($touser);