Check if name already exist - php

I have this code.
This code can check if form number is already existing in the database.
Now i want to check if the firstname and lastname is already existing.what and where should i
$FNresult = mysql_query("SELECT COUNT(*) FROM profile WHERE FormNo = '$FrmN' ");
if (!$FNresult) {
die(mysql_error());
}
if (mysql_result($FNresult, 0, 0) > 0) {
echo "<br>Form number already exist!";
}
else {
$sql = "INSERT INTO profile
(FormNo, FirstName, LastName, Address, Email, MobileNo,
LandlineNo, Amount, Term, Manner)
VALUES ('$FrmN', '$FN', '$LN', '$ADD', '$E', '$MOBILE',
'$LAND', '$AMNT', '$TRM', '$MNNR')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "<br>1 record added!";
}
mysql_close($con);

$sql = mysqli_query("SELECT firstname,lastname FROM profile WHERE firstname = '$firstname' and lastname = '$lastname'");
$rownum = mysqli_num_rows($sql);
if( $rownum > 0 )
die('Your name already exists in database');
Note = I wrote mysqli_* but you are using mysql_*
You can change it depending on how you want it to be.
You should change your mysql_* to mysqli_* as the first one has been deprecated and will be deleted in the future
Something similar to the code above must do the trick.
Good Luck

Related

Duplication of record on insert in php, mysql

I notice sometimes that there are duplicated data when inserting in the database. It doesn't always happen but what might be the issue here? Here is my code.
$sql = $conn->query("INSERT INTO registration(lrn, department_id, fname, mname, lname, contact_no, email, persontocontact, emergency_contact, agreement, statuss) VALUES('".$_POST['userid']."','".$_POST['departmentid']."', '".$_POST['fname']."', '".$_POST['mname']."', '".$_POST['lname']."', '".$_POST['contact_no']."','".$_POST['email']."', '".$_POST['persontocontact']."', '".$_POST['emergency_contact']."', '".$_POST['agreement']."', 'pending')");
if($sql->rowCount() > 0){
echo "success";
}
It only happens sometimes means it is not the code that is doing it but the user actions like refresh on that page.
You should make it much more secure and handle the refresh situation but to answer to your question use this code.
$checkid = $_POST['userid'];//Specifically taking it here so you can know this is what we are looking for.
$sql = $conn->query("Select * from registration WHERE lrn = '$checkid'");
if($sql->rowCount() > 0){
echo "User Already Exists";
}
else
{//Move forward
$sql = $conn->query("INSERT INTO registration(lrn, department_id, fname, mname, lname, contact_no, email, persontocontact, emergency_contact, agreement, statuss) VALUES('".$_POST['userid']."','".$_POST['departmentid']."', '".$_POST['fname']."', '".$_POST['mname']."', '".$_POST['lname']."', '".$_POST['contact_no']."','".$_POST['email']."', '".$_POST['persontocontact']."', '".$_POST['emergency_contact']."', '".$_POST['agreement']."', 'pending')");
if($sql->rowCount() > 0){
echo "success";
}
}//Main if closes here

Cannot insert data in SQL table when using the same code as previous query

I need to insert two pieces of data into two different tables. It successfully does it with one of the tables but not the second. I have used or die mysqli_error to see if it will tell me the error, but it does not show anything. See the code below:
$sql = "INSERT INTO ticketUsers
(name, emailAddress, password)
SELECT * FROM (SELECT '$name', '$emailAddress', '$dbPassword') AS tmp
WHERE NOT EXISTS (
SELECT name
FROM ticketUsers
WHERE emailAddress = '$emailAddress'
)
LIMIT 1";
$query = mysqli_query($connection, $sql);
if($query)
{
echo "Success entering ticket Users";
}
else if(!$result)
{
echo "Cant enter information";
}
$sql = "INSERT INTO tickets
(id, emailAddress, urgency, subject,
description, relevantURL, status)
VALUES ('$id', '$emailAddress', '$username', '$urgency',
'$subject', '$description2', '$relevantURL', 'Open')";
$query = mysqli_query($connection, $sql);
if($query)
{
echo "Success entering tickts";
}
else if(!$result)
{
echo "Cant enter information";
}
if (!sql)
{
echo "There has been an error creating your ticket.";
}
In your second query, you try to insert in a table with 7 fields 8 values.
I think you don't want to insert '$username' in the query.

PHP/MySQLi Not finding existing user

For some reason, the code seems to not be able to find any existing usernames. I can't find anything wrong with my code though. Any help will be appreciated.
$Name = $_POST["User"];
$Pass = $_POST["Pass"];
$get = "SELECT * FROM Logins";
$result = mysqli_query($conn, $get);
$found = false;
echo $Name;
$sql=mysqli_query("SELECT FROM Logins (ID, Username, Password) WHERE Username=$Name");
if(mysqli_num_rows($sql) > 0) {
echo "Username Taken";
} else {
$sql = "INSERT INTO Logins (ID, Username, Password) VALUES (0, '$Name', '$Pass')";
if (mysqli_query($conn, $sql)) {
echo "Account Created";
} else {
echo mysqli_error($conn);
}
}
When I post to the site, $Name is correct.
You have an incorrect syntax near your select statement. It's
SELECT FROM Logins (ID, Username, Password) WHERE Username=$Name")
You need:
SELECT ID, Username, Password
FROM Logins
WHERE Username='$Name'
Also note, you should be using prepared statement which will avoid need for quotes and will avoid your code vulnerable from SQL Injection.

add mysql row if userID do not exist in table

i'm sending a post request to this code:
$name = (string)$_POST['name'];
$id = (int)$_POST['id'];
$query = "INSERT INTO Users (name, userID) VALUES ('$name', '$id')";
$result = mysqli_query($link,$query);
Which works fine and it adds a row to the table. How do i check wether the userID all ready exist in one of the following rows?
Do it like this
$query = "SELECT COUNT(*) FROM Users WHERE userID = '$id'";
$result = mysqli_query($link,$query);
if ( mysqli_fetch_assoc($result) ) {
$message = "Already exists";
} else {
$query = "INSERT INTO Users (name, userID) VALUES ('$name', '$id')";
$result = mysqli_query($link,$query);
}
Try this
$name = (string)$_POST['name'];
$id = (int)$_POST['id'];
$res = mysqli_query($link, "SELECT * FROM Users WHERE userID = '$id' LIMIT 1 ");
if($row = mysqli_fetch_assoc($res))
{
echo "this user id is already exists";
}
else
{
$query = "INSERT INTO Users (name, userID) VALUES ('$name', '$id')";
$result = mysqli_query($link,$query);
echo "record inserted successfully ";
}
REMEMBER : always use LIMIT 1 when you trying to get exactly one result.
IF you have properly set 'id' as primary key or unique key in your table, you can use the modifier IGNORE in your query you don't get an error when you try to isert a duplicate.
Doing this will result in the row only being inserted if the value of the primary key wasn't already in the table.
$query = "INSERT IGNORE INTO Users (name, userID) VALUES ('$name', '$id')";
IF you haven't set a primary key in your table you will have to do a SELECT query to find out if a row with that id is already in your table.
Make the UserID an Unique Key.
If it already exists, your code will throw an error and the row will not be insterted.
alter table Users
add unique index Unique_user (userID (8000))
Before inserting the values to the table check whether the following user id exists in the table or not
You can do it in this way
$name = $_POST['name'];
$id = $_POST['id'];
$sql = "SELECT * FROM Users WHERE userID = '$id'";
$res= mysqli_query($sql);
$num = mysqli_num_rows($res);
if($num == 0)
{
$query2 = "INSERT INTO Users (name, userID) VALUES ('$name', '$id')";
$result2 = mysqli_query($query2);
echo "record inserted successfully ";
}
else
{
echo "Record Failed !!";
}

PHP, Error 1136 : Column count doesn't match value count at row 1 [duplicate]

This question already has answers here:
PHP, MySQL error: Column count doesn't match value count at row 1
(3 answers)
Closed 9 years ago.
I get this Exception:
Error 1136 : Column count doesn't match value count at row 1
Structure of the table :
create table gb_entries (
id int(4) not null auto_increment,
username varchar(40) not null,
name varchar(40),
gender varchar(40),
dob int(40),
email varchar(40),
primary key (id)
);
With this PHP code:
// Add a new entry to the database
function addEntry($username, $name, $gender, $dob, $email) {
$connection = mysql_open();
$insert = "insert into gb_entries " .
"values ('$username', '$name', '$gender', '$dob', '$email')";
$result = # mysql_query ($insert, $connection)
or showerror();
mysql_close($connection)
or showerror();
}
// Return an array of database entries that contain $name anad $email
function getEntries($username,$name,$gender,$dob,$email) {
// Sanitise user input to prevent SQL injection attacks
$username = mysql_escape_string($username);
$name = mysql_escape_string($name);
$gender = mysql_escape_string($gender);
$dob = mysql_escape_string($dob);
$email = mysql_escape_string($email);
// Open connection and select database
$connection = mysql_open();
// Construct query
$query =
"select username, name, gender, dob, email from gb_entries where 0=0 ";
if (! empty($username)) {
$query .= "AND username LIKE '%$username%' ";
}
if (! empty($name)) {
$query .= "AND name LIKE '%$name%' ";
}
if (! empty($gender)) {
$query .= "AND gender LIKE '%$gender%' ";
}
if (! empty($dob)) {
$query .= "AND dob LIKE '%$dob%' ";
}
if (! empty($email)) {
$query .= "AND email LIKE '%$email%' ";
}
$query .= "ORDER BY id";
// echo $query;
// Execute query
$result = # mysql_query($query, $connection)
or showerror();
// Transform the result set to an array (for Smarty)
$entries = array();
while ($row = mysql_fetch_array($result)) {
$entries[] = $row;
}
mysql_close($connection)
or showerror();
return $entries;
}
What does the Exception mean?
As it says, the column count doesn't match the value count. You're providing five values on a six column table. Since you're not providing a value for id, as it's auto increment, it errors out - you need to specify the specific columns you're inserting into:
$insert = "insert into gb_entries (username, name, gender, dob, email) " .
"values ('$username', '$name', '$gender', '$dob', '$email')"
Also, I really hate that WHERE 0=0 line. I know why you're doing it that way, but I personally find it cleaner to do something like this (warning: air code!):
$query = "select username, name, gender, dob, email from gb_entries ";
$where = array();
if (! empty($username)) {
$where[] = "username LIKE '%$username%'"; // add each condition to an array
// repeat for other conditions
// create WHERE clause by combining where clauses,
// adding ' AND ' between conditions,
// and append this to the query if there are any conditions
if (count($where) > 0) {
$query .= "WHERE " . implode($where, " AND ");
}
This is personal preference, as the query optimizer would surely strip out the 0=0 on it's own and so it wouldn't have a performance impact, but I just like my SQL to have as few hacks as possible.
If the error is occurring when trying to insert a row to your table, try specifying the list of fields, in the insert query -- this way, the number of data in the values clause will match the number of expected columns.
Else, MySQL expects six columns : it expects the id column -- for which you didn't specify a value.
Basically, instead of this :
$insert = "insert into gb_entries " .
"values ('$username', '$name', '$gender', '$dob', '$email')";
Use something like that :
$insert = "insert into gb_entries (username, name, gender, dob, email) " .
"values ('$username', '$name', '$gender', '$dob', '$email')";
I had a similar problem. The column count was correct. the problem was that i was trying to save a String (the value had quotes around it) in an INT field. So your problem is probably coming from the single quotes you have around the '$dob'. I know, the mysql error generated doesn't make sense..
funny thing, I had the same problem again.. and found my own answer here (quite embarrassingly)
It's an UNEXPECTED Data problem (sounds like better error msg to me). I really think, that error message should be looked at again
Does modifying this line help?
$insert = "insert into gb_entries (username, name, gender, dob, email) " .
"values ('$username', '$name', '$gender', '$dob', '$email')";

Categories