Check and Return Value in Mysqli_query - php

I am Android developer and trying to make one API for register user using PHP and Mysqli. I have made API like below
<?php
include("dbconnection.php");
$email= $_GET['email'];
$query = mysqli_query($conn, "SELECT * FROM tbl_user WHERE email='".$email."'");
if (!$query){
die('Error: ' . mysqli_error($con));
}
if(mysqli_num_rows($query) > 0){
$response='success';
}else{
$sql = "INSERT INTO tbl_user(email)VALUES ('".$email."')";
if (mysqli_query($conn, $sql)) {
$response='success';
}else {
$response='error';
}
}
echo json_encode($response);
?>
basically I am passing email as parameter like example.com/login?=abc#gmail.com
and I want check that email is already in database table or not. if email exist in database I want return user_id in response and if email is not in database than I want add that email in database and want return user_id. I have made API is working fine as I require but I do not know how to return user_id located with that email. Let me know if someone can give me idea to solve my puzzle. Thanks

The below code will create an array with message and user_id.
include("dbconnection.php");
$email= $_GET['email'];
$query = mysqli_query($conn, "SELECT * FROM tbl_user WHERE email='".$email."'");
if (!$query){
die('Error: ' . mysqli_error($con));
}
if(mysqli_num_rows($query) > 0){
// assign message to response array
$response['message']='success';
// Get the results data
while($row = mysqli_fetch_assoc($query)) {
// assign user_id to response array
$response['user_id'] = $row['user_id'];
}
}else{
$sql = "INSERT INTO tbl_user(email) VALUES ('".$email."')";
if (mysqli_query($conn, $sql)) {
$response['message']='success';
// assign last inserted id to response array
$response['user_id'] = mysqli_insert_id($conn);
}else {
$response['message']='error';
}
}
echo json_encode($response);
Prepared statements help you secure your SQL statements from SQL Injection attacks.

First of all, you should use PreparedStatement to avoid sql injection.
Then, second you can use PDO::lastInsertId()

Related

how to store session value in another table?

I have one login page and its database. i want to take the email from there and store it in another table of the same database. Code is give below please have a look and tell me.
Table 1
<?php
session_start();
$email = $_POST['email'];
$password = $_POST['password'];
include 'connection.php';
$sql = "SELECT * FROM users WHERE email='$email' AND password='$password'";
$res = mysql_query($sql);
$count = mysql_num_rows($res);
if($count == 0)
{
echo "Username Password Incorrect";
}
else
{
$_SESSION['email'] = $email;
header("location:home2.php")
}
?>
Table 2
<?php
$email= (HOW TO GET IT FROM SESSION?)
$company = $_POST['company'];
$project = $_POST['project'];
$duration = $_POST['duration'];
$key_learning = $_POST['key_learning'];
include 'connection.php';
$sql = "INSERT INTO `internship`(`id`, `email`, `company`, `project`, `duration`, `key_learning`) VALUES ('', '$email', '$company','$project', '$duration', '$key_learning')";
$res = mysql_query($sql);
$count = mysql_num_rows($res);
if($count == 1)
{
echo "Fail";
}
else
{
$_SESSION['email'] = $email;
header("location:home3.php");
}
?>
From table 1 i want to take email if using session and want to store it in table 2. How to do it?
$email= (HOW TO GET IT FROM SESSION?)
If the 2nd code block is in the same execution context as the first, you can just use the variable $email that you created.
If you're trying to retrieve data from session as the user navigates to a new page, you do:
<?php
session_start();
$email = isset($_SESSION['email'])? $_SESSION['email'] : null;
By the way, in the 2nd code block you're trying to use mysql_num_rows to analyze the effect of an INSERT query. You can't do that. According to the manual:
[mysql_num_rows] retrieves the number of rows from a result set. This
command is only valid for statements like SELECT or SHOW that return
an actual result set. To retrieve the number of rows affected by a
INSERT, UPDATE, REPLACE or DELETE query, use mysql_affected_rows().
$res = mysql_query($sql) or die(mysql_error());
if(mysql_affected_rows()){
//success
}else{
//failure
}
You should not be using mysql_ functions anyway and you should most definitely not be inserting user provided values (username, email, password) directly in your SQL statement

How to automatic update data in database in PHP

I want to make toefl test. I make table score_structure in database containing 4 columns (email, right, false, score). If the user has done on previous test and will perform a test again, then the user data will be updated according to the user's email pitch.
I have tried but failed, the data will not update. Please help me.
This is structure.php
<?php
$email = $_SESSION['email'];
$cek = mysql_num_rows(mysql_query("SELECT email FROM score_structure WHERE email='$email'"));
if($cek > 0 ) {
$simpan = "UPDATE score_structure SET right='$right', false='$false', score='$score' WHERE email='$email'";
if(mysql_query($simpan)) {
header("location:test_listening.php");
} else {
echo mysql_error();
} else {
$simpan = "INSERT INTO score_structure VALUES ('$email', '$right', '$false', '$score')";
if(mysql_query($simpan)) {
header("location:test_listening.php");
} else {
echo mysql_error();
}
}
?>
Update your update query & let us know the feedback:
$simpan = "UPDATE score_structure SET `right`='$right', `false`='$false', `score`='$score' WHERE email='$email'";
Also currently mysql_() are depreciated so use mysqli_()

Prevent duplicate data being entered into mysql database

I'm trying to make my email subscription service reject emails that already exist within my database so users don't subscribe the same email twice. this is what I have but its not working, any ideas?
<?php
if(!isset($_POST['submit']))
exit();
$vars = array('email');
$verified = TRUE;
foreach($vars as $v) {
if(!isset($_POST[$v]) || empty($_POST[$v])) {
$verified = FALSE;
}
}
if(!$verified) {
echo "<p style='color:white; margin-top:25px;'>*Email required*</p>";
exit();
}
$email = $_POST['email'];
if($_POST['submit']) echo "<p style='color:white; margin-top:25px;'>*Check your inbox* </p>";
// Create connection
$con=mysqli_connect("mysql.host","user","password","dbname");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO emails (email) VALUES ('$_POST[email]')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
$query = mysql_query("SELECT * FROM emails WHERE email='$email'",($con));
if(mysql_num_rows($query) != 1)
{
echo "email already exists";
// redirect back to form and populate with
// data that has already been entered by the user
}
mysqli_close($con);
?>
The easiest way to let MySQL reject the duplicate e-mail address is to make the field unique (http://www.w3schools.com/sql/sql_unique.asp)
ALTER TABLE emails ADD UNIQUE (email)
However, MySQL will not return a warning
Use mysqli_num_rows($query) instead of mysql_num_rows($query)
$query = mysqli_query($con, "SELECT * FROM emails WHERE email='".$email."'");
if(mysqli_num_rows($query) > 0){
echo "email already exists";
}else{
$sql="INSERT INTO emails (email) VALUES ('".$_POST[email]."')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
}
Firstly, you're mixing MySQLi_ with MySQL_ so stick with MySQLi_ and modify the rest of your code accordingly.
This is the logic I use in my scripts, using ? instead of '$email'
$query = $con->query("SELECT * FROM emails WHERE email=?");
// $query = $con->query("SELECT email FROM emails WHERE email=?");
// you may need to use that one --^ if checking a particular column
$numrows=mysqli_num_rows($query);
if($numrows > 0){
die("Email already exists in the database, please try again.");
}
You can use this method, binding parameters. Assuming your column is named email
$query = "SELECT email FROM emails WHERE email=?";
if ($stmt = $con->prepare($query)){
$stmt->bind_param("s", $email);
if($stmt->execute()){
$stmt->store_result();
$email_check= "";
$stmt->bind_result($email_check);
$stmt->fetch();
if ($stmt->num_rows == 1){
echo "That Email already exists.";
exit;
}
}
}
Beside mixing mysql and mysli
Use > not !=
if(mysqli_num_rows($query) > 1)
But this approach means you already have duplicates.
Maybe this will help after you put an unique index on the email column.
As noted in the other answers, you mixed mysqli and mysql functions.
for exemple in both these lines you use mysql instead of mysqli functions.
$query = mysql_query("SELECT * FROM emails WHERE email='$email'",($con));
if(mysql_num_rows($query) != 1)
I also think your code is easily SQL Injectable.
You are using $_POST["email"] in your insert query, without sanitizing it.
Have a look to at least the sql injection wikipedia page
My answer would be as follows,
First, create a UNIQUE KEY of the email column, and then:
INSERT INTO `table` VALUES (/*etc*/) ON DUPLICATE KEY UPDATE /*set a column equal to itself*/
This allows you to attempt inserting into the database, and you can choose whether or not the query throws an error. If you want it to throw an error, then simply do not use ON DUPLICATE KEY, and then catch the SQLException that is thrown from the query and tell the user that the email already exists.
Add a unique constraint to the email column.
Test for error returned on insert or update. I believe the code may be influenced if it is a primary key, foreign key, unique constraint on an index.
With PHP you can use
if( mysql_errno() == X) {
// Duplicate VALUE
} else {
// fail
}
You can test it yourself with a duplicate email or here are the mysql_errNo return values
For non PHP, to determine correct error code test it yourself with a duplicate email or look at the following.
MySQL Errors

checking for email address in mysql db

So im trying to do what should seem and probably is a very simple mundane task. I am trying to check for an email address in my db. I dont know if im on the right track or not, can some one straiten me out please?
$query = "SELECT * FROM 68_users WHERE email= $email";
if($result = mysqli_query($link, $query) == $email) {
echo 'Email has been registered';
}else{
$query = "INSERT INTO 68_users (email,pass,old_pass,first_name,last_name,dob,gender,phone,fanmail)
VALUES ('$email',AES_ENCRYPT('$pass', 'something'),AES_ENCRYPT('$pass', 'something'),'$first_name','$last_name','$dob','$gender','$phone','$fanmail')"
or die(mysqli_error());
if ( !mysqli_query($link, $query) ) {
echo 'error: '.mysqli_error($link);
exit();
}
}
mysqli_close($link);
}
Thank you all for your help. I need to figure out a debugging situation for php. Right now i write in eclipse and debug on my site, very aggravating.. this is what i used:
$query = "SELECT * FROM 68_users WHERE email= '$email'";
$result = mysqli_query($link, $query);
if($result->num_rows > 0) {
echo 'This email has previously been registered';
}else{
$query = "INSERT INTO 68_users (email,pass,old_pass,first_name,last_name,dob,gender,phone,fanmail)
VALUES ('$email',AES_ENCRYPT('$pass', 'something'),AES_ENCRYPT('$pass', 'something'),'$first_name','$last_name','$dob','$gender','$phone','$fanmail')"
or die(mysqli_error());
if ( !mysqli_query($link, $query) ) {
echo 'error: '.mysqli_error($link);
exit();
}
header( 'Location: http://www.example.com/html/thankyou.html' ) ;
}
this query will fail as you need apostrophes around the email variable. also you can simply run the query and see how many rows are return:
$query = "SELECT * FROM 68_users WHERE email= '$email'";
$result = mysqli_query($link, $query);
if($result->num_rows > 0) {
echo 'Email has been registered';
}else{
// ....
}
You need quotes around the variable $email,
$query = "SELECT * FROM 68_users WHERE email= '$email'";
You will need to see the result of the rest of the code, to know if everything else works fine.
Without knowing the results of your current code, the one problem I can spot is that you want to make sure you enclose the email value in single-quotes for your query statement to ensure that it is evaluated properly:
$query = "SELECT * FROM 68_users WHERE email='$email'";
Omitting the quotes will result in an error when your query executes, which depending on your verbose handling, may or may not be visibly apparent. As a further point, this would be where basic debugging comes into play, which is a fundamental for all programmers.
Remove the equality check for your email, as your query statement is already doing that for you. If there aren't any rows returned, then it will return false and trigger the else statement:
$query = "SELECT * FROM 68_users WHERE email='$email'";
if($result = mysqli_query($link, $query)) {
// Registered
}else{
// Not Registered
}
$query = "SELECT * FROM 68_users WHERE email= '$email'";
will also return a array of values, your "if ($result ... == $email)" will fail.
*var_dump($result)* to see whats coming back from the query.

Checking if row exists under criteria (PDO, prepare???)

The code below indicates my attempts to try and find out whether a row exists with the criteria gave in the code. It defaults to the else statement, correctly, but doesn't work with the 'if' statement if the if statement appears to be true (there are no emails down as ashfjks#sdhja.com), and instead the code proceeds. The latter part of this code is mostly to expand on the situation. the row can only exist or not exist so I don't understand why it's not strictly doing one or the other. I am converting into PDO for site secuirty, thats why not all is in PDO, yet. I am sorry if this question is too localised?
$stmt = $pdo->prepare("SELECT * FROM table WHERE email = ?");
$stmt->execute(array("$email"));
$row3 = $stmt->fetch(PDO::FETCH_ASSOC);
while($row = $stmt->fetch()) {
if ( ! $row3) {
// Row3 doesn't exist -- this means no one in the database has this email, allow the person to join
$query = "INSERT INTO table (username, email, password, join_date) VALUES ('$username', '$email', SHA('$password1'), NOW())";
mysqli_query($dbc, $query);
$query = "SELECT * FROM table WHERE username = '$username'";
$data2 = mysqli_query($dbc, $query);
while ($row = mysqli_fetch_array($data2)) {
$recipent = '' . $row['user_id'] . '';
$query = "INSERT INTO messages (recipent, MsgTit, MsgR, MsgA, sender, time, readb, reada, MsgCon) VALUES ('$recipent', '$MsgTit', '$MsgR', '$MsgA', '$sender', NOW(), '$readb', '$reada', '$MsgCon')";
mysqli_query($dbc, $query);
// Aftermath.
echo '<p>Your new account has been successfully created. You\'re now ready to log in. After this you should implement basic character-details on your users profile to begin the game.</p>';
mysqli_close($dbc);
exit();
} }
else {
// An account already exists for this email, so display an error message
echo '<p class="error">An account already exists for this e-mail.</p>';
$email = "";
}
}
Your if statement will never be executed. You need to check the number of rows returned. This is what you want:
Note: I originally used $stmt->rowCount(), but the OP said that didn't work for him. But I'm pretty sure the cause of that error was coming from somewhere else.
if (!($stmt = $pdo->prepare("SELECT * FROM table WHERE email = ?"))) {
//error
}
if (!$stmt->execute(array("$email"))) {
//error
}
//The $row3 var you had was useless. Deleted that.
$count = 0;
while ($row = $stmt->fetch()) {
$count++;
}
//The query returned 0 rows, so you know the email doesn't exist in the DB
if ($count== 0) {
$query = "INSERT INTO table (username, email, password, join_date) VALUES ('$username', '$email', SHA('$password1'), NOW())";
if (!mysqli_query($dbc, $query)) {
//error
}
$query = "SELECT * FROM table WHERE username = '$username'";
if (!($data2 = mysqli_query($dbc, $query))) {
//error
}
while ($row = mysqli_fetch_array($data2)) {
$recipent = '' . $row['user_id'] . '';
$query = "INSERT INTO messages (recipent, MsgTit, MsgR, MsgA, sender, time, readb, reada, MsgCon) VALUES ('$recipent', '$MsgTit', '$MsgR', '$MsgA', '$sender', NOW(), '$readb', '$reada', '$MsgCon')";
if (!mysqli_query($dbc, $query)) {
//error
}
// Aftermath.
echo '<p>Your new account has been successfully created. You\'re now ready to log in. After this you should implement basic character-details on your users profile to begin the game.</p>';
mysqli_close($dbc);
exit();
}
}
//The query did not return 0 rows, so it does exist in the DB
else {
// An account already exists for this email, so display an error message
echo '<p class="error">An account already exists for this e-mail.</p>';
$email = "";
}
And you should totally convert the rest of those queries to use PDO.
+1 to answer from #Geoff_Montee, but here are a few more tips:
Make sure you check for errors after every prepare() or execute(). Report the error (but don't expose your SQL to the user), and fail gracefully.
Note that even though you checked for existence of a row matching $email, such a row could be created in the brief moment of time since your check and before you INSERT. This is a race condition. Even if you SELECT for a row matching $email, you should also use a UNIQUE constraint in the database, and catch errors when you execute the INSERT in case the UNIQUE constraint blocks the insert due to conflict.
SELECT email instead of SELECT *. If you have an index on email, then the query runs more efficiently because it can just check the index for the given value, instead of having to read all the columns of the table when you don't need them. This optimization is called an index-only query.
Likewise use SELECT user_id instead of SELECT *. Use SELECT * only when you really need to fetch all the columns.
Bcrypt is more secure than SHA for hashing passwords.

Categories