I am writing the following command in php:
$query="insert into tableone (user_name, password, name, email) values('$user_name', '$password', '$name', '$email')";
if(mysql_query($query))
{
header("Location:thislocation.php");
} else {
echo '<br><br><font color="red"><strong>Username or EmailId already exists. Please try different Username.<br> If you have forgotten your Password <u><i>click here</i></u>.</strong></font><br>';
}
Here in mysql-db I have made name and email field as unique and id as auto increment, so that no two people have same registration records. The problem is that, if someone uses same username or email, the query fails and else statement is executed. But, it auto-increments the id, without getting records added in db. If someone after that registers successfully, he gets an id not 2 more than the previous one.
How to get auto-incremented just once?
There's no real fix; this is how auto-increment IDs work. IDs are not designed to be "clean", they're designed to fullfill a need to be able to link data together.
It'll be a huge amount of work for your database to keep them in order and (here's the most important part) nobody cares about whether they're aligned anyway. They're numbers without a real-world meaning (by definition of being a database ID) so nothing about them should matter.
The only reason they're "in order" normally is because it's an easy way to generate them.
What you need to do is run an num_rows on it, before you insert it. what num_rows do, it count how many records the SELECT returns, so if it returns 1, there is a place in the database where there are a match, if it returns 0, there are no match
$selectSql = "SELECT * FROM tableone WHERE name= '".$name."' OR email = '".$email."'";
$result = mysql_query($selectSql, $YOUR_DATABASECONNECTION);
$num_rows = mysql_num_rows($result);
if($num_rows){
echo "email or name is already taken";
}else{
$query="insert into tableone (user_name, password, name, email) values('$user_name', '$password', '$name', '$email')";
if(mysql_query($query))
{
header("Location:thislocation.php");
} else {
echo '<br><br><font color="red"><strong>Username or EmailId already exists. Please try different Username.<br> If you have forgotten your Password <u><i>click here</i></u>.</strong></font><br>';
}
}
This is a good way to secure, that the error you're talking about wont happend
Related
i have an customers i want to add IP address to these customers
i used loop $i=254 to add ip address automatically
but it's give 1.1.2.254 to all the customers how can i fixing it
i need to make loop if the 1.1.2.254 is existing for customer 1 !! use the next 1.1.2.253 for customer 2
$i=254
$res = MySQL_query("INSERT INTO `rm_users`(`username`, `staticipcpe`) VALUES ('$username', '1.1.2.$i');
$i--
use ip unique in db to insert and failure if ip is exiting
now using for($i=254;$i > 0;$i--){ $res = mysql_query("INSERT INTO `rm_users`(`username`, `staticipcpe`) VALUES ('$username', '1.1.2.$i')"); }
and it's working good
The question is a little incomplete and incorrect, but I think you have an IP address from the input or elsewhere. You can search this address with a query.
SELECT EXISTS(SELECT * FROM table1 WHERE ...)
this will return you a true or false value. You can browse the detailed document and similar question
Best way to test if a row exists in a MySQL table
https://dev.mysql.com/doc/refman/8.0/en/exists-and-not-exists-subqueries.html
for($i=254;$i > 0;$i--){
$res = mysql_query("INSERT INTO `rm_users`(`username`, `staticipcpe`) VALUES ('$username', '1.1.2.$i')");
}
this will do the trick!!!. This loop will insert upto 1.1.2.1
I have been trying to prevent any user from registering an email that is already registered in the database. I couldn't. Maybe it's because I have to check three tables at the same time. I tried but failed. I hope you are able to help me.
//Check whether Email exists or not
$check="SELECT * FROM admins, engineers, users WHERE admins.Email='$email' OR engineers.Email='$email' OR users.Email='$email'";
$results=mysql_query($check);
//Confirm that the Email doesn't exist
if(mysql_num_rows($results) == 0)
{ $check='true'; }
//Error message to the user that the Email already exists.
else
{
header("location: register.php?email=false");
}
//Register the data
if($check=='true')
{
mysql_query("INSERT INTO admins (Admin, Password, Email, Phone, Date, Time) VALUES ('$username', '$password','$email', '$phone', '$date', '$time')");
header("location: login.php?register=success");
}
Use UNION rather than a cross-product.
SELECT 1 FROM admins WHERE email = '$email'
UNION
SELECT 1 FROM engineers WHERE email = '$email'
UNION
SELECT 1 FROM users WHERE email = '$email'
The cross-product will only work if it finds matches in all the tables, not just one of them.
You can make your life easier by storing all emails in one table. You can use a column named for example 'type' which would then be admin, user or engineer. This makes your lookups much easier instead of having to look through multiple tables.
I'm trying to upload data to a existing User database I have stored online. I need to post the user phone number string in the user specified row. Using android and php, is there any way to post extra info in an existing row?
I think I'm not choosing WHERE to put that extra info.
<?php
require "indioPhP.php";
$username = $_POST["username"];
$phoneNumber = $_POST["phoneNumber"];
$statement = mysqli_prepare($con, "SELECT * FROM User WHERE username = ?");
mysqli_stmt_bind_param($statement, "s", $username);
mysqli_stmt_execute($statement);
$sql ="insert into User values('$phoneNumber')";
if(mysqli_query($con,$sql)){
echo "Gracias por registrarte!";
} else{
echo "error in insertion".mysqli_error($con);
}
?>
Ok now i see your Problem:
Update User set phonenumber=? where username=?
You Need something like this ? it's only one query where you search the user and Change it. Try to read more about SQL. Your code Looks a bit confused, with prepared Statements and normal statments in the same block.
Edit:
The statement insert adds a new line in the table wheras update modifies an existing one. Assuming your table User has 4 columns: username, firstname, lastname, phonenumber, for insert, the syntax is either
insert into user values("jdoe", "John", "Doe", "555 7565")
or
insert into user(username, phonenumber) values ("jdoe", "555 7565")
In the first case, as columns are not specified, you must give all of them.
In the second case, you insert a new line specifying only some columns. The other ones will take their default values. If a missing column doesn't have a default value, you will have an error.
Right now I have 2 tables. A comment table and a user table. Short and simple, I wanna sent a comment to all users. I need to know the sql command for it and how to display on PHP.
Comment table
pk
comment
sender (refers to username)
receiver (refers to username)
User table
pk
username
etc.....
I tried using this:
$provider = $_REQUEST['provider'];
$cert = $_REQUEST['cert'];
$valid = $_REQUEST['valid'];
$lprice = $_REQUEST['lprice'];
$trial = $_REQUEST['trial'];
$cost = $_REQUEST['cost'];
echo $cert;
$sql=mysql_query("SELECT * FROM sslcert WHERE CertificateName='$cert'",$connect);
if(mysql_num_rows($sql)>0)
{
echo"SSL already exists.";
echo "<br><a href=addssl.php>Back</a>";
}
else
{
$insert = mysql_query("INSERT INTO sslcert (Provider, CertificateName, Validation,
ListPrice, Trial, Cost) VALUES ('$provider', '$cert', '$valid', '$lprice',
'$trial', '$cost')",$connect);
$result77=mysql_query("SELECT username FROM user");
while($row77=mysql_fetch_array($result77))
{
$insert1 = mysql_query("INSERT INTO notification (msg, sender, receiver, notification) VALUES ('A new product is now available, $cert by $provider', '$username', '$row77['username']', 1)");
if(!$insert1){
die("There's little problem: ".mysql_error());
echo "<br><a href=quotesmanage1.php>Back</a>";
}
}
if(!$insert){
die("There's little problem: ".mysql_error());
echo "<br><a href=addssl.php>Back</a>";
}
echo "<br>You have add a new Product <br><a href=adminhome.php>Back to Home</a>";
}
mysql_close($connect);
}
the call for username is somewhere else on the page.
It came out with a blank page (error on php), any ideas?
I believe you want a INSERT...SELECT query.
INSERT INTO `Comment`(`Comment`.`comment`, `Comment`.`sender`, `Comment`.`receiver`)
SELECT 'Message as text or variable substitution', `User`.`pk`, '1'
FROM `User`
You can substitute any ID instead of 1 at the end of the SELECT line, I just figured your administrative user is probably 1 (but you can create a new user for sending these mass messages and just use whatever number ID corresponds.
By the way, in your comment table you should probably reference User.pk, not User.username. That's sort of why you have the key in the first place :-)
For some reason my insert/update check only ever inserts. the value userID does have a value so i dont know what is up with this. Any ideas?
$result = mysql_query("SELECT * FROM users where userID = $userID ");
if (mysql_num_rows($result) > 0) {
mysql_query("UPDATE users SET firstName='$firstName', lastName='$lastName',
birthday='$birthday', update='$today', accessToken='$accessToken', emailOne='$emailOne' WHERE userID='$userId'");
} else {
mysql_query("INSERT INTO users (userID, firstName, lastName, birthday, updated, accessToken, emailOne )
VALUES ('$userId', '$firstName', '$lastName','$birthday', '$today', '$accessToken', '$emailOne')");
}
You'd be far better off doing INSERT ... ON DUPLICATE KEY UPDATE. Your version is subject to race conditions. It's entirely possible that between the time you do the SELECT * and then attempt the update/insert queries, ANOTHER script has already inserted the same ID number and then your script breaks. This also reduces the database load by one query.
As well, unless you've passed all those variables in the query through mysql_real_escape_string(), you'll probably be getting a visit from Little Bobby Tables.
From the way you're inserting the records, it seems that your userId field is a varchar (or alphanumeric) field. So your query NEVER reads the data that matches it since it is searching for it as a numeric. You've got to re-write the first line as:
$result = mysql_query("SELECT * FROM users where userID = '$userID' ");
Hope it helps.