Hi I am trying to create a little email subscriber script for adding email addresses to my database. I was able to get it working fine using deprecated functions like mysql_connect but am making it better using mysqli instead. However for some reason I am no longer able to insert the email addresses into the database yet I can connect to the database fine and check the email address doesn't already exist. I would like to know why my INSERT doesn't seem to be working. I don't have much experience with PHP thanks.
if (!$link) {
echo "save_failed cannot connect"; //if cant connect show error
return;
}
mysqli_select_db($link,$mydb);
// Clean variables before performing insert
$clean_email = mysqli_real_escape_string($link,$_POST['email']);
$clean_subscriber = mysqli_real_escape_string($link,$_POST['firstname']);
$clean_date = mysqli_real_escape_string($link,$_POST['date']);
$query = "SELECT * FROM EmailList WHERE email = '{$email}'";//check if already in list
$result = mysqli_query($link,$query);
$row_cnt = mysqli_num_rows($result);
if($row_cnt == 0) {
// Perform insert if not in list
$sql = "INSERT INTO EmailList (Email,Name,Date) VALUES
('$clean_email','$clean_subscriber','$clean_date')";
echo "Thank you for Subscribing to my blog!";
} else {
echo "You have subscribed already. Thank you for subscribing";
}
Looks like you're missing the line that runs the query:
mysqli_query($link,$sql);
You need to execute the query with
mysqli_query()
like so:
if (!$link) {
echo "save_failed cannot connect"; //if cant connect show error
return;
}
mysqli_select_db($link,$mydb);
// Clean variables before performing insert
$clean_email = mysqli_real_escape_string($link,$_POST['email']);
$clean_subscriber = mysqli_real_escape_string($link,$_POST['firstname']);
$clean_date = mysqli_real_escape_string($link,$_POST['date']);
$query = "SELECT * FROM EmailList WHERE email = '{$email}'";//check if already in list
$result = mysqli_query($link,$query);
$row_cnt = mysqli_num_rows($result);
if($row_cnt == 0) {
// Perform insert if not in list
$sql = "INSERT INTO EmailList (Email,Name,Date) VALUES
('$clean_email','$clean_subscriber','$clean_date')";
mysqli_query($link,$sql)
echo "Thank you for Subscribing to my blog!";
} else {
echo "You have subscribed already. Thank you for subscribing";
}
Related
So, I got a code to check if the mail is already registrated in the users database.. But when I try to register using the same mail as registrated, it don't trigger the code.
I tried to print the result and I used the code as IsValidUser("themail"); and it returned 1. But still it wont trigger the registration code..
Here's how I check it;
if(IsValidUser($reg_email) == 1) {
$result = '<script>var iframe = document.createElement("IFRAME");iframe.setAttribute("src", "data:text/plain,");document.documentElement.appendChild(iframe);window.frames[0].window.alert("Error\nThis mail adress are already registrated.");iframe.parentNode.removeChild(iframe);</script>';
}
and here's the function;
function IsValidUser($mail) {
global $conn;
$sql = "SELECT * FROM users WHERE mail = '$mail'";
$result = mysqli_query($conn, $sql);
if(!$result)
die("Error description: " . mysqli_error($conn));
if(mysqli_num_rows($result) > 0)
return 1;
else
return 0;
}
I fixed it by placing the other if's under
else {
if(..) {}
}
I have the following PHP code which is for a voting system of an app.
Its a Q&A app, and the user can vote for questions and answers that are posted.
In my php code, I first check if the user has voted for a specific question.
This would exist in the QVOTES table, with the email and the id of the question being voted for.
When performing this check, I am not sure of how to see if $result is an empty set, so as to submit the user's vote if they have not voted for the question yet.
How can i get this working? All help is greatly appreciated.
<?php
$con=mysqli_connect("127.2.1.1","S837","887","D887");
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$qid = $_POST['qid'];
$email = $_POST['email'];
$result = mysqli_query($con, "SELECT * FROM QVOTES WHERE QID = $qid AND EMAIL = '$email'");
if (!mysqli_num_rows($result) ){
if ($result = mysqli_query($con, "INSERT INTO QVOTES (QID, EMAIL) VALUES ($qid, '$email')")) {
mysqli_query($con, "Update QUESTIONS SET VOTES = VOTES +1 WHERE QID = $qid");
echo "Update successful";
} else{
echo "Update unsuccessful";
}
} else{
echo "null";
}
mysqli_close($con);
Actually you are doing in a wrong way. Please try to do like this:-
<?php
$con=mysqli_connect("127.2.1.1","S837","887","D887");
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$qid = $_POST['qid'];
$email = $_POST['email'];
$result = mysqli_query($con, "SELECT * FROM QVOTES WHERE QID = $qid AND EMAIL = $email") or die(mysqli_error($con)); // no need of extra quote
if ($result->num_rows == 0 ){ // means no vote-up done till now
$result = mysqli_query($con, "INSERT INTO QVOTES (QID, EMAIL) VALUES ($qid, $email)")or die(mysqli_error($con)); // insert
if($result){
echo "Vote Added successfully.";
} else{
echo "Error occur while adding vote.Please try again.";
}
} else{
$result = mysqli_query($con, "Update QUESTIONS SET VOTES = VOTES +1 WHERE QID = $qid AND EMAIL = $email")or die(mysqli_error($con)); // upddate
if($result){
echo "Vote updated successfully.";
} else{
echo "Error occur while updating vote.Please try again.";
}
}
mysqli_close($con);
Note:- I change message for better understanding. You can change according to your wish. thanks.
How to see if $result is an empty set?
From the docs:
Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a mysqli_result object. For other successful queries mysqli_query() will return TRUE (Ref)
Use $result->num_rows if $result is not FALSE;
I'm trying to to test to see if an email address exists in my database by running a query check.
I can connect to the database fine.
However no matter what, even if the email exists it returns "doesn't exist".
<?php
//----------------------------------------------------------------------------------//
//Setup
require_once('SB_Constants.php');
//----------------------------------------------------------------------------------//
//Connect to the database
//----------------------------------------------------------------------------------//
$connection = mysqli_connect(DATABASE_HOST, SAVE_USERNAME, SAVE_PASSWORD, DATABASE_NAME);
// check the connection was successful
if (mysqli_connect_errno($connection)) {
header('HTTP/1.0 500 Internal Server Error', true, 500);
die(FailedToAccessDatabase . ". Failed to connect to Database");
} else {
echo "Connection Success!";
}
//Query Check
$assessorEmail = mysqli_query($connection, "SELECT email_address FROM assessorID WHERE email_address = 'ryan#ablah.com'");
if (mysqli_num_rows($query_identifier) == 0) {
die(UnregisteredAssessor . ". Doesn't Exist");
} else {
// Exists
echo "Exists getting ace id.";
//Get the assessor ID
$result = mysqli_query($connection, "SELECT ace_id FROM assessorID WHERE email_address = 'ryan#blah.com'");
echo $result;
}
/* close connection */
mysqli_close($connection);
?>
Any ideas of the problem? :)
Various mistakes. Fix:
$assessorEmail = mysqli_query($connection, "SELECT ace_id,email_address FROM assessorID WHERE email_address = 'ryan#ablah.com'");
if (mysqli_num_rows($assessorEmail) == 0) {
die(UnregisteredAssessor . ". Doesn't Exist");
} else {
// Exists
echo "Exists getting ace id.";
//Get the assessor ID
$result = mysqli_fetch_assoc($assessorEmail);
echo $result['ace_id'];
}
Your problem is mysqli_num_rows($query_identifier) is accessing an undefined variable instead of $assessorEmail.
Additionally, you only need one query if you just want the ace_id:
$assessorEmail = mysqli_query($connection, "SELECT ace_id FROM assessorID WHERE email_address = 'ryan#ablah.com'");
If mysqli_num_rows($assessorEmail) returns a row, than the email exists and you already have the ace_id
while(mysqli_fetch_assoc($assessorEmail) = $row) {
echo $result['ace_id'];
}
I am new in PHP and need help with my below code. When I am entering wrong userid instead of giving the message "userid does not exist" it is showing "password/id mismatch. Please guide me where I am wrong.
<?php
session_start();
$id = $_POST['userid'];
$pwd = $_POST['paswd'];
$con = mysqli_connect("localhost", "????", "????", "??????");
if ($con) {
$result = mysqli_query($con, "SELECT * FROM users WHERE userid=$id");
if ($result) {
$row = mysql_fetch_array($result);
if ($row["userid"] == $id && $row["paswd"] == $pwd) {
echo "Welcome! You are a authenticate user";
if ($id == $pwd)
//my default login id and password are same
{
header("Location: changepwd.html");
} else {
header("Location: dataentry.html");
}
} else {
echo "ID/Password Mismatch";
}
} else {
echo "User does not Exist !!!";
}
} else {
echo "Connection failed - ".mysqli_error()." -- ".mysqli_errno();
}
?>
The main problem you have is that you're mixing up between the mysqli and mysql functions. These two libraries are not compatible with each other; you must only use one or the other.
In other words, the following line is wrong:
$row=mysql_fetch_array($result);
It needs to be changed to use mysqli_.
While I'm here, going off-topic for a moment I would also point out a few other mistakes you're making:
You aren't escaping your SQL input. It would be extremely easy to hack your code simply by posting a malicious value to $_POST['userid']. You must use proper escaping or parameter binding. (since you're using mysqli, I recommend the latter; it's a better technique).
Your password checking is poor -- you don't appear to be doing any kind of hashing, so I guess your passwords are stored as plain text in the database. If this is the case, then your database is extremely vulnerable. You should always hash your passwords, and never store the actual password value in the database.
I've gone off topic, so I won't go any further into explaining those points; if you need help with either of these points I suggest asking separate questions (or searching here; I'm sure there's plenty of existing advice available too).
else
{
echo "ID/Password Mismatch";
}
is connected with the
if($row["userid"]==$id && $row["paswd"]==$pwd)
{
So since you are giving a wrong id. It echo's: ID/Password Mismatch
Also the else at if ($result) { wont ever show since
$result = mysqli_query($con, "SELECT * FROM users WHERE userid=$id");
You need some additionnal checks:
select * return 1 row (not 0, and not more)
you need to protect the datas entered by the html form (for example someone could enter 1 or 1 to return all rows
<?php
session_start();
$con = mysqli_connect("localhost", "????", "????", "??????");
$id = mysqli_real_escape_string($_POST['userid']);
$pwd = mysqli_real_escape_string($_POST['paswd']);
if ($con) {
// don't even do the query if data are incomplete
if (empty($id) || empty($pwd)
$result = false;
else
{
// optionnal : if userid is supposed to be a number
// $id = (int)$id;
$result = mysqli_query($con, "SELECT * FROM users WHERE userid='$id'");
}
if (mysqli_num_rows($result) != 1)
$result = false;
if ($result) {
$row = mysqli_fetch_assoc($result);
if ($row["userid"] == $id && $row["paswd"] == $pwd) {
echo "Welcome! You are a authenticate user";
if ($id == $pwd)
//my default login id and password are same
{
header("Location: changepwd.html");
} else {
header("Location: dataentry.html");
}
} else {
echo "ID/Password Mismatch";
}
} else {
echo "User does not Exist, or incomplete input";
}
} else {
echo "Connection failed - " . mysqli_error() . " -- " . mysqli_errno();
}
?>
Try with isset() method while you are checking if $result empty or not.
that is in line
if ($result) {.......}
use
if (isset($result)) { .......}
$result is always true, because mysqli_query() only returns false if query failed.
You could check if $result has actual content with empty() for example.
You can use this sql compare password as well with userid
$sql= "SELECT * FROM users WHERE userid='".$id.", and password='".$pwd."'";
I am trying to insert some data into a MySQL database using PHP. The code I have works fine on localhost, but when I try it on my server the reg_user_id, reg_user_access_level and reg_user_status are inserted while all the other fields are not.
Please help, I've already wasted a day trying to sort this out.
everything up to here is fine
The PHP is:
else {
//sort the data
$reg_user_name = mysql_real_escape_string($_POST['reg_user_name']);
//create a salt for the password before encryption, use the same when retrieving the password!
$salt = 'mysalt';//not actually this
//first encryption
$reg_user_password = sha1($_POST['reg_user_password']);
//second encryption with salt
$reg_user_password = sha1($salt.$reg_user_password);
$reg_user_password = mysql_real_escape_string($reg_user_password);
/*** strip injection chars from email ***/
$reg_user_email = preg_replace( '((?:\n|\r|\t|%0A|%0D|%08|%09)+)i','',$_POST['reg_user_email']);
$reg_user_email = mysql_real_escape_string($reg_user_email);
//connect to the db
include '../-useful_scripts/php/mysqli_connect_dsnydesign.php';
//check the connection
if($dbc) {
/*** check for existing username and email ***/
$query = "SELECT reg_user_name, reg_user_email FROM reg_users WHERE reg_user_name = '{$reg_user_name}' OR reg_user_email = '{$reg_user_email}';";
$result = mysqli_query($dbc, $query);
$row = mysqli_fetch_row($result);
if (sizeof($row) > 0) {
foreach($row as $value) {
echo $value.'<br>';
}
if($row[0] == $reg_user_name) {
$errors[] = 'Sorry, the username is already in use';
}
elseif($row[1] == $reg_user_email) {
$errors[] = 'This Email address is already subscribed';
}
mysqli_free_result($result);
}
else {
/*** create a verification code ***/
$verification_code = uniqid();
//set the query
$query = "INSERT INTO reg_users(reg_user_id, reg_user_name, reg_user_password, reg_user_email, reg_user_access_level, reg_user_status) VALUES (NULL, '$reg_user_name', '$reg_user_password', '$reg_user_email', '1', '$verification_code');";
//run the query
if(mysqli_query($dbc, $query)) {
just goes on to notify of submission after this.
Check that you are using the same PHP version number on your server and your localhost. mysql_real_escape_string has been deprecated in the latest version of PHP.