id incorrect in url - php

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']);

Related

Error in query: Cannot delete or update a parent row: a foreign key constraint fails

I am trying to delete the contents from 3 tables which are associated with a certain User ID and I get the following error:
Error in query: Cannot delete or update a parent row: a foreign key constraint fails (`MyName_4.2c`.`tbl_reservation`, CONSTRAINT `tbl_reservation_ibfk_2` FOREIGN KEY (`propertyId`) REFERENCES `tbl_property` (`propertyId`))
Code:
<?php
session_start();
$userId = $_GET['userId'];
require_once('databaseConn.php');
$query = "DELETE FROM tbl_reservation WHERE userId = '$userId'";
$result = mysqli_query($connection, $query)
or die("Error in query: ". mysqli_error($connection));
$query2 = "DELETE FROM tbl_property WHERE userId = '$userId'";
$result2 = mysqli_query($connection, $query2)
or die("Error in query: ". mysqli_error($connection));
$query3 = "DELETE FROM tbl_users WHERE userId = '$userId'";
$result3 = mysqli_query($connection, $query3)
or die("Error in query: ". mysqli_error($connection));
header('Location: index.php');
?>
My Tables:
CREATE TABLE `tbl_property` (
`propertyId` int(11) NOT NULL,
`userId` int(11) NOT NULL,
`title` varchar(50) NOT NULL,
`capacity` int(11) NOT NULL,
`pricePerNight` double NOT NULL,
`locationId` int(11) NOT NULL,
`image` varchar(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE `tbl_reservation` (
`reservationId` int(11) NOT NULL,
`propertyId` int(11) NOT NULL,
`date_from` date NOT NULL,
`date_to` date NOT NULL,
`amountPaid` double NOT NULL,
`userId` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE `tbl_users` (
`userId` int(11) NOT NULL,
`name` varchar(50) NOT NULL,
`surname` varchar(50) NOT NULL,
`email` varchar(50) NOT NULL,
`password` varchar(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE `tbl_location` (
`locationId` int(11) NOT NULL,
`location` varchar(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

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

mysql MAX() returns 0 instead of actual value

The following code returns 0 instead of the biggest number from the row order_id
if ($result_oid = $link->prepare("SELECT MAX(order_id) AS order_id FROM $table")) {
$result_oid->execute();
$obj = $result_oid->get_result()->fetch_object();
$oid_o = $obj->id;
$result_oid->close();
$oid = $oid_o + 1;
}
Here is a working example using the PHP mysql instead of mysqli (with the same mysql database):
mysql_connect($host, $user, $pwd) or die ("Couldn't connect to MySQL database.");
mysql_select_db($db) or die ("No Database found!");
$query = mysql_query('SELECT MAX(order_id) FROM airsale_list');
$result = mysql_fetch_array($query, MYSQL_NUM);
$max_order_id = $result[0];
$max_order_id = (int)$max_order_id;
$oid = $max_order_id++;
echo "<h4>order_id: $oid</h4>";
mysql_close();
Table structure
CREATE TABLE IF NOT EXISTS `airsale_list` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`cat` int(11) NOT NULL,
`title` varchar(255) NOT NULL,
`desc_small` varchar(1000) DEFAULT NULL,
`name` varchar(255) NOT NULL,
`lastupdate` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`price` int(20) NOT NULL,
`currency` varchar(3) NOT NULL DEFAULT 'EUR',
`total_time` varchar(255) DEFAULT NULL,
`engine` varchar(1000) DEFAULT NULL,
`engine_time` varchar(255) DEFAULT NULL,
`prop` varchar(1000) DEFAULT NULL,
`prop_time` varchar(255) DEFAULT NULL,
`exterior` varchar(2000) DEFAULT NULL,
`interior` varchar(2000) DEFAULT NULL,
`avionics` varchar(5000) DEFAULT NULL,
`add_info` varchar(5000) DEFAULT NULL,
`order_id` int(20) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=103;
I think you should be using $obj->order_id instead of $obj->id since you are grabbing the maximum value as order_id in the query.
if ($result_oid = $link->prepare("SELECT MAX(order_id) AS order_id FROM $table")) {
$result_oid->execute();
$obj = $result_oid->get_result()->fetch_object();
$oid_o = $obj->order_id;
$result_oid->close();
$oid = $oid_o + 1;
}

Why mysql_insert_id returns 0 in my case?

This is my table:
CREATE TABLE `users` (
`id` int(10) unsigned NOT NULL auto_increment,
`name` varchar(20) NOT NULL default '',
`pass` varchar(32) NOT NULL default '',
`lang` varchar(2) default NULL,
`locale` varchar(2) default NULL,
`pic` varchar(255) default NULL,
`sex` char(1) default NULL,
`birthday` date default NULL,
`mail` varchar(64) default NULL,
`created` timestamp NOT NULL default CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `mail` (`mail`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=27 ;
And this is my query:
$query = "INSERT IGNORE INTO `users` (`name`, `mail`, `birthday`, `lang`, `locale`, `sex`, `pic`) VALUES ('".$name."', '".$email."', '".date_format($birthdaynew, 'Y-m-d H:i:s')."', '".substr($locale, 0, 2)."', '".substr($locale, -2, 2)."', '".$sex."', 'pic/".$uid.".jpg')";
$rows = mysql_query($query) or die("Failed: " . mysql_error());
$_SESSION['id'] = mysql_insert_id(); // I have tryed also mysql_insert_id($db_con) where $db_con is the link to db.
$_SESSION['name'] = $name;
$_SESSION['name'] contains correctly the name but $_SESSION['id'] contains 0.
Why ?
I'm going crazy!
Is there a particular reason why you are using INSERT IGNORE?
If you use INSERT IGNORE, then the row won't actually get inserted if there is a duplicate key (PRIMARY or UNIQUE), or inserting a NULL into a column with a NOT NULL constraint.
Referring to the pass column, as you have not defined anything to insert into it, and it has NOT NULL constraint.
EDIT:
Referring also to the mail column, as you have a UNIQUE constraint on it.

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