Please i want a select count statement to retrieve value from a table row and verify it against another table row using php.
meaning
Hello Guys/Gurus
Please I have an issue, am some months into php and i need your help/assistance.
This is the flow. a client register at another site, when we confirm the registration, we send them a code.
The code is generated and saved in another table name called code and column generated_code.
I develop a form (http://cash2money2020.com/form.html)
So all i want is if someone inputs the generated code we sent to them, and filled it in the form, it makes a database checks to see if the code exists in the other table, if yes, submit form..if not, error message that the code is invalid and the form will not be submitted:
$query = "INSERT INTO registration
(id, fname, lname, address1, address2, city, state, country, email, phone, home_phone, dob, gender, living, qualification, mental, mental_details, criminal, criminal_details, kin_name, kin_phone, kin_relationship, tv_appearance, work_financial, tv_station, why, interesting, impressive, generated_code, submitted_date)
VALUES
('', '$fname', '$lname', '$address1', '$address2', '$city', '$state', '$country', '$email', '$phone', '$home_phone', '$dob', '$gender', '$living', '$qualification', '$mental', '$mental_detail', '$criminal', '$criminal_details', '$kin_name', '$kin_phone', '$kin_relationship', '$tv_appearance', '$work_financial', '$tv_station', '$why', '$interesting', '$impressive', '$code', now()) ";
This is what i have done so far
$result = mysqli_query("select count(generated) from code ");
if (!$result) echo mysqli_error();
$row = mysqli_fetch_row($result);
$query = "INSERT INTO registration (generated_code) VALUES ('$code')";
if ($query != $row) {
//code to submit and process the form
}
else
{
//error message
}
Please help am stucked !!!
something like this should do (according to the last comment):
$link = mysqli_connect("my_host", "my_user", "my_password", "my_db");
$result = mysqli_query($link, "select * from code where generated = '$code'");
if (!$result) die("mysql error: " . mysqli_error());
$row = mysqli_fetch_row($result);
if ( $row !== false ) {
// code to submit and process the form
// you might use the result with $row[<fieldname>]
}
else
{
// error message
}
You need to add some error handling and unescaping values (like $code)
Related
This question already has answers here:
PHP MYSQL UPDATE if Exist or INSERT if not?
(2 answers)
Closed 3 years ago.
I'm trying to create a registration form to insert or update users credential in a simple mysql table
I've watched almost every question here but I can't figure why my code doesn't update or insert the user in the form
//check if the user is already registered and then override and update his credentials
$check = "SELECT COUNT(*) FROM theElisa_signUp WHERE Email = '$email'";
if (mysqli_query($conn, $check) >= 1)
{
$update = mysqli_query($conn, "UPDATE theElisa_signUp SET name = '$name', user = '$username', psw = '$password', expire_date = '$expire_date' WHERE email = '$email'");
} elseif (mysqli_query($conn, $check) == 0) {
//inserire dati sign up dei nuovi registrati
$query = mysqli_query($conn, "INSERT INTO theElisa_signUp (name, email, telephone, user, psw, role, expire_date) VALUES ('$name', '$email', 'not-set', '$username', '$password', '$role', '$expire_date')");
} else {
header( "Location: ../admin/index.php" );
}
As you can see, I want to check if the user's email already exists.
If exists (in this case, if it's >= 1) the code must UPDATE the values already set in the mysql table.
If doesn't exist already (== 0) it will create a new user with the INSERT.
I hope my question is clear and respects the standards.
EDIT:
i've tried also the ON DUPLICATE KEY UPDATE but still nothing.
$query=mysqli_query($conn, "INSERT INTO theElisa_signUp (name, email, telephone, user, psw, role, expire_date) VALUES ('$name', '$email', 'not-set', '$username', '$password', '$role', '$expire_date')
ON DUPLICATE KEY UPDATE name = '$name', user = '$username', password = '$password', expire_date = '$expire_date' ");
Really hoping someone can help in this. Unfortunately I'm a simple web designer but for this project they asked me to do this and I have zero code background.
From PHP Manual
/* Select queries return a resultset */
if ($result = mysqli_query($link, "SELECT Name FROM City LIMIT 10")) {
printf("Select returned %d rows.\n", mysqli_num_rows($result));
/* free result set */
mysqli_free_result($result);
}
I have a small database project using HTML forms and PHP code. It is working perfectly except the last part. Basically, I have my database connection setup and working in my PHP, and upon hitting the Add button it should insert values from the form to the database. My instructor said that due to table constraints it has to be inserted in a certain order, basically address table first and then staff table. IF I comment out the staff part of code, my successful confirmation page appears and the address appears in the database every time with an auto incremented address_id. The issue is that I'm supposed to query for a MAX(Address_id) and use that for inserting the staff part, as it uses address_id as a foreign key. When I do that, I get a foreign key constraint error on update cascade. If I completely pull out the INSERT staff code, and put a 'debug' to print the MAX(address_id), it prints correctly. I just can't get it to insert to the staff table correctly so that everything from my form creates a staff record. Here is the code:
$userQuery = "INSERT INTO address (address, district, city_id, postal_code, phone)
VALUES ('$address', '$district', '$city', '$postal_code', '$phone') ";
$addressResult = mysqli_query($connect, $userQuery);
if (!$addressResult)
{
die("Could not successfully run query ($userQuery) from $db: " .
mysqli_error($connect) );
}
$maxQuery = "SELECT MAX(address_id) FROM address";
$result = mysqli_query($connect, $maxQuery);
$row = mysqli_fetch_assoc($result);
if (!$result)
{
die("Could not successfully run query ($userQuery) from $db: " .
mysqli_error($connect) );
}
/**else
{
print ("<p>Average hourly wage:".$row['MAX(address_id)']."</p>");
}**/
$userQuery1 = "INSERT INTO staff (first_name, last_name, address_id, email, store_id)
VALUES ('$first_name', '$last_name', '$row', '$email', '$store_id')";
$staffResult = mysqli_query($connect, $userQuery1);
if (!$staffResult)
{
die("Could not successfully run query ($userQuery1) from $db: " .
mysqli_error($connect) );
}
else
{
print(" <h1>New Staff Record Added!</h1>");
print ("<p>The following record was added:</p>");
print("<table border='0'>
<tr><td>First Name</td><td>$first_name</td></tr>
<tr><td>Last Name</td><td>$last_name</td></tr>
<tr><td>Email</td><td>$email</td></tr>
<tr><td>Store ID</td><td>$store_id</td></tr>
<tr><td>Address</td><td>$address</td></tr>
<tr><td>City</td><td>$city</td></tr>
<tr><td>District</td><td>$district</td></tr>
<tr><td>Postal Code</td><td>$postal_code</td></tr>
<tr><td>Phone</td><td>$phone</td></tr>
</table>");
}
You are not calling the correct associative index. You are just calling the array:
$userQuery1 = "INSERT INTO staff (first_name, last_name, address_id, email, store_id) VALUES ('$first_name', '$last_name', '{$row['MAX(address_id)']}', '$email', '$store_id')";
I'm inserting data into members table, after I've inserted it I want to get the userID of the information just inserted. Whats the best way about doing this ?
My php code
//Insert info into database
$sql = "INSERT INTO members (type, firstname, lastname, email, password, bio) VALUES ('$usertype', '$firstname', '$lastname', '$emailsighup', '$passwordsighnup', '$bio')";
//Run a query to check if data has been inserted correctly.
$records = mysqli_query($connect, $sql);
I did try this SQL but was getting errors
$sql = "INSERT INTO members (type, firstname, lastname, email, password, bio) VALUES ('$usertype', '$firstname', '$lastname', '$emailsighup', '$passwordsighnup', '$bio')"; SELECT SCOPE_IDENTITY(userID);
Assuming $connect as the variable holding your connection information, which seems legit, you can get the value of the last id with:
$user_id = mysqli_insert_id($connect);
This is something you can do from the PHP MySQLi interface, rather than directly from SQL!
Recently i was searching for unique username registration using php.. I came across a piece of code which i am displaying below:
<?php
$fname=trim($_POST['fname']);
$lname=trim($_POST['lname']);
$email=trim($_POST['email']);
$usn=trim($_POST['usn']);
$dept=trim($_POST['dept']);
$pass=trim($_POST['pass']);
$tel=trim($_POST['tel']);
$dbh = mysql_connect('localhost', 'root','') or die("<h3 style=\"color:red;\" align=\"center\">SERVER ERROR</h3>");
mysql_select_db('fy') or die("<h3 style=\"color:red;\" align=\"center\">SERVER ERROR</h3>");
$error= mysql_query("SELECT * FROM stud WHERE email='$email' OR usn='$usn' OR tel='$tel'") or die (mysql_error());
if (mysql_num_rows($error) > 0);
{
die ("Sorry! Either email, usn or tel already exists!");
}
$query="INSERT INTO stud (fname, lname, email, tel, usn, dept, pass) VALUES ('$fname', '$lname', '$email', '$tel', '$usn', '$dept', '$pass')";
mysql_query($query);
$query="INSERT INTO log VALUES ('$usn','$pass',0,0)";
mysql_query($query);
print("REGISTERED");
?>
LOGIN<br />
At this moment my database is completely empty. I've just created the database stud with the desired columns. Now the problem is when i try to register using my registration page, it gives me the error i specified in die that is
"Sorry! Either email, usn or tel already exists!"
How is this possible if there are no values in the database. In the registration form I've given
action="register.php"
as a processing file. Also I've tried with mysql_fetch_assoc(), but i get the same error. Any help is appreciated. Thank you .
Your first problem is that, as John Conde states, your code is vulnerable to SQL injection attacks.
Your second problem, and to answer your question, is probably because you have this:
if (mysql_num_rows($error) > 0);
instead of this:
if (mysql_num_rows($error) > 0)
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')";