variable not inserting correctly in mysql from PHP - php

Here is my PHP code:
// Collect data from URL
$mid = $_GET['m'];
if (isset($_POST['submit']))
{
$insert = "insert into table SET from_id = '".$loginuser['members_id']."', to_id = '". $mid ."', date = '".$_POST['date']."' ";
$add_member = mysql_query($insert);
}
The data gets entered in the database correctly except the $mid
But if in my HTML I put this :
<?php print $mid;?>
Then i can see the print of the ID number ... so I know my variable $mid has the proper value.... I don't know why it not getting inserted in the DB.
I also tried this SQL
$insert = "insert into table SET from_id = '".$loginuser['members_id']."', to_id = "$mid", date = '".$_POST['date']."' ";
$add_member = mysql_query($insert);
Same thing... everything works except the value of $mid doesn't go in the DB.
My field in the DB is set to Int(11) and there is no mistake in the column name.. i checked 5 times... Don'T know what's wrong.. thx
ENTIRE CODE HERE :
<?
ob_start();
include 'datalogin.php';
//checks cookies to make sure they are logged in
if(isset($_COOKIE["user"]))
{
$username = $_COOKIE["user"];
$pass = $_COOKIE["password"];
$check = mysql_query("SELECT * FROM members WHERE email = '$username'")or die(mysql_error());
$loginuser = false;
while($info = mysql_fetch_array( $check ))
{
if(! $loginuser)
{ $loginuser = $info; }
//if the cookie is present but has the wrong password, they are taken to the login page
if ($pass != $info['password'])
{
header("Location: login.php");
exit();
}
else //if the cookie is present and doesn'T have the wrong password they are shown the admin area
{
include 'header.php';
}
}
}
else //if there is no cookie present
{
header("Location: login.php");
exit();
}
// Collects data from images table
$mid = $_GET['m'];
$data = mysql_query("SELECT images.image_id, images.members_id, images.image_url, members.members_id, members.name, members.age
FROM members
LEFT JOIN images
ON members.members_id=images.members_id WHERE members.members_id ='". $mid ."' ")
or die(mysql_error());
$data2 = mysql_fetch_array( $data );
if (isset($_POST['submit']))
{
$insert = "insert into booking SET from_id = '".$loginuser['members_id']."', to_id = '$mid', date = '".$_POST['date']."'";
$add_member = mysql_query($insert) or die(mysql_error());
header('Location: index.php');
exit();
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" >
<table cellspacing='0' id="booking" align="center" width="680">
<tr>
<td>Date:</td>
<td><input name="date" type="text" size="10" maxlength="10" class="form-field" /> </td>
</tr>
<tr>
<td> </td>
<td><input class="submit-button" type="submit" name="submit" value="SEND REQUEST" /></td>
</tr>
</table>
</form>
<br />
HERE IS THE TABLE STRUCTURE
CREATE TABLE IF NOT EXISTS `booking` (
`booking_id` int(11) NOT NULL AUTO_INCREMENT,
`from_id` int(11) NOT NULL,
`to_id` int(11) NOT NULL,
`date` varchar(10) NOT NULL,
PRIMARY KEY (`booking_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=17 ;

Try in this way
if (isset($_POST['submit']))
{
$mid = $_GET['m'];
$insert = "insert into table SET from_id = '".$loginuser['members_id']."', to_id = '". $mid ."', date = '".$_POST['date']."' ";
$add_member = mysql_query($insert);
}

Related

How to take data from database and store it in session PHP

i want to make TOEFL test. when user want to start the test, first user must input email. So, when user click start, user have an id. I want take id from table 'id' and save it in session. so when i want to take score from 'listening', 'structure' and 'reading' table, i used that id.
but the problem is: when i do the test, listening, reading and structure score will be '0'. but i sure i has answered the questions correctly. Maybe it because id not save in session correctly. please help meeee
index.php
<form method="POST" action="add_id.php">
<input type="text" name="email" placeholder="Email">
<input name="btn" type="submit" value="Start"/>
</form>
add_id.php
<?php
include "connection.php";
$email = $_POST['email'];
$query = "INSERT INTO id(email) VALUES ('$email')";
if(mysql_query($query)){
$q = "SELECT * FROM id";
$ex=mysql_query($q);
$id = $ex['id'];
session_start();
$_SESSION['id'] = $id;
header("location:test_structure.php");
}
else {
echo mysql_error();
}
?>
calculate.php
<?
include "connection.php";
$id =$_SESSION['id'];
$query ="SELECT * FROM Reading WHERE Reading.id='$id'";
$ex=mysql_query($query);
$data=mysql_fetch_array($ex);
$right_structure = $data['rightanswer_read'];
$Reading = $data['score_read'];
$query ="SELECT * FROM Structure WHERE Structure.id='$id'";
$ex=mysql_query($query);
$data=mysql_fetch_array($ex);
$right_structure = $data['rightanswer_struct'];
$Structure = $data['score_struct'];
$q ="SELECT * FROM Listening WHERE Listening.id='$id'";
$e=mysql_query($q);
$d=mysql_fetch_array($e);
$right_listening = $d['rightanswer_list'];
$Listening = $d['score_list'];
$final_score = (($Listening + $Structure + $Reading)/3) * 10;
$NA = "INSERT INTO final_score VALUES ('$email', '$final_score', '$Listening', '$Structure', '$Reading', '$right_listening', '$right_structure', '$right_reading')";
if(mysql_query($NA)){
header("location:index.php");
}else {
echo mysql_error();
}
}
?>
this is id table structure:
CREATE TABLE IF NOT EXISTS `id` (
`id` int(100) NOT NULL,
`email` varchar(30) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
Change your add_id.php file like this,
<?php
session_start();
include "connection.php";
$email = $_POST['email'];
$query = "INSERT INTO id(email) VALUES ('$email')";
if(mysql_query($query)){
$id = mysql_insert_id();
$_SESSION['id'] = $id;
header("location:test_structure.php");
}
else {
echo mysql_error();
}
?>
Also read about function mysql_insert_id() at http://php.net/manual/en/function.mysql-insert-id.php

Only first entry in list enters mysql table PHP even though trim is used

I have this page of html
<html>
<body>
<form action="new_group.php" method="post">
<div>
<label for="group_name">Group Name: </label>
<input type="text" name="group_name" id="group_name" />
</div>
<div>
<label for="invites">Invite...</label>
<input type="text" name="invites" id="invites" />
</div>
<div>
<label for="description">Description: </label>
<textarea name="description" id="description"></textarea>
</div>
<div>
<input type="submit" value="Create" />
</div>
</form>
</body>
</html>
Which then has this PHP:
<?php
include "function_inc.php";
if(isset($_POST['group_name'], $_POST['description'], $_POST['invites'])){
$invites = explode(',', $_POST['invites']);
$user_id = $_SESSION['user_id']; //avoids issues with quotations (either invalid quotation for referring to PHP variable or repeated double quotes)
$result = mysqli_query($link, "SELECT `username` FROM `users` WHERE `user_id` = '$user_id'");
foreach($result as $resul){
foreach($resul as $resu){
$logged_in_username = $resu;
}}
if(in_array($logged_in_username, $invites)){
}else{
$invites[] = $logged_in_username;
}
foreach($invites as $invite) {
$invite = trim($invite);
echo $invite . '<br />';
$idres = mysqli_query($link, "SELECT `user_id` FROM `users` WHERE `username` = '$invite'");
if(mysqli_num_rows($idres) == 0) {
exit("1 or more of the users that you entered do(es) not exist!");
}
}
create_group($_POST['group_name'], $_POST['description'], $invites);
}
?>
and this is the create_group function:
function create_group($name, $description, $invites){
global $link;
$name = mysqli_real_escape_string($link, $name);
$description = mysqli_real_escape_string($link, $description);
$names = mysqli_query($link, "SELECT `group_name` FROM `groups` WHERE `group_name` = '$name'");
$descriptions = mysqli_query($link, "SELECT `group_description` FROM `groups` WHERE `group_description` = '$description'");
if(mysqli_num_rows($names) == 0 && mysqli_num_rows($descriptions) == 0) {
mysqli_query($link, "INSERT INTO `groups` (`group_name`, `group_description`) VALUES ('$name', '$description')");
} else {
echo 'Group with that name/description already exists.';
}
$result = mysqli_query($link, "SELECT `group_id` FROM `groups` WHERE `group_name` = '$name'");
foreach($result as $resul) {
foreach($resul as $resu) {
$group_id = $resu;
}
}
foreach($invites as $invite) {
$idres = mysqli_query($link, "SELECT `user_id` FROM `users` WHERE `username` = '$invite'");
foreach($idres as $idarr) {
foreach($idarr as $id) {
mysqli_query($link, "INSERT INTO `group_members` (`group_id`, `user_id`, `confirmed?`) VALUES ('$group_id', '$id', 0)");
}
}
}
echo 'Group created!';
}
What I am confused about is the following: if I create a group (for testing purposes) and include my (the current user logged on's) name, and have commas but no spaces in between, everything works fine. However, if I do the exact same thing, however I have spaces, only the first name in the array enters group_members. As you can see, there is a trim statement.
I have no idea why this is. Any help would be much appreciated as I am a beginner at PHP.
Thank you in advance
In the code:
foreach ($invites as $invite) {
$invite = trim($invite);
...
}
The variable $invite is separate from the array element. Assigning to that variable does not modify the contents of the array. You can fix this by using a reference:
foreach ($invites as &$invite) {
$invite = trim($invite);
...
}
The & prefix makes $invite a reference variable, i.e. an alias for the array element. Now, assigning to the variable updates the array element that it refers to.

PHP Friend Relationship between 2 rows?

first time I've used this site .. I've had a good look around but I cant seem to find the answer to my question. It's been answered in other ways but not for what I want I think..
Image of the database table so it's easy to see: http://puu.sh/6BtmZ.png
So basically I've got a friends.php page that has an input field and submit button, you put a username in and press submit and I want it to send a request to that user; I've got that to work, the user can accept but it only places the "friend" into him. As in FRIENDA is friends with FRIENDB but on FRIENDB's page he isn't friends with FRIENDA .. I hope this makes sense.
I just basically want it so, you send a request and the person accepts it and BOTH parties can see each other as friends.
<?php
include 'core/init.php';
// check
protect_page();
include 'includes/templates/header.php';
$user_id = $user_data['user_id'];
if (empty($_POST) === false) {
$required_fields = array('username');
foreach($_POST as $key=>$value) {
if (empty($value) && in_array($key, $required_fields) === true) {
$errors[] = 'You need to enter a username to send a request!';
break 1;
}
}
if (empty($errors) === true) {
if (user_exists($_POST['username']) === false) {
$errors[] = 'Sorry, the username \'' . htmlentities($_POST['username']) . '\' doesn\'t exist.';
}
}
}
if (isset($_GET['success']) && empty($_GET['success'])) {
echo 'Friend request sent!';
} else {
if (empty($_POST) === false && empty($errors) === true) {
// add friend
$username = $_POST['username'];
$get_userid = mysql_query("SELECT `user_id` FROM `users` WHERE `username` = '$username'");
$row = mysql_fetch_array($get_userid);
$username_id = $row[user_id];
$user_id = $user_data['user_id'];
mysql_query("INSERT INTO `users_friends` (user_id, friends_with) VALUES ('$user_id', '$username_id')");
//redirect
header('location: friends.php?success');
//exit
exit();
} else if (empty($errors) === false) {
// output errors
echo output_errors($errors);
}
}
?>
<h1>Friends</h1>
<p>
<h2>Send a friend request:</h2>
<form id="friend_request" action="" method="POST">
<ul>
<li>Username: <input type="text" name="username"><input id="friend_request" type="submit"></li>
</ul>
</form>
</p>
<p>
<h2>Pending requests:</h2>
<?php
if(isset($_POST['decline'])){
$decline_id = $_POST['decline_friend_id'];
$decline_query = "DELETE FROM `users_friends` WHERE `id` = $decline_id";
$accept_result = mysql_query($decline_query);
}
if(isset($_POST['accept'])){
$accept_id = $_POST['accept_friend_id'];
$accept_query = "UPDATE `users_friends` SET `request_pending` = 0 WHERE `id` = $accept_id";
$accept_result = mysql_query($accept_query);
}
$result = mysql_query("SELECT * FROM `users_friends` WHERE `friends_with` = '$user_id' AND `request_pending` = 1");
while($requests_row = mysql_fetch_array($result)) {
$get_username = mysql_query("SELECT `username` FROM `users` WHERE `user_id` = '$requests_row[user_id]'");
$get_username_row = mysql_fetch_array($get_username);
$request_from = $get_username_row[username];
echo 'Request from: ' . $request_from . '<form id="decline" action="" method="POST">
<input type="hidden" name="decline_friend_id" value="' . $requests_row['id'] . '">
<input type="submit" value="Decline" name="decline">
</form>
<form id="accept" action="" method="POST">
<input type="hidden" name="accept_friend_id" value="' . $requests_row['id'] . '">
<input type="submit" value="Accept" name="accept">
</form>';
echo '<br />';
}
?>
</p>
<h2>Your friends:</h2>
<?php
$friends_result = mysql_query("SELECT * FROM `users_friends` WHERE `friends_with` = '$user_id' AND `request_pending` = 0");
while($friends_row = mysql_fetch_array($friends_result)) {
$get_username = mysql_query("SELECT `username` FROM `users` WHERE `user_id` = '$friends_row[user_id]'");
$get_username_row = mysql_fetch_array($get_username);
$friend = $get_username_row[username];
echo $friend . '<br />';
}
?>
</p>
<?php include 'includes/templates/footer.php'; ?>
Hopefully someone might be able to help? Thanks in advance!
What you probably want to do is insert both directions in the friends relationship once both friends have confirmed. So instead of doing this:
INSERT INTO `users_friends` (user_id, friends_with) VALUES ('$user_id', '$username_id')
You would do this:
INSERT INTO `users_friends` (user_id, friends_with) VALUES ('$user_id', '$username_id'),('$username_id','$user_id')
This would allow you to do the friend lookup in either direction.
What is unclear to me however is how you store pending friend requests in your database. So what you may ultimately need to do is to insert those relations in the DB and then simply update those DB records to change the value of an "accepted" flag once the friendship has confirmed.
If the structure of "users_friends" table looks like this:
me friends_with request_pending
to get the result (= if the user is your friend):
"SELECT * FROM `users_friends` WHERE (`friends_with` = '$user_id' AND `me`= `$me`) OR (`friends_with` = '$me' AND `me`= `$user_id `) AND `request_pending` = 0"
You check if the user is in friends_with where YOU are in me.. or if the user is in me and you're in friends_with

PHP Validating Submit

I'm working on a project where a user can click on an item. If the user clicked at it before , then when he tries to click at it again it shouldn't work or INSERT value on the DB. When I click the first item(I'm displaying the items straight from database by id) it inserts into DB and then when I click at it again it works(gives me the error code) doesn't insert into DB. All other items when I click at them , even if I click for the second, third, fourth time all of it inserts into DB. Please help guys. Thanks
<?php
session_start();
$date = date("Y-m-d H:i:s");
include("php/connect.php");
$query = "SELECT * FROM test ORDER BY `id` ASC LIMIT 3";
$result = mysql_query($query);
if (isset($_SESSION['username'])) {
$username = $_SESSION['username'];
$submit = mysql_real_escape_string($_POST["submit"]);
$tests = $_POST["test"];
// If the user submitted the form.
// Do the updating on the database.
if (!empty($submit)) {
if (count($tests) > 0) {
foreach ($tests as $test_id => $test_value) {
$match = "SELECT user_id, match_id FROM match_select";
$row1 = mysql_query($match)or die(mysql_error());
while ($row2 = mysql_fetch_assoc($row1)) {
$user_match = $row2["user_id"];
$match = $row2['match_id'];
}
if ($match == $test_id) {
echo "You have already bet.";
} else {
switch ($test_value) {
case 1:
mysql_query("UPDATE test SET win = win + 1 WHERE id = '$test_id'");
mysql_query("INSERT INTO match_select (user_id, match_id) VALUES ('1','$test_id')");
break;
case 'X':
mysql_query("UPDATE test SET draw = draw + 1 WHERE id = '$test_id'");
mysql_query("INSERT INTO match_select (user_id, match_id) VALUES ('1','$test_id')");
break;
case 2:
mysql_query("UPDATE test SET lose = lose + 1 WHERE id = '$test_id'");
mysql_query("INSERT INTO match_select (user_id, match_id) VALUES ('1','$test_id')");
break;
default:
}
}
}
}
}
echo "<h2>Seria A</h2><hr/>
<br/>Welcome,".$username."! <a href='php/logout.php'><b>LogOut</b></a><br/>";
while ($row = mysql_fetch_array($result)) {
$id = $row['id'];
$home = $row['home'];
$away = $row['away'];
$win = $row['win'];
$draw = $row['draw'];
$lose = $row['lose'];
echo "<br/>",$id,") " ,$home, " - ", $away;
echo "
<form action='seria.php' method='post'>
<select name='test[$id]'>
<option value=\"\">Parashiko</option>
<option value='1'>1</option>
<option value='X'>X</option>
<option value='2'>2</option>
</select>
<input type='submit' name='submit' value='Submit'/>
<br/>
</form>
<br/>";
echo "Totali ", $sum = $win+$lose+$draw, "<br/><hr/>";
}
} else {
$error = "<div id='hello'>Duhet te besh Log In qe te vendosesh parashikime ndeshjesh<br/><a href='php/login.php'>Kycu Ketu</a></div>";
}
?>
Your problem is here :
$match = "SELECT user_id, match_id FROM match_select";
$row1 = mysql_query($match)or die(mysql_error());
while ($row2 = mysql_fetch_assoc($row1)) {
$user_match = $row2["user_id"];
$match = $row2['match_id'];
}
You are not checking it correctly. You have to check if the entry in match_select exists for the user_id and the match_id concerned. Otherwise, $match would always be equal to the match_id field of the last inserted row in your database :
$match = "SELECT *
FROM `match_select`
WHERE `user_id` = '<your_id>'
AND `match_id` = '$test_id'";
$matchResult = mysql_query($match)or die(mysql_error());
if(mysql_num_rows($matchResult)) {
echo "You have already bet.";
}
By the way, consider using PDO or mysqli for manipulating database. mysql_ functions are deprecated :
http://www.php.net/manual/fr/function.mysql-query.php
validate insertion of record by looking up on the table if the data already exists.
Simplest way for example is to
$query = "SELECT * FROM match_select WHERE user_id = '$user_id'";
$result = mysql_query($query);
if(mysql_num_rows($result) > 0)
{
// do not insert
}
else
{
// do something here..
}
In your form you have <select name='test[$id]'> (one for each item), then when you submit the form you are getting $tests = $_POST["test"]; You don't need to specify the index in the form and can simply do <select name='test[]'>, you can eventually add a hidden field with the id with <input type="hidden" value="$id"/>. The second part is the verification wich is not good at the moment; you can simply check if the itemalready exist in the database with a query

Keeping session (userID) the same whilst changing pages

My users have a user_ID when logging in and this appears within the URL. However when moving to a page from 'myaccount.php' when the next form has been saved (thesis.php) the same ID should still be in the URL and therefore the correct data they inputted should be under their own ID in the database. At the moment the thesis.php page just refreshes with the following code:
$err = array();
$result = mysql_query("SELECT `id` FROM `users` WHERE `banned` = '0' ORDER BY
`id` DESC");
if(isset($_SESSION['user_id']))
if(empty($_SESSION['$user_id'])) { // user not logged in; redirect to somewhere else }
if (!empty($_POST['doThesis']) && $_POST['doThesis'] == 'Save')
{
list($id) = mysql_fetch_row($result);
session_start();
// this sets variables in the session
$_SESSION['user_id'] = $id;
foreach($_POST as $key => $value)
$stamp = time();
$ckey = GenKey();
mysql_query("update users set `ctime`='$stamp', `ckey` = '$ckey' where id='$id'")
or die(mysql_error());
$row = mysql_fetch_array($result);
print_r($row);
if(empty($err)) {
$thesis_Name = mysql_real_escape_string($_POST['thesis_Name']);
$abstract = mysql_real_escape_string($_POST['abstract']);
$sql_insert = "INSERT into `thesis`
(`user_id`,`thesis_Name`,`abstract` )
VALUES
('$id','$thesis_Name','$abstract') ";
mysql_query($sql_insert,$link) or die("Insertion Failed:" . mysql_error());
}
header("Location: myaccount.php?id=' . $_SESSION[user_id] .'");
exit();
}
}
HTML:
<p align="center">
<input name="doThesis" type="submit" id="doThesis" value="Save">
</p>
I believe you need to call session_start() before you can do isset($_SESSION['blah']).
Try shifting session_start(); to the top of the file
<?php
session_start();
.....
the rest of your code
session_start(); Must be at the top;
if you want to pass the id var in the URL use
<a href='myaccount.php?id=<? echo $id; ?>'>

Categories