id not changing correctly - php

If I register a user using this table:
CREATE TABLE IF NOT EXISTS `users`
(
`id` INT(11) NOT NULL AUTO_INCREMENT,
`md5_id` VARCHAR(200) NOT NULL,
`full_name` TINYTEXT CHARACTER SET latin1 COLLATE latin1_general_ci
NOT NULL,
`user_name` VARCHAR(10) NOT NULL,
`user_email` VARCHAR(30) NOT NULL,
`user_level` TINYINT(4) NOT NULL DEFAULT '1',
`pwd` VARCHAR(220) NOT NULL,
`nationality` VARCHAR(30) NOT NULL,
`department` VARCHAR(20) NOT NULL,
`birthday` DATE NOT NULL,
`date` DATE NOT NULL DEFAULT '0000-00-00',
`users_ip` VARCHAR(200) NOT NULL,
`activation_code` INT(10) NOT NULL DEFAULT '0',
`banned` INT(1) NOT NULL,
`ckey` VARCHAR(200) NOT NULL,
`ctime` VARCHAR(220) NOT NULL,
`approved` INT(1) NOT NULL DEFAULT '1',
PRIMARY KEY (`id`)
)
ENGINE=INNODB
DEFAULT CHARSET=latin1
AUTO_INCREMENT=3;
and then once logged in to 'myaccount.php' use this code to enter values into another table, the language table:
if (empty($_SESSION['$user_id'])) { // user not logged in; redirect to somewhere else }
if (!empty($_POST['doLanguage']) && $_POST['doLanguage'] == 'Submit') {
$result = mysql_query("SELECT `id` FROM users WHERE `banned` = '0' order by id desc");
list($id) = mysql_fetch_row($result);
session_start();
$_SESSION['user_id'] = $id;
foreach ($_POST as $key => $value) if (empty($err)) {
for ($i = 0;$i < count($_POST["other"]);$i++) {
$native = mysql_real_escape_string($_POST['native'][$i]);
$other = mysql_real_escape_string($_POST['other'][$i]);
$other_list = mysql_real_escape_string($_POST['other_list'][$i]);
$other_read = mysql_real_escape_string($_POST['other_read'][$i]);
$other_spokint = mysql_real_escape_string($_POST['other_spokint'][$i]);
$other_spokprod = mysql_real_escape_string($_POST['other_spokprod'][$i]);
$other_writ = mysql_real_escape_string($_POST['other_writ'][$i]);
$sql_insert = "INSERT into `language`
(`user_id`,`native`,`other`,`other_list`,`other_read`, `other_spokint`
,`other_spokprod`,`other_writ` )
VALUES
('$id','$native','$other','$other_list','$other_read','$other_spokint',
'$other_spokprod','$other_writ') ";
mysql_query($sql_insert, $link) or die("Insertion Failed:" . mysql_error());
}
header("Location: myaccount.php?id=' . $_SESSION[user_id] .'");
exit();
}
}
}
All is fine until , for example I register id=3 (in users table) and then log back into id=1 and change their details in the language table, then their user_id in the language table (which is foreign key to id in users table) is 3 when it should be 1. To make things simple, the id in users table should be same as the user_id in the language table. But when going back and changing data in the languages table the user_id stays the same as the last id that registered!
Please help!

This query you have:
$result = mysql_query("SELECT `id` FROM users WHERE `banned` = '0' order by id desc");
What is the purpose of it? You are assigning to $id the first value it finds, yet the query doesn't look for user name or anything else. You probably want to user $_SESSION['$user_id'] instead of $id as your user's ID.

Related

Fetch all data in array

I am trying to add the direction, left and right member to direct but the problem now here is that I am only able to fetch one data (left_mem) instead of both left_mem and right_mem.
$query = $MySQLi_CON->query("select * from users where enroller_id='".$enroller_id_n."' ");
$direct = array();
if($query){
while ($row = $query->fetch_array()) {
$enroller_id3 = $row['enroller_id'];
$direct[] = $row['direction'];
}
}
if ($direct == "left_mem")
{
echo "success";
}
else {
echo "fail";
}
This is my database
CREATE TABLE `users` (
`user_id` int(11) NOT NULL,
`user_name` varchar(25) NOT NULL,
`user_email` varchar(255) NOT NULL,
`user_pass` varchar(255) NOT NULL,
`enroller_id` varchar(25) NOT NULL,
`enrolled_id` varchar(25) NOT NULL,
`direction` varchar(25) NOT NULL DEFAULT 'avail'
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
INSERT INTO `users` (`user_id`, `user_name`, `user_email`, `user_pass`, `enroller_id`, `enrolled_id`, `direction`);
ALTER TABLE `users`
ADD UNIQUE KEY `user_id` (`user_id`);
ALTER TABLE `users`
MODIFY `user_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1;
Use in_array to see if both values exist:
if (in_array('left_mem',$direct) && in_array('right_mem',$direct) )

How to write nested query MySQL PHP

I'm developing a page to edit board meetings and I want to display all board members who did not attend specific meeting as a checkox located below who attend as an edit in case of user want to add more so I did this:
My code:
$q = "SELECT * FROM `boardteam`";
$r = mysql_query($q);
while ($dbfield = mysql_fetch_assoc($r))
{
$member_id =$dbfield['nationalID'];
$query = "SELECT `attendance` FROM `meetingattendance` WHERE `meetingID` = '$mid' AND `attendance`!= '$member_id'";
$res = mysql_query($query);
if ($res)
{
$tname ="";
switch ($dbfield['titleName'])
{
case "Dr":
$tname .= "د.";
break;
case "Ms":
$tname .= "السيدة.";
break;
case "Mr":
$tname .= "السيد.";
break;
}
$At .= "<input type='checkbox' name='moreAttendence[]' dir='rtl' value=".$dbfield['nationalID']."><div class='styled-checkbox'>".$tname." ".$dbfield['fName']." ".$dbfield['sName']." ".$dbfield['lName']."</div><br>";
}
}
DB:
CREATE TABLE `boardteam` (
`nationalID` int(10) NOT NULL,
`titleName` char(2) NOT NULL,
`fName` char(20) NOT NULL,
`sName` char(20) NOT NULL,
`lName` char(20) NOT NULL,
`gender` char(1) NOT NULL,
`birthDate` date DEFAULT NULL,
`materialStatus` char(15) DEFAULT NULL,
`jobTitle` varchar(100) NOT NULL,
`jobLocation` varchar(20) DEFAULT NULL,
`employer` varchar(100) DEFAULT NULL,
`email` varchar(100) NOT NULL,
`photo` varchar(255) DEFAULT NULL,
`academicGrade` char(15) DEFAULT NULL,
`employmentStartDate` date NOT NULL,
`employmentEndDate` date NOT NULL,
`employmentType` char(20) DEFAULT NULL,
`employmentStatus` char(15) DEFAULT NULL,
`jobStartDate` date DEFAULT NULL,
`jobNumber` int(10) DEFAULT NULL,
`cv` varchar(255) DEFAULT NULL,
PRIMARY KEY (`nationalID`)
)
CREATE TABLE `meetingattendance` (
`meetingID` int(11) NOT NULL,
`attendance` int(10) DEFAULT NULL,
`absence` int(10) DEFAULT NULL,
`reason` varchar(255) DEFAULT NULL,
`additionalAttendance` varchar(255) DEFAULT NULL,
KEY `absence` (`absence`),
KEY `meeingID` (`meetingID`),
KEY `attendance` (`attendance`),
CONSTRAINT `meetingattendane_ibfk_1` FOREIGN KEY (`meetingID`) REFERENCES `boardmeetings` (`meetingID`),
CONSTRAINT `meetingattendane_ibfk_2` FOREIGN KEY (`attendance`) REFERENCES `boardteam` (`nationalID`),
CONSTRAINT `meetingattendane_ibfk_3` FOREIGN KEY (`absence`) REFERENCES `boardteam` (`nationalID`)
)
With my code I got all board members including who attend, How to fix that ??
You need to use a LEFT JOIN in order to find people in the boardTeam who were not in a specific meeting. eg:
SELECT b.*, m.attendance
FROM boardTeam b
LEFT JOIN meetingattendance m
ON b.nationalID = m.attendance AND m.meetingID = $mid
WHERE m.meetingID IS NULL
If you want to get ALL board members, and then determine within PHP if they attended the meeting or not, simply remove the m.attendance IS NULL clause, as such:
SELECT b.*, m.attendance as attendance
FROM boardTeam b
LEFT JOIN meetingattendance m
ON b.nationalID = m.attendance AND m.meetingID = $mid
and now when you loop through the response rows in php, you can test as such (assuming you fetch your rows one by one into a $row variable):
if($row['attendance'] != null)
{
// attended meeting
}
else
{
// did not attend meeting
}
Also, as mentioned in the comments, use mysqli, or pdo instead of pure mysql_ functions
Example fiddle here: http://sqlfiddle.com/#!9/ba7d4/6

PHP MySQL, check for duplicates in two tables

I am working on a program that allows students to sign up for a placement test. If we have the student ID in the student_data table, we add information to the additional_data table that stores test date and time info. If student is not in the student_data table, they're added to untracked_attendants that stores test date and time info.
Here is what I need to do: If the student is in additional_data or untracked_attendants and the test date is the same as the new entry, I don't want the seats taken to increment.
I've looked for an answer to this for a couple of days now and tried different variations of my query with no success. Below are the answers I've gotten tips from:
Check for duplicates before inserting
Proper way to prevent duplicate entries using MySQL or PHP
The $query1 below check if the student exists in the additional_data table already but I need to also check if the placement date is the same. If it is, then I don't want to increment the number of seats taken. The AND clause here isn't working for me. Without the AND, it's fine.
$query1 = $db->prepare("SELECT AES_DECRYPT(student_data_id, '".KEY."')
FROM additional_data
WHERE AES_DECRYPT(student_data_id, '".KEY."') = :studentDataId
AND placement_date = :placementDate");
$query1->bindParam(":studentDataId", $studentDataId);
$query1->execute();
$query2 just doesn't work at all. It always returns 0 event if I can see that the id exists
$query2 = $db->prepare("SELECT AES_DECRYPT(stu_id, '".KEY."')
FROM untracked_attendants
WHERE AES_DECRYPT(stu_id, '".KEY."') = :stuId
AND test_date = :placementDate");
$query2->bindParam(":stuId", $stuId);
$query2->execute();
Here is the entire code from my document. (the code between the two lines of *** is what I've changed from when I inherited the program when it incremented seats no matter what:
//Return test dates as JSON
if($_POST['action'] == "getDates") {
$query = $db->prepare("SELECT * FROM test_dates WHERE active = 1 ORDER BY date ASC");
$query->execute();
echo json_encode($query->fetchAll());
}
//Checks if the test date is still activated and returns an appropriate response
if($_POST['action'] == "checkDate") {
$id = strip_tags($_POST['id']);
$query = $db->prepare("SELECT id FROM test_dates WHERE id = :id AND active = 1");
$query->bindParam(":id", $id);
$query->execute();
if($query->rowCount() > 0) {
echo "open";
}
else {
echo "closed";
}
}
//Return test types as JSON
if($_POST['action'] == "getTests") {
$query = $db->prepare("SELECT * FROM test_types");
$query->execute();
echo json_encode($query->fetchAll());
}
//Save the placement test registration
if($_POST['action'] == "save") {
$uid = filter_var(strip_tags(trim($_POST['uid'])), FILTER_SANITIZE_STRING);
$id = filter_var(strip_tags(trim($_POST['id'])), FILTER_SANITIZE_NUMBER_INT);
$fname = filter_var(strip_tags(trim($_POST['firstName'])), FILTER_SANITIZE_STRING);
$lname = filter_var(strip_tags(trim($_POST['lastName'])), FILTER_SANITIZE_STRING);
$stuId = filter_var(strip_tags(trim($_POST['stuId'])), FILTER_SANITIZE_NUMBER_INT);
$email = filter_var(strip_tags(trim($_POST['emailAddress'])), FILTER_SANITIZE_EMAIL);
$retake = filter_var(strip_tags(trim($_POST['retake'])), FILTER_SANITIZE_NUMBER_INT);
$location = filter_var(strip_tags(trim($_POST['location'])), FILTER_SANITIZE_STRING);
$testDate = filter_var(strip_tags(trim($_POST['testDate'])), FILTER_SANITIZE_NUMBER_INT);
if(isset($_POST['testTypes'])) {
$testTypes = strip_tags(trim($_POST['testTypes']));
$testTypes = str_replace("|", " ", $testTypes);
}
else {
$testTypes = "";
}
//If the student already exists then add data relating to that record
$query = $db->prepare("SELECT id,
AES_DECRYPT(student_id, '".KEY."') AS student_id
FROM student_data
WHERE AES_DECRYPT(student_id, '".KEY."') = :student_id");
$query->bindParam(":student_id", $stuId);
$query->execute();
if($query->rowCount() > 0) {
$row = $query->fetch();
$studentDataId = $row['id'];
$query = $db->prepare("SELECT AES_DECRYPT(student_data_id, '".KEY."')
FROM additional_data
WHERE AES_DECRYPT(student_data_id, '".KEY."') = :studentDataId");
$query->bindParam(":studentDataId", $studentDataId);
$query->execute();
//If there is already additional data then update it
if($query->rowCount() > 0) {
$query = $db->prepare("UPDATE additional_data
SET uid = :uid,
placement_date = :placementDate,
placement_room = :placementRoom,
placement_time = :placementTime,
tests_needed = :testsNeeded
WHERE AES_DECRYPT(student_data_id, '".KEY."') = :studentDataId");
$query->bindParam(":uid", $uid);
$query->bindParam(":studentDataId", $studentDataId);
$query->bindParam(":placementDate", date("Y-m-d", $testDate));
$query->bindParam(":placementRoom", $location);
$query->bindParam(":placementTime", date("H:i:s", $testDate));
$query->bindParam(":testsNeeded", $testTypes);
$query->execute();
}
//If not insert a new record
else {
$query = $db->prepare("INSERT INTO additional_data
(uid,
student_data_id,
placement_date,
placement_room,
placement_time,
tests_needed)
VALUES
(:uid,
AES_ENCRYPT(:studentDataId, '".KEY."'),
:placementDate,
:placementRoom,
:placementTime,
:testsNeeded)");
$query->bindParam(":uid", $uid);
$query->bindParam(":studentDataId", $studentDataId);
$query->bindParam(":placementDate", date("Y-m-d", $testDate));
$query->bindParam(":placementRoom", $location);
$query->bindParam(":placementTime", date("H:i:s", $testDate));
$query->bindParam(":testsNeeded", $testTypes);
$query->execute();
}
}
//If the student does not exist in then add it into an untracked attendants table
else {
$query = $db->prepare("INSERT INTO untracked_attendants
VALUES(null,
:uid,
AES_ENCRYPT(:fname, '".KEY."'),
AES_ENCRYPT(:lname, '".KEY."'),
AES_ENCRYPT(:stuId, '".KEY."'),
AES_ENCRYPT(:email, '".KEY."'),
:testDate,
:location,
:testTime,
:retake,
:testsNeeded)");
$query->bindParam(":uid", $uid);
$query->bindParam(":fname", $fname);
$query->bindParam(":lname", $lname);
$query->bindParam(":stuId", $stuId);
$query->bindParam(":email", $email);
$query->bindParam(":testDate", date("Y-m-d", $testDate));
$query->bindParam(":location", $location);
$query->bindParam(":testTime", date("H:i:s", $testDate));
$query->bindParam(":retake", $retake);
$query->bindParam(":testsNeeded", $testTypes);
$query->execute();
}
/*************************************************************************
*************************************************************************/
$query1 = $db->prepare("SELECT AES_DECRYPT(student_data_id, '".KEY."')
FROM additional_data
WHERE AES_DECRYPT(student_data_id, '".KEY."') = :studentDataId
AND placement_date = :placementDate");
$query1->bindParam(":studentDataId", $studentDataId);
$query1->execute();
$query2 = $db->prepare("SELECT AES_DECRYPT(stu_id, '".KEY."')
FROM untracked_attendants
WHERE AES_DECRYPT(stu_id, '".KEY."') = :stuId
AND test_date = :placementDate");
$query2->bindParam(":stuId", $stuId);
$query2->execute();
// if the test date on the additional_data and untracked_attandants
// table for the current student is different from the date on the
// current submission, increment seats filled
if($query2->rowCount() == 0){
//Increment the number of seats filled for the test in question
$query = $db->prepare("UPDATE test_dates SET seats_filled = seats_filled + 1 WHERE id = :id");
$query->bindParam(":id", $id);
$query->execute();
//Check if the date should be closed off
$query = $db->prepare("SELECT date, location, seats_max, seats_filled FROM test_dates WHERE id = :id");
$query->bindParam(":id", $id);
$query->execute();
$row = $query->fetch();
if($row['seats_max'] == $row['seats_filled']) {
$query = $db->prepare("UPDATE test_dates SET active = 0 WHERE id = :id");
$query->bindParam(":id", $id);
$query->execute();
//Check if there's another room with the same date that should be opened automatically
//If this is true, activate the room
$query = $db->prepare("UPDATE test_dates SET active = 1 WHERE id != :id AND date = :date AND seats_max != seats_filled");
$query->bindParam(":id", $id);
$query->bindParam(":date", $row['date']);
$query->execute();
}
}
/*********************************************************************/
/*************************************************************************/
}
}
EDIT: Here is my schema
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
CREATE TABLE additional_data (
id int(11) NOT NULL AUTO_INCREMENT,
uid char(23) NOT NULL,
student_data_id blob NOT NULL,
placement_code int(2) NOT NULL,
sent_wr_to_english tinyint(1) NOT NULL,
mail_date date NOT NULL,
tests_needed varchar(20) NOT NULL,
placement_date date NOT NULL,
placement_room varchar(30) NOT NULL,
placement_time time NOT NULL,
orientation_date date NOT NULL,
orientation_group varchar(20) NOT NULL,
confirm_test tinyint(1) NOT NULL,
attended_test tinyint(1) NOT NULL,
rsvp_orientation tinyint(1) NOT NULL,
attended_orientation tinyint(1) NOT NULL,
tech_prep_complete tinyint(1) NOT NULL,
student_accounts tinyint(1) NOT NULL,
it_letters tinyint(1) NOT NULL,
sent_email_reminder tinyint(1) NOT NULL,
sent_august_mail tinyint(1) NOT NULL,
no_schedule tinyint(1) NOT NULL,
change_test date NOT NULL,
notes text NOT NULL,
honors tinyint(1) NOT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE student_data (
id int(11) NOT NULL AUTO_INCREMENT,
student_id blob NOT NULL,
last_name blob NOT NULL,
first_name blob NOT NULL,
address1 blob NOT NULL,
address2 blob NOT NULL,
city blob NOT NULL,
state blob NOT NULL,
zip blob NOT NULL,
major blob NOT NULL,
major2 blob NOT NULL,
sex blob NOT NULL,
student_type blob NOT NULL,
phone blob NOT NULL,
satr blob NOT NULL,
satm blob NOT NULL,
attdent_type blob NOT NULL,
gpa blob NOT NULL,
ptma blob NOT NULL,
ptwr blob NOT NULL,
ptre blob NOT NULL,
ptlg blob NOT NULL,
pths blob NOT NULL,
waiver blob NOT NULL,
tbrdepo_term_code blob NOT NULL,
goremal_email_address blob NOT NULL,
gobtpac_external_user blob NOT NULL,
download_date date NOT NULL,
PRIMARY KEY (id),
UNIQUE KEY student_id (student_id(16))
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE test_dates (
id int(11) NOT NULL AUTO_INCREMENT,
`date` datetime NOT NULL,
location varchar(30) NOT NULL,
seats_max tinyint(3) NOT NULL,
seats_filled tinyint(3) NOT NULL DEFAULT '0',
MA tinyint(1) NOT NULL,
RE tinyint(1) NOT NULL,
WR tinyint(1) NOT NULL,
LG tinyint(1) NOT NULL,
active tinyint(1) NOT NULL DEFAULT '1',
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE test_types (
id int(11) NOT NULL AUTO_INCREMENT,
test_type varchar(10) NOT NULL,
active tinyint(1) NOT NULL DEFAULT '1',
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE untracked_attendants (
id int(11) NOT NULL AUTO_INCREMENT,
uid char(23) NOT NULL,
fname blob NOT NULL,
lname blob NOT NULL,
stu_id blob NOT NULL,
email blob NOT NULL,
test_date date NOT NULL,
location varchar(30) NOT NULL,
test_time time NOT NULL,
retake tinyint(1) NOT NULL,
tests_needed varchar(20) NOT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE uploaded_exports (
id int(11) NOT NULL AUTO_INCREMENT,
filename varchar(255) NOT NULL,
uploaded timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE users (
id int(11) NOT NULL AUTO_INCREMENT,
username varchar(50) NOT NULL,
email varchar(100) NOT NULL,
`password` char(128) NOT NULL,
PRIMARY KEY (id),
KEY login (username,`password`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE writing_test_data (
id int(11) NOT NULL AUTO_INCREMENT,
uid char(23) NOT NULL,
student_id blob NOT NULL,
fname blob NOT NULL,
mi blob NOT NULL,
lname blob NOT NULL,
email blob NOT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Ok, so you have a student_id or an attendant_id. In additional data you reference these data to one of these with its id and maybe its type.
if you now want to enter a new record to additional data you just have to perform an duplicate check.
if untracked attendants have their own additional data somewhere, it should work the same.
it is the same principle with test dates. I think you should check your database/table scheme and the keys you are using for relations.

id incorrect in url

I am having problems with my foreign key in mysql.
My primary key (id) in Users should = user_id in language table.
Updated code:
CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`md5_id` varchar(200) NOT NULL,
`full_name` tinytext CHARACTER SET latin1 COLLATE latin1_general_ci NOT NULL,
`user_name` varchar(10) NOT NULL,
`user_email` varchar(30) NOT NULL,
`user_level` tinyint(4) NOT NULL DEFAULT '1',
`pwd` varchar(220) NOT NULL,
`nationality` varchar(30) NOT NULL,
`department` varchar(20) NOT NULL,
`birthday` date NOT NULL,
`date` date NOT NULL DEFAULT '0000-00-00',
`users_ip` varchar(200) NOT NULL,
`activation_code` int(10) NOT NULL DEFAULT '0',
`banned` int(1) NOT NULL,
`ckey` varchar(200) NOT NULL,
`ctime` varchar(220) NOT NULL,
`approved` int(1) NOT NULL DEFAULT '1',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
CREATE TABLE `language` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`native` varchar(30) NOT NULL,
`other` varchar(30) NOT NULL,
`other_list` varchar(9) NOT NULL,
`other_read` varchar(9) NOT NULL,
`other_spokint` varchar(9) NOT NULL,
`other_spokprod` varchar(9) NOT NULL,
`other_writ` varchar(9) NOT NULL,
PRIMARY KEY (`id`),
KEY `user_id` (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=9 ;
When I log in to the application, in the url the ID is correct (id1)= myaccount.php?id='%20.%201%20.'
However when I go to language.php and return back the url has changed to myaccount.php?id='%20.%203%20.'
Therefore the user id in language table is 3 when it should be 1!
Php code:
$result = mysql_query("SELECT `id` FROM `users` WHERE `banned` = '0' ORDER BY
`id` DESC");
$err = array();
if(isset($_SESSION['user_id'])) { }
if (!empty($_POST['doLanguage']) && $_POST['doLanguage'] == 'Submit')
{
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());
//set a cookie
if(isset($_POST['remember'])){
setcookie("user_id", $_SESSION['user_id'], time()+60*60*24*COOKIE_TIME_OUT, "/");
setcookie("user_key", sha1($ckey), time()+60*60*24*COOKIE_TIME_OUT, "/");
setcookie("user_name",$_SESSION['user_name'], time()+60*60*24*COOKIE_TIME_OUT, "/");
}
if(empty($err)) {
for($i = 0; $i < count($_POST["other"]); $i++)
{
$native = mysql_real_escape_string($_POST['native'][$i]);
$other = mysql_real_escape_string($_POST['other'][$i]);
$other_list = mysql_real_escape_string($_POST['other_list'][$i]);
$other_read = mysql_real_escape_string($_POST['other_read'][$i]);
$other_spokint = mysql_real_escape_string($_POST['other_spokint'][$i]);
$other_spokprod = mysql_real_escape_string($_POST['other_spokprod'][$i]);
$other_writ = mysql_real_escape_string($_POST['other_writ'][$i]);
$sql_insert = "INSERT into `language`
(`user_id`,`native`,`other`,`other_list`,`other_read`, `other_spokint`
,`other_spokprod`,`other_writ` )
VALUES
('$id','$native','$other','$other_list','$other_read','$other_spokint',
'$other_spokprod','$other_writ') ";
mysql_query($sql_insert,$link) or die("Insertion Failed:" . mysql_error());
}
header("location: myaccount.php?id=" . $_SESSION['user_id']. "");
exit();
}
I didn't read everything, but I see big problems here:
header("Location: myaccount.php?id=' . $_SESSION[user_id] .'");
Because:
you are inconsistently mixing single-quoted and double-quoted strings
you are accessing to a table index user_id by using a constant (user_id) instead of a string ('user_id')
Try instead:
header('Location: myaccount.php?id='.$_SESSION['user_id']);

Foreign Key not linking correctly

When registering my first user in table 'users' the id is the same value as user_id in the linking table,1, (language). However, when I register another user (id2 in users) the user_id in language is still 1. See SQL:
CREATE TABLE `language` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`native` varchar(30) NOT NULL,
`other` varchar(30) NOT NULL,
`other_list` varchar(9) NOT NULL,
`other_read` varchar(9) NOT NULL,
`other_spokint` varchar(9) NOT NULL,
`other_spokprod` varchar(9) NOT NULL,
`other_writ` varchar(9) NOT NULL,
PRIMARY KEY (`id`),
KEY `user_id` (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=9 ;
CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`md5_id` varchar(200) NOT NULL,
`full_name` tinytext CHARACTER SET latin1 COLLATE latin1_general_ci NOT NULL,
`user_name` varchar(10) NOT NULL,
`user_email` varchar(30) NOT NULL,
`user_level` tinyint(4) NOT NULL DEFAULT '1',
`pwd` varchar(220) NOT NULL,
`nationality` varchar(30) NOT NULL,
`department` varchar(20) NOT NULL,
`birthday` date NOT NULL,
`date` date NOT NULL DEFAULT '0000-00-00',
`users_ip` varchar(200) NOT NULL,
`activation_code` int(10) NOT NULL DEFAULT '0',
`banned` int(1) NOT NULL,
`ckey` varchar(200) NOT NULL,
`ctime` varchar(220) NOT NULL,
`approved` int(1) NOT NULL DEFAULT '1',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
This is my PHP code:
if(empty($_SESSION['$user_id'])) { // user not logged in; redirect to somewhere else }
if (!empty($_POST['doLanguage']) && $_POST['doLanguage'] == 'Submit')
{
$result = mysql_query("SELECT `id` FROM users WHERE `banned` = '0'") or
die (mysql_error());
list($id) = mysql_fetch_row($result);
session_start();
$_SESSION['user_id']= $id;
sql_insert = "INSERT into `language`
(`user_id`,`native`,`other`,`other_list`,`other_read`, `other_spokint`
,`other_spokprod`,`other_writ` )
VALUES
('$id','$native','$other','$other_list','$other_read','$other_spokint',
'$other_spokprod','$other_writ') ";
mysql_query($sql_insert,$link) or die("Insertion Failed:" . mysql_error());
}
header("Location: myaccount.php?id=' . $_SESSION[user_id] .'");
exit();
Would appreciate any help!
I think this is because your initial select query is selecting all users that are not banned
So need to change the query to filter by the new user:
"SELECT `id` FROM users WHERE `banned` = '0' and id=" . $_SESSION['$user_id'];
The reason why the user_id field kept getting populated as 1 was because mysql_fetch_row was getting the first record which was user id 1.
So if you filter it by the new user, mysql_fetch_row should get the id of the new user.
EDIT
I'm just looking at the code again, and it looks like you do not store the user id in php after you insert it, so your user_id for $_SESSION is null.
So my above example will not work. Instead of the above query, use the following function to get the id of your newly created user. You call this function after you run your insert query. That function will get the new of your newly created user.
mysql_insert_id()
http://php.net/manual/en/function.mysql-insert-id.php
EDIT 2
Ok, since mysql_insert_id() didn't work for you, maybe you can try the following. I just changed your select query to order by id desc.
$result = mysql_query("SELECT `id` FROM users WHERE `banned` = '0' order by id desc")
Just a note, this is probably not the best solution. But on a low traffic website it should be fine. To make the query a bit more accurate, you'd want to search for the user id based on a unique field like a username or email. This would make sure you get the correct id back.
EDIT 3
Here is an example of checking for the user's email. This is just the mysql query, you'll have to adjust this for php. Sorry I'm in class right now.
"SELECT `id` FROM users WHERE `banned` = '0' and email='user#email.com' limit 1

Categories