I've been using $_GET data to send data across pages and it has been working fine.
What i have on one page is news. Each news article has its own specific ID (and this page works perfectly fine). I can click on an add me button next to each event to add myself as a volunteer for organising the BBQ for that event. However now i'm trying to click on an add button which can add other users to the BBQ.
I've checked to see if the $_GET data is returning anything on page load and it does, however the values are lost when i click submit. So, when i check to see if it returns anything inside the isset($_POST['userselect']), the values are lost:
Here is my code:
$rosterID = $_GET["rosterid"];
$eventID = $_GET["eventid"];
//if i check to see if they gets work here, they do.
if (hasRole2($connection, "Admin") || hasRole2($connection, "Moderator") || hasRole2($connection, "BBQ Moderator")){
$usernames[] = array();
if ($stmt = $connection->prepare("SELECT id, uid from people")){
$stmt->execute();
$stmt->bind_result($id, $username);
$stmt->store_result();
$form = new jqmForm();
$form->method('post');
$sel = $form->add(new jqmSelect('userselect','userselect','<p align="center">Select User:</p>'), true);
while ($stmt->fetch()){
$usernames[] = array('uid' => $username, 'id' => $id);
$optName = $username;
$optValue = $id;
$sel->add(new jqmOption($optName, $optValue, false));
$sel->attribute('data-native-menu', 'false');
}
$stmt->close();
$form->add(new jqmInput('submit', 'submit', 'submit', 'submit', '', 'b', true));
}
if (isset($_POST["userselect"])){
//if i check to see if the gets work here, they don't.
$personID = $_POST["userselect"];
if (rostered($connection, $personID, $rosterID, $eventID)){
$personID = $_POST["userselect"];
$p->addContent("<p align=center><font color = red>You have already rostered for this event</font></p>");
$login = $p->addContent("<font color=brown size=4><a href = news.php rel=external> Go back </a></font>");
$login->attribute('align', 'center');
}
else{
$search = "INSERT INTO RosterPeopleEvent (roster_id, person_id, news_id) VALUES (?, ?, ?)";
if (!$roster = $connection->prepare($search)){
$p->addContent("Inserting into RosterPeopleEvent Prepare failed: (" . $connection->errno . ") " . $connection->error);
}
else{
$roster->bind_param("iii", $_GET["rosterid"], $personID, $_GET["eventid"]);
$roster->execute();
}
}
}
}
Just added:
$form->action("url.php?rosterid=$rosterID&eventid=$eventID");
This worked.
Related
I have three files that are relevant for this part of my login scenario:
/project/index.html
/project/api/user/login.php
/project/api/objects/user.php
The index.html has a simple login form in it, calling the ./api/user/login.php.
In this form I have a checkbox that is an option for the user in order to stay logged in or not.
If the user has selected this option, with every login, I would like to check if the credentials are correct (login function -> stmt1 in user.php) as well as to update the lastlogin (datetime), the identifier and securitytoken if the checkbox was set (login function -> stmt2 in user.php).
The user.php is included_once in the login.php that gets the values out of the index.html form and sends them to the login() function in the user.php.
Depending on the functions return value, the login.php decides if the login was successful or not.
The login itself (stmt1) works, but the update of lastlogin, identifier and securitytoken (stmt2) doesn't.
login.php
session_start();
// include database and object files
include_once '../config/database.php';
include_once '../objects/user.php';
// get database connection
$database = new Database();
$db = $database->getConnection();
// prepare user object
$user = new User($db);
// set ID property of user to be edited
$user->username = isset($_GET['username']) ? $_GET['username'] : die();
$user->password = base64_encode(isset($_GET['password']) ? $_GET['password'] : die());
$user->remember = isset($_GET['remember']) ? $_GET['remember'] : die();
$stmt1 = $user->login();
if($stmt1->rowCount() > 0){
// get retrieved row
$row1 = $stmt1->fetch(PDO::FETCH_ASSOC);
$_SESSION['userid'] = $row1['uid'];
// create array
$user_arr=array(
"status" => true,
"message" => "Login erfolgreich!",
"uid" => $row1['uid'],
"username" => $row1['username']
);
$stmt2 = $user->login();
$row2 = $stmt2->fetch(PDO::FETCH_ASSOC);
print_r($row2);
// create array
$user_arr=array(
"lastlogin" => $row2['lastlogin']
);
}
else{
$user_arr=array(
"status" => false,
"message" => "Benutzername und/oder Passwort nicht korrekt!",
);
}
// make it json format
print_r(json_encode($user_arr));
?>
user.php
function login(){
// select all query
$query1 = "SELECT
`uid`, `username`, `email`, `password`, `created`, `lastlogin`
FROM
" . $this->table_name . "
WHERE
username='".$this->username."' AND password='".$this->password."'";
// prepare query statement
$stmt1 = $this->conn->prepare($query1);
// execute query
$stmt1->execute();
return $stmt1;
// set up the remain logged in function
if(isset($this->remember)) {
$identifier = random_string();
$securitytoken = random_string();
$remember = ",identifier='".$identifier."',securitytoken='".$securitytoken."'";
setcookie("identifier",$identifier,time()+(3600*24*365)); //1 year valid
setcookie("securitytoken",$securitytoken,time()+(3600*24*365)); //1 year valid
} else {
$remember = "";
}
// update last login
$query2 = "UPDATE
" . $this->table_name . "
SET
`lastlogin` = '".date("Y-m-d H:i:s")."'
".$remember."
WHERE
username='".$this->username."' AND password='".$this->password."'";
// prepare query statement
$stmt2 = $this->conn->prepare($query2);
// execute query
$stmt2->execute();
return $stmt2;
}
function random_string(){
if(function_exists('random_bytes')) {
$bytes = random_bytes(16);
$str = bin2hex($bytes);
} else if(function_exists('openssl_random_pseudo_bytes')) {
$bytes = openssl_random_pseudo_bytes(16);
$str = bin2hex($bytes);
} else if(function_exists('mcrypt_create_iv')) {
$bytes = mcrypt_create_iv(16, MCRYPT_DEV_URANDOM);
$str = bin2hex($bytes);
} else {
//secret key should have >12 random chars
$str = md5(uniqid('SECRET KEY', true));
}
return $str;
}
In the user.php after return $stmt1;
The code is returned and the cookies are not set
I would do this... Check login... If true, save cookies with id and token
And then periodically check if token and id correspond... If so... Just UPDATE the last login time.
Note: your prepared statement is vulnerable!! Dont append the parameters with '.' use placeholders instead, and dont encode the password, is better to hash it... Then compare hashes
I have created a search using php so that when a user is logged in they can search for other users and add them as a friend. When the user clicks the add as friend button I would like to post the username of the user that is logged in and the username of the user in the search result to a database table called friend_request.
Here is my code
<?php
if(isset($_POST['search'])) {
$search = $_POST['search'];
$search = preg_replace("#[^0-9a-z]i#","", $search);
$search = "%$search%";
if ($stmt = $db->prepare("SELECT username, name, location, gender, date_of_birth, url FROM Users WHERE name LIKE ?")){
$stmt->bind_param("s", $search);
$stmt->execute();
$stmt->bind_result($username, $name, $location, $gender, $date_of_birth, $picture);
$stmt->store_result();
$count = $stmt->num_rows;
if ($count == 0) {
$output = "There was no search results!";
} else {
while ($stmt->fetch()) {
$output .='<form action="#" method="post"><div class="row"><div class="col-sm-3">'.$name.'<br>'.$location.'<br>'.$gender.'<br>'.$date_of_birth.'</div>';
$output2 = '<div class="col-sm-3"><img src="upload/'.$picture.'"width="180" height="144" /></div>';
$output3 = '<input type="submit" name="addfriend" value="Submit" /></div></form>';
}
}
}
}
if(isset($_POST['addfriend'])) {
$user_from = $_SESSION['username'];
$user_to = $_POST['username'];
if ($stmt = $db->prepare("INSERT INTO `friends_request`(`user_to`, `user_from`) VALUES (?,?)")){
$stmt->bind_param("ss", $user_to, $user_from);
$stmt->execute();
}
}
?>
When I run my code I get the following message
Notice: Undefined index: username in /Applications/MAMP/htdocs/student_connect/header.php on line 51
It is simple.
It says $_SESSION['username']; hasn't been set, so look for the line of code where you expect you'd set it. I guess it might be in some other file (maybe to be executed after a login-form filling..?)
You need to start Debugging your code.....
Try adding this line after "$user_from = $_SESSION['username'];"
if(!$user_from)
{
echo "<pre>";
var_dump($_SESSION);
echo "<pre>";
}
Run your code and paste the results here - we can then start to determine what information is held in SESSION.
This is something you have to do when code doesn't do what expected, check your variables and see whats missing before heading to Stack. We are here to help, but need all info possible.
I am attempting to create a simple form that updates a row in a MYSQL database based on what ID the row is.
I have managed to get the form and updating values working, but for one of my variables I need its new value to be added to it, based on the values of two other variables. (So like $currPoints = $currPoints+$addPoints-$remPoints;).
The problem I am facing is that whenever the form is submitted, $currPoints is either resetting to 0, then adding and subtracting the other values, or the value of $cuurPoints isn't being found so that it cannot add to it's original value.
I am not sure where specifically in my code I am going wrong so I will paste the whole page if that is okay!
My form function. This get's called on page load:
// creates the form
function renderForm($name = '', $currPoints = '', $addPoints = '', $remPoints = '', $reason = '', $error = '', $id = '')
{ ?>
<title>
<?php if ($id != '') { echo "Edit Punk"; } else { echo "New Punk"; } ?>
</title>
<h1><?php if ($id != '') { echo "Edit Punk"; } else { echo "New Punk"; } ?></h1>
<?php if ($error != '') {
echo "<div style='padding:4px; border:1px solid red; color:red'>" . $error
. "</div>";
} ?>
<form name="pointsForm" action="" method="post" style="margin-top:50px;">
<?php if ($id != '') { ?>
<input type="hidden" name="id" value="<?php echo $id; ?>" />
<p>Name: <?php echo $name; ?> / <?php echo $currPoints; ?></p>
<?php } ?>
<input type="number" name="addPoints" placeholder="Add Punk Points">
<input type="number" name="remPoints" placeholder="Remove Punk Points">
<input type="text" name="reason" placeholder="Reason">
<input type="submit" name="submit" value="Update Punk Points">
</form>
</body>
</html>
<script>
$(function() {
$('form[name="pointsForm"]').submit(function(e) {
var reason = $('form[name="pointsForm"] input[name="reason"]').val();
if ( reason == '') {
e.preventDefault();
window.alert("Enter a reason, fool!")
}
});
});
</script>
<?php
}
Then my PHP for editing a record:
Where I get the variables from the URL/form I have added $currPoints = $currPoints+$addPoints-$remPoints;
Then on my bind_param is just add $currPoints.
I believe I am going wrong somewhere around these lines... or where I SET currPoints = ? . should that be something else?
Forgive me I am just learning PHP.
/*
EDIT RECORD
*/
// if the 'id' variable is set in the URL, we know that we need to edit a record
if (isset($_GET['id']))
{
// if the form's submit button is clicked, we need to process the form
if (isset($_POST['submit']))
{
// make sure the 'id' in the URL is valid
if (is_numeric($_POST['id']))
{
// get variables from the URL/form
$id = $_POST['id'];
$addPoints = htmlentities($_POST['addPoints'], ENT_QUOTES);
$remPoints = htmlentities($_POST['remPoints'], ENT_QUOTES);
$reason = htmlentities($_POST['reason'], ENT_QUOTES);
$currPoints = $currPoints+$addPoints-$remPoints;
// if everything is fine, update the record in the database
if ($stmt = $mysqli->prepare("UPDATE points SET currPoints = ? , addPoints = ?, remPoints = ?, reason = ?
WHERE id=?"))
{
$stmt->bind_param("iiisi", $currPoints, $addPoints, $remPoints, $reason, $id);
$stmt->execute();
$stmt->close();
}
// show an error message if the query has an error
else
{
echo "ERROR: could not prepare SQL statement.";
}
// redirect the user once the form is updated
header("Location: index.php");
}
// if the 'id' variable is not valid, show an error message
else
{
echo "Error!";
}
}
// if the form hasn't been submitted yet, get the info from the database and show the form
else
{
// make sure the 'id' value is valid
if (is_numeric($_GET['id']) && $_GET['id'] > 0)
{
// get 'id' from URL
$id = $_GET['id'];
// get the record from the database
if($stmt = $mysqli->prepare("SELECT * FROM points WHERE id=?"))
{
$stmt->bind_param("i", $id);
$stmt->execute();
$stmt->bind_result($id, $name, $currPoints, $addPoints, $remPoints, $reason, $date);
$stmt->fetch();
// show the form
renderForm($name, $currPoints, $addPoints, $remPoints, $reason, NULL, $id);
$stmt->close();
}
// show an error if the query has an error
else
{
echo "Error: could not prepare SQL statement";
}
}
// if the 'id' value is not valid, redirect the user back to the view.php page
else
{
header("Location: index.php");
}
}
}
?>
Sorry If I have been too vague. Please let me know if you need more information.
Thank you!
Oh found the error I think, you are never defining $currPoints before you try and use it, so you can't have $currPoints = $currPoints+.. because it isn't created yet. PHP more or less so will read line by line, so you have to query the SQL table and set $currPoints equal to the value from your database before you do $currPoints = $currPoints+$addPoints-$remPoints;
Ok, this probably won't work, but you should be able to figure out what I changed and adapt your code to work with it. I wouldn't say it's the 'proper' way, but it is a little easier to read and see what the code is doing when you have the if statements at the top to deal with what data is submitted vs not submitted.
if (!isset($_GET['id'] || !isset($_POST['submit'])))
{
echo "No Data!"
return;
}
if (!is_numeric($_POST['id']))
{
echo "Invalid ID!";
header("Location: index.php");
return;
}
// get variables from the URL/form
$id = $_POST['id'];
$addPoints = htmlentities($_POST['addPoints'], ENT_QUOTES);
$remPoints = htmlentities($_POST['remPoints'], ENT_QUOTES);
$reason = htmlentities($_POST['reason'], ENT_QUOTES);
$currPoints = 0;
//Check what the current points are first
// make sure the 'id' value is valid also
if (is_numeric($_GET['id']) && $_GET['id'] > 0)
{
// get 'id' from URL
$id = $_GET['id'];
// get the record from the database
if($stmt = $mysqli->prepare("SELECT * FROM points WHERE id=?"))
{
$stmt->bind_param("i", $id);
$stmt->execute();
$stmt->bind_result($id, $name, $currPoints, $addPoints, $remPoints, $reason, $date);
$stmt->fetch();
// show the form
renderForm($name, $currPoints, $addPoints, $remPoints, $reason, NULL, $id);
$stmt->close();
}
else
echo "Error: could not prepare SQL statement";
}
//Now update currPoints
$currPoints += $addPoints-$remPoints;
// if everything is fine, update the record in the database
if ($stmt = $mysqli->prepare("UPDATE points SET currPoints = ? , addPoints = ?, remPoints = ?, reason = ?
WHERE id=?"))
{
$stmt->bind_param("iiisi", $currPoints, $addPoints, $remPoints, $reason, $id);
$stmt->execute();
$stmt->close();
}
else
echo "ERROR: could not prepare SQL statement.";
// redirect the user once the form is updated
header("Location: index.php");
I have a table with inline editing using X-editable and everything is working fine including the value being submitted to the database, but for some reason it will display my echo in the else section.
Here is my PHP code:
require("config.php");
$userid = $_SESSION['user']['id'];
$sql = "SELECT fb_url, tw_url, ggl_url FROM social_preferences WHERE user_id = :userID";
$stmt = $db->prepare($sql);
$stmt->bindParam(":userID", $userid, PDO::PARAM_INT);
$stmt->execute();
$result = $stmt->fetch();
$pk = $_POST['pk'];
$name = $_POST['name'];
$value = $_POST['value'];
if(!empty($value)) {
try // save user selection to the database
{
$stmt = $db->prepare("UPDATE social_preferences SET tw_url = :twurl WHERE user_id = :userID");
$stmt->bindParam(":userID", $pk, PDO::PARAM_INT);
$stmt->bindParam(':twurl', $value);
$stmt->execute();
header("Location: admin-social.php");
die("Redirecting to admin-social.php");
} catch(PDOException $e) { echo 'Connection failed: ' . $e->getMessage(); }
}else {
echo 'Something went wrong!';
var_dump($value);
}
Here is my HTML code:
<a name="tw-url" id="tw-url" data-type="text" data-pk="<?php echo ($userid);?>" title="Edit"><?php echo ($result['tw_url']);?></a>
Like I said above everything seems to be working but it redirects to a page that will display my echo Something went wrong!even though it submitted the value to the DB. I included the var_dump to see if there is a value and that returns NULL. Can someone please help me? Any ideas why it would submit the right value to the database but redirect to my error?
Also, at what point does it send it to the database? I have a table in a form with a save button, but when I open the editable text and submit the new value does it send to the database when I save from the pop-over or when I click the save button in my table form?
The else statement is executing because when your details inserted into DB, you have set a header which redirects to the same page, in that case the variable $value value set to empty and your else statement executes.
The above answer is only valid if you set your header to same page.
I have a players page which returns a list of players and provides you with some options. One is edit and the other is stats. The edit page predictably takes you to a form where you can edit the player info like name, while the stats page simply shows statistics to do with that player (such as games played) that come primarily from other tables. Currently this a snippet of the code used to get stats:
if (isset($_POST['action']) and $_POST['action'] == 'Stats')
{
include $_SERVER['DOCUMENT_ROOT'] . '/statsite/includes/db.inc.php';
try
{
$sql = 'SELECT id, user.usertitle as name, role, aggression, position, bowlstyle, cricket_players.username, link FROM cricket_players INNER JOIN user ON cricket_players.username = user.userid WHERE id = :id';
$s = $pdo->prepare($sql);
$s->bindValue(':id', $_POST['id']);
$s->execute();
}
catch (PDOExecption $e)
{
$error = 'Error retrieving player details';
include 'players.html.php';
exit();
}
$row = $s->fetch();
$pageTitle = 'View Stats';
$name = $row['name'];
$aggression = $row['aggression'];
$position = $row['position'];
$role = $row['role'];
$bowlstyle = $row['bowlstyle'];
$link = $row['link'];
$username = $row['username'];
$id = $row['id'];
include 'stats.html.php';
exit();
}
If I click on the stats button everything works fine, but the address bar only has /? on the end of the address of the players page. Is there any way that I can get it to display something such as /stats?id=1 so that it can be linked directly?
Yes, you can directly pass the value /stats?id=1
and get value of id by using $_REQUEST['id'] OR $_GET['id']
Don't use : $s->bindValue(':id', $_POST['id']);
Use : $s->bindValue(':id', $_GET['id']);
OR
$s->bindValue(':id', $_REQUEST['id']);