PHP MySQL, check for duplicates in two tables - php

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.

Related

Save and update with uniqid in database

I tried to insert the player with a unique id in the database.
This model works for me, but if I give it a key update it duplicates it in my database.
Option 1
$id = uniqid();
$insert_player_query = mysqli_query($db,"INSERT INTO players (id,nickname,score,time_online,mapname,sid) VALUES ('$id','$player_nickname','$player_score','$player_time','$mapname','$server_id') ON DUPLICATE KEY UPDATE score = score + VALUES(score), time_online = time_online + VALUES(time_online) WHERE id='$id'");
Option 2
Then I tried that, but it doesn't insert anything at all
$id = uniqid();
$sql=mysqli_query($db, "SELECT * FROM players WHERE nickname='$player_nickname'");
if (mysqli_num_rows($sql) > 0)
{
$insert_player_query2 = mysqli_query($db,"UPDATE players (nickname,score,time_online,mapname,sid) VALUES ($player_nickname','$player_score','$player_time','$mapname','$server_id') WHERE id='$id'");
} else {
$insert_player_query = mysqli_query($db,"INSERT INTO players (id,nickname,score,time_online,mapname,sid) VALUES ('$id','$player_nickname','$player_score','$player_time','$mapname','$server_id') WHERE id='$id'");
}
Remove "where" condition. It does not make any sense in "INSERT" statement.
You should check field and use:
CREATE TABLE `players` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`nickname` varchar(100) DEFAULT NULL,
`score` int(11) DEFAULT NULL,
`time_online` varchar(100) DEFAULT NULL,
`mapname` varchar(100) DEFAULT NULL,
`sid` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `uniq` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
INSERT INTO players (id,nickname,score,time_online,mapname,sid) VALUES ('1','player_nickname','1','1','mapname','1')
ON DUPLICATE KEY UPDATE score = score + VALUES(score), time_online = time_online + VALUES(time_online)
Please try it.

PDO query updating a datetime column not in query

A PDO prepared update statement is somehow updating the datetime column for the selected record in the table, even though that particular datetime column is not even in the query.
if(isset($_POST['editCriteria']))
{
$value = $_POST['editCriteria'];
$editusername = $value['editusername'];
$hiddenUsername = $value['hiddenUsername'];
$editfullname = $value['editfullname'];
$editemail = $value['editemail'];
$edituserlevel = $value['edituserlevel'];
$editdivision = $value['editdivision'];
$editdept = $value['editdept'];
$editphone = $value['editphone'];
try
{
$dbc->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$update = $dbc->prepare("UPDATE users_edi SET username = :uname,
fullname = :fname, userlevel = :ulevel, email = :uemail,
division = :udivision, dept = :udept, phone = :uphone WHERE username = :hname");
$update->execute([
'uname' => $editusername,
'fname' => $editfullname,
'ulevel' => $edituserlevel,
'uemail' => $editemail,
'udivision' => $editdivision,
'udept' => $editdept,
'uphone' => $editphone,
'hname' => $hiddenUsername
]);
if($update)
{
echo "Success: User has been updated.";
}
}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
}
In the database table, there is a column called lastLoginDate that is being updated to the current datetime.
If you'll notice in the update statement above, the query does not include lastLoginDate.
How is lastLoginDate being updated when it's not even in the query?
Upon using the SHOW CREATE TABLE command, there was indeed a trigger on the lastLoginDate column.
CREATE TABLE `users_edi` (
`username` varchar(30) NOT NULL DEFAULT '',
`fullname` varchar(50) DEFAULT NULL,
`userlevel` tinyint(1) unsigned NOT NULL,
`ipaddress` varchar(30) DEFAULT NULL,
`email` varchar(150) DEFAULT NULL,
`entrydate` datetime DEFAULT NULL,
`division` varchar(35) DEFAULT NULL,
`password` varchar(32) DEFAULT NULL,
`userid` varchar(32) DEFAULT NULL,
`timestamp` int(11) unsigned NOT NULL,
`job_title` varchar(30) DEFAULT NULL,
`dept` varchar(50) DEFAULT NULL,
`phone` varchar(11) DEFAULT NULL,
`lastLoginDate` datetime DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP, // <-- here
PRIMARY KEY (`username`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
I will have to ask another question on how to remove this trigger.

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) )

Database trouble and php trouble

I am having trouble with my create a table .php script, It creates all tables in the database except one which is 'useroptions'. I am new to php but still understand it to an extent, feedback and help would be greatly appreciated.
<?php
include_once("php_includes/db_connect.php");
$tbl_users = "CREATE TABLE IF NOT EXISTS users (
id INT(11) NOT NULL AUTO_INCREMENT,
firstname VARCHAR(100) NOT NULL,
lastname VARCHAR(100) NOT NULL,
email VARCHAR(255) NOT NULL,
password VARCHAR(255) NOT NULL,
gender ENUM('m','f') NOT NULL,
avatar VARCHAR(255) NULL,
ip VARCHAR(255) NOT NULL,
signup DATETIME NOT NULL,
lastlogin DATETIME NOT NULL,
notescheck DATETIME NOT NULL,
activated ENUM('0','1') NOT NULL DEFAULT '0',
PRIMARY KEY (id),
UNIQUE KEY email (email)
)";
$query = mysqli_query($db_connect, $tbl_users);
if ($query === TRUE) {
echo "<h3>user table created OK :) </h3>";
} else {
echo "<h3>user table NOT created :( </h3>";
}
////////////////////////////////////
$tbl_useroptions = "CREATE TABLE IF NOT EXISTS useroptions (
id INT(11) NOT NULL,
question VARCHAR(255) NULL,
answer VARCHAR(255) NULL,
PRIMARY KEY (id),
UNIQUE KEY email (email)
)";
$query = mysqli_query($db_connect, $tbl_useroptions);
if ($query === TRUE) {
echo "<h3>useroptions table created OK :) </h3>";
} else {
echo "<h3>useroptions table NOT created :( </h3>";
}
////////////////////////////////////
$tbl_friends = "CREATE TABLE IF NOT EXISTS friends (
id INT(11) NOT NULL AUTO_INCREMENT,
user1 VARCHAR(100) NOT NULL,
user2 VARCHAR(100) NOT NULL,
datemade DATETIME NOT NULL,
accepted ENUM('0','1') NOT NULL DEFAULT '0',
PRIMARY KEY (id)
)";
$query = mysqli_query($db_connect, $tbl_friends);
if ($query === TRUE) {
echo "<h3>friends table created OK :) </h3>";
} else {
echo "<h3>friends table NOT created :( </h3>";
}
////////////////////////////////////
$tbl_blockedusers = "CREATE TABLE IF NOT EXISTS blockedusers (
id INT(11) NOT NULL AUTO_INCREMENT,
blocker VARCHAR(100) NOT NULL,
blockee VARCHAR(100) NOT NULL,
blockdate DATETIME NOT NULL,
PRIMARY KEY (id)
)";
$query = mysqli_query($db_connect, $tbl_blockedusers);
if ($query === TRUE) {
echo "<h3>blockedusers table created OK :) </h3>";
} else {
echo "<h3>blockedusers table NOT created :( </h3>";
}
////////////////////////////////////
$tbl_status = "CREATE TABLE IF NOT EXISTS status (
id INT(11) NOT NULL AUTO_INCREMENT,
osid INT(11) NOT NULL,
account_name VARCHAR(100) NOT NULL,
author VARCHAR(100) NOT NULL,
data TEXT NOT NULL,
postdate DATETIME NOT NULL,
PRIMARY KEY (id)
)";
$query = mysqli_query($db_connect, $tbl_status);
if ($query === TRUE) {
echo "<h3>status table created OK :) </h3>";
} else {
echo "<h3>status table NOT created :( </h3>";
}
////////////////////////////////////
$tbl_photos = "CREATE TABLE IF NOT EXISTS photos (
id INT(11) NOT NULL AUTO_INCREMENT,
user VARCHAR(100) NOT NULL,
gallery VARCHAR(16) NOT NULL,
filename VARCHAR(255) NOT NULL,
description VARCHAR(255) NULL,
uploaddate DATETIME NOT NULL,
PRIMARY KEY (id)
)";
$query = mysqli_query($db_connect, $tbl_photos);
if ($query === TRUE) {
echo "<h3>photos table created OK :) </h3>";
} else {
echo "<h3>photos table NOT created :( </h3>";
}
////////////////////////////////////
$tbl_notifications = "CREATE TABLE IF NOT EXISTS notifications (
id INT(11) NOT NULL AUTO_INCREMENT,
firstname VARCHAR(100) NOT NULL,
initiator VARCHAR(100) NOT NULL,
app VARCHAR(255) NOT NULL,
note VARCHAR(255) NOT NULL,
did_read ENUM('0','1') NOT NULL DEFAULT '0',
date_time DATETIME NOT NULL,
PRIMARY KEY (id)
)";
$query = mysqli_query($db_connect, $tbl_notifications);
if ($query === TRUE) {
echo "<h3>notifications table created OK :) </h3>";
} else {
echo "<h3>notifications table NOT created :( </h3>";
}
?>
Also I'm getting this error when I click on database ?
Error
SQL query:
SELECT tracking_active
FROM `phpmyadmin`.`pma_tracking`
WHERE db_name = 'circle'
AND table_name = 'blockedusers'
ORDER BY version DESC
MySQL said:
1146 - Table 'phpmyadmin.pma_tracking' doesn't exist
Your useroptions create table statement has an invalid unique key ref: UNIQUE KEY email (email). There is no column email on useroptions. Remove it and it will likely run clean.
As for the query issue, not really sure what you're trying to do.

id not changing correctly

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.

Categories