This is my table
And this is my php query code
// Check for unique username
$quser = "SELECT user_id FROM users
WHERE (username = '$u' AND email = 'e')
";
$ruser = mysqli_query($dbc, $quser) or die("MySQL error: " . mysqli_error($dbc) . "<hr>\nQuery: $quser");
if(mysqli_num_rows($ruser) == 0 ){
//do the INSERT INTO query
$q = " INSERT INTO users (lang_id, username, pass, email, active, registration_date)
VALUES ( '$l','$u', SHA1('$p'), '$e', '$a', NOW() )
";
}else{
echo 'That email address has already been registered.';
}
When I test it by entering the duplicate email address into the HTML form (assumed that the form validation is good), it returns error as shown below:
MySQL error: Duplicate entry 'email#domain.com ' for key 3
---------------------------------------------------------
Query: SELECT user_id FROM users WHERE (username = 'dsfdsf' AND email = 'e')
And of course, the value is NOT entered into the table yet.
These are the solutions I have been trying:
1/ I removed the unique indexes for username and email, data gets inserted, but still duplicated, which i NEVER expect.
2/ I tried duplicate username, but not email, the same error returns.
The question in my head now is why does it NOT returns my customized error message as in }else{ part, but the one generated by server or so?
Can you help? Thanks
Chaging your request to
$quser = "SELECT user_id FROM users
WHERE username = '$u'
or email = '$e'
";
should do the trick.
You missed a $ at email as well as this query only returned values if both are set... so only duplicate email or duplicate username wouldn't be catched.
Maybe you can catch these kind of errors with some exception handling to avoid bad luck on timing (2 processes are inserting data at the same time).
$ruser = mysqli_query($dbc, " SELECT * user_id FROM users
WHERE username like '$u' or email like '$e' ");
in the select Query Email should be $e and not just e
try
$res=mysql_query("select * from users
where username like '$u' or email like '$e' ");
if(mysql_num_rows($res)==0)
mysql_query(" insert into users
(lang_id, username, pass, email, active,registration_date) values
('$l','$u','$p','$e','$a',NOW()) ");
else
echo "Duplicate entry";
This may be the Error
Oh the problem is that you have user_id in your table as primary and it should be not be null , even user_level cannot be NULL, hence everytime you insert a new row you should insert a value for user_id and user_level
mysql_query(" insert into users
(lang_id, username, pass, email, active,registration_date,user_id,user_level)
values('$l','$u','$p','$e','$a',NOW(),$userid,'$user_level') ");
hope this solves your problem
Related
I need some help to figure out how to make a select from tables in multiple databases using Active Record in Codeigniter.
In details: I have two database; in the first one there is a table named users with all details about user (first name, last name and so on); in the second database there is a table named credit where there are credit info about each user; the user_id is the key that links the tables.
In the contruct Model I have:
public function __construct()
{
parent::__construct();
$this->rci_db = $this->load->database('dev', TRUE);
}
The query to select the data is:
$this->db->select ("
$this->t_users.user_id,
$this->t_users.username,
$this->t_users.first_name,
$this->t_users.last_name,
$this->t_users.email,
$this->t_users.lastlogin,
$this->t_contributers.user_id AS credit
");
$this->db->from($this->t_users);
$this->db->join($this->rci_db.$this->t_contributers, "$this->t_contributers.user_id = $this->t_users.user_id");
The query doesn't work and I get the following error:
Error Number: 1146
Table 'gavsit_data.rci_imgcontributers' doesn't exist
SELECT `users`.`user_id`, `users`.`username`, `users`.`first_name`, `users`.`last_name`, `users`.`email`, `users`.`lastlogin`, `rci_imgcontributers`.`user_id` AS `credit` FROM `users` JOIN `rci_imgcontributers` ON `rci_imgcontributers`.`user_id` = `users`.`user_id` ORDER BY `id` ASC
Filename: models/adm/Users_model.php
Thanks a lot for any hint...I really don't know how to figure out this issue.
EDIT:
I've edited the code splitting the select query, the error has gone but I got no data from the second DB:
$this->db->select ("
$this->t_users.id,
$this->t_users.username,
$this->t_users.first_name,
$this->t_users.last_name,
$this->t_users.email,
$this->t_users.last_login,
$this->t_users.active
");
$this->rci_db->select("
$this->t_contributers.user_id,
$this->t_contributers.cbtid
");
$this->db->from($this->t_users);
$this->rci_db->join("$this->t_contributers", "$this->t_contributers.user_id = $this->db.$this->t_users.id", 'left');
I am working on Zend Framework, got 1 problem in query, i want to fetch userid from tbl_user & want to check record with And in where clause
here is my query
$sql=$this->select()->from(users)->where('email = ? ', trim($email) , 'password = ?', md5(trim($password)) );
when i am printing query it prints
select * from users where email = 'test#gmail.com';
i want to print query like
select * from users where email = 'test#gmail.com' AND password='123456';
thanks in advance
You were close. You just need to call the where() method twice:
$this->select()->from(users)->where('email = ?', trim($email))
->where('password = ?', md5(trim($password)));
I'm trying to add a new mysql column in a table, using an insert_id from an insert of another table. This is the sentence that i use...
string sqlInsert = "INSERT INTO test (IdPico, Nombre, TextoBienvenida, FechaCreacion) VALUES (1, 'nombretest', 'aslkñdfa lsñdk asjd asldkf añlsj f', '2011-07-13 10:22:53'); ";
sqlInsert += "SET #IDTESTCREATED := CONCAT('Test', LAST_INSERT_ID(); ";
sqlInsert += "ALTER TABLE Usuarios ADD COLUMN #IDTESTCREATED BIT DEFAULT 0; ";
I using ASP.NET 4.0 and MySql connection, and server responds with 'Fatal error encountered during command execution. '
Could anybody help me?
Well ... I answer myself.
After making a deep search, I have not found how to add a column dynamically by a variable in mysql.
At end I had to make two querys, first to insert the test and get the id, and second to update the users table.
Since the insertion and retrieval of id are in the same query, no problems of persistent connections and concurrent updates.
string sqlInsert = "INSERT INTO Test (<fields>) VALUES (<values>);";
sqlInsert += "SELECT LAST_INSERT_ID() AS IdTestInserted; ";
string idnewtest = <result of insert query>;
string sqlAlter = "ALTER TABLE Users ADD COLUMN Test" + idnewtest + " BIT DEFAULT 0; ";
I regret not having found the answer, but at least I achieved my goal.
Thank you all for your help!
In my table I have an userID that is auto-incremented. In the same row I have an idHash. Is it possible to generate the idHash (simply an MD5 sum) from it directly with the same INSERT statement so that I don't have to SELECT the id, and then UPDATE the idHash again?
Problem is: I do not know the userID before it is being generated (auto-incremented) by MySQL.
Thanks
Frank
PS: I'm using PHP.
PPS: This question is all about a SINGLE INSERT. I know that I can use PHP or other languages to manually select the data and then update it.
I don't believe you can do it within a single INSERT statement.
What you probably could do is use an INSERT trigger, that both determines the new ID, hashes it, and then updates the record.
One solution I can recommend is using the last insert ID instead of re-querying the table. Here is a simplified example:
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "INSERT INTO users VALUES (....)";
$mysqli->query($query);
$newUserID = $mysqli->insert_id;
$query = "UPDATE users SET idHash = MD5(userID) WHERE userID = $newUserID";
$mysqli->query($query);
/* close connection */
$mysqli->close();
?>
AFAIK there's no "secure" way for doing this in the same query if you're using auto_increment.
However, if rows are never deleted in your table, you can use this little trick :
insert into mytable (col1, col2, col3, idhash)
values ('', '', '', md5(select max(id) from mytable))
I don't understand why you need to hash the id though, why not use the id directly ?
This seems to work for me:
CREATE TABLE tbl (id INT PRIMARY KEY AUTO_INCREMENT, idHash TEXT);
INSERT INTO tbl (idHash) VALUES (MD5(LAST_INSERT_ID() + 1));
SELECT *, MD5(id) FROM tbl;
Note this will only work on single-row inserts as LAST_INSERT_ID returns the insert ID of the first row inserted.
Performing MD5(column_name) on an auto_increment value does not work as the value has not been generated yet, so it is essentially calling MD5(0).
PHP snippet
<?
$tablename = "tablename";
$next_increment = 0;
$qShowStatus = "SHOW TABLE STATUS LIKE '$tablename'";
$qShowStatusResult = mysql_query($qShowStatus) or die ( "Query failed: " . mysql_error() . "<br/>" . $qShowStatus );
$row = mysql_fetch_assoc($qShowStatusResult);
$next_increment = $row['Auto_increment'];
echo "next increment number: [$next_increment]";
?>
This will get you the next auto-increment and then you can use this in your insert.
Note: This is not perfect (Your method is imperfect as you will effectively have 2 primary keys)
From: http://blog.jamiedoris.com/geek/560/
How can I check if email = '$e' or username = '$e' inside my MySQL query.
Here is my MySQL query so far.
"SELECT user_id FROM users WHERE (email = '$e' AND pass=SHA1('$p'))"
If you want to modify you existing query so that it works even if $e matches username, you can do:
SELECT user_id
FROM users
WHERE (email = '$e' OR username = '$e') AND pass=SHA1('$p')