PDO Prepared Select statement for checking if a user exists - email

I'm a pdo newbie and need to prepare and execute some php/pdo code:
This code works to allow me to create users in my database:
// Perform Insert / Update
$STH = $dbh->prepare("INSERT INTO users (username, email) values (:username, :email)");
$STH->bindParam(':username', $username);
$STH->bindParam(':email', $email);
try{
$STH->execute();
redirect_to(signupsuccess.php);
}
catch(PDOException $e) {
echo "I'm sorry, Dave. I'm afraid I can't do that.";
file_put_contents('PDOErrors.txt', $e->getMessage(), FILE_APPEND);
}
}
but before I put that data into the database I need to do a check to make sure the email doesn't already exist in the database. I need to do a SELECT, something like:
$STH = $dbh->prepare("SELECT FROM users (email) values (:email)");
$STH->bindParam(':email', $email);
try{
$STH->execute();
}
and I know I need to add
"WHERE something matches '$_POST'email') something.." ...
I'm totally lost at this point..I can do this without PDO but I want to start using PDO's prepared statements..Please help!

Just do a simple select. I recommend Using bind value if you may possibly have a null email.
$STH = $dbh->prepare("SELECT email FROM users WHERE email = :email");
$STH->bindValue(':email', $email);
try{
$STH->execute();
}
Then just check if any records are returned. If so, Update, don't insert. good luck.

Related

mysqli_query() expects parameter 1 to be mysqli error

I have a problem with my scripts I need to change minimal of 30 scripts to the "new" mysqli but its terrible I know some basics but now I'm complete lost...
The connection to the database is ok, but now I have this error with this kind of rule in the script.... can someone help me out so I can learn from it ?
$sql_email_check = mysqli_query($GLOBALS["___mysqli_ston"], "SELECT email
FROM users WHERE email='$email' AND status='Alive'");
$sql_username_check = mysqli_query($GLOBALS["___mysqli_ston"],
"SELECT username FROM users WHERE username='$reg_username'");
Update 1:
I cleared the error from the first rule of the script, i saw something on google similair.
This was my script:
$sql_email_check = mysqli_query($GLOBALS["___mysqli_ston"], "SELECT email FROM users WHERE email='$email' AND status='Alive'");
And now this:
$sql_email_check = mysqli_query($con, "SELECT email FROM users WHERE email='$email' AND status='Alive'");
i replaced: $GLOBALS["___mysqli_ston"], with $con, $con i have already dentifyed in a other filte with the connection with db and included in this file Is this right and will it work ? the error's are disapearing but if it will work ?
This is how I do it...
$connection = new mysqli('database_name', 'user', 'password', 'table_name');
$email = 'emailAddressYouWantToLookUp';
$sql = "SELECT email FROM users WHERE email = '$email' AND status = 'Alive';";
$results = $connection->query($sql);
$emailFoundInDatabase = '';
if ($results->num_rows > 0) {
while($row = $results->fetch_assoc()) {
$emailFoundInDatabase = $row['email'];
};
};
echo $emailFoundInDatabase;
Close!
The solution was
replacing: $GLOBALS["___mysqli_ston"], with $con,
I have $con in a other file that makes a connection with the database and included in this script.
Also got a weird error about
i replaced that with:
and now all error's are gone and this script is working 100%
Thanks

Mysqli not inserting data on table

Here's my code:
// Register User
$sql = "INSERT INTO users (username, password, email, register_date)
VALUES ('$username', '$md5pass', '$email', '$date')";
if (mysqli_query($conn, $sql)) {
$last_id = mysqli_insert_id($conn);
$sql = "INSERT INTO skills (user_id)
VALUES ('$last_id')" or die(mysqli_error($conn));
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
Well the first table is created and everything seems ok but the second table (skills) it's not being inserted.
Can anyone tell what I'm doing wrong?
You create the second insert query, but you are not executing it.
Also, you should be checking the result of mysqli_insert_id, in case this call fails.

Mysqli bind_result error

I am new to SQL and PHP. My goal is simple: Check if there is already an email adress stored in database. I am using following code:
$email = info#test.pl;
$conn = new mysqli("localhost", "root", "", "mysite"); // Create connection
if ($conn->connect_error) { // Check connection
die("Connection failed: " . $conn->connect_error);
}
$stmt = $conn->prepare("SELECT * FROM contacts WHERE email = ?");
$stmt->bind_param("s", $email);
$stmt->execute();
$stmt->bind_result($email);
$stmt->store_result();
$result = $stmt->num_rows;
echo $result;
Every time i get an error. It says i am using wrong numbers of parameters in bind_result. How it can be?
If you're new to all this, I would recommend using PDO instead of mysqli.
As for your error: you select * columns but bind only one.
You can change the query to select email, or do away with binding the resultset:
if all you want is to check for the presence of the email, all you need is the rowcount.

Result binding in mysqli

In the following example, can any folks show me how to code the binding part as I select all fields from the table
$stmt = $mysqli_conn->stmt_init();
if ($stmt->prepare("SELECT * FROM books")) {
$stmt->execute();
$stmt->bind_result( **WHAT DO I PUT HERE** );
$stmt->close();
}
In bind_result, you put in the variables where you want to fetch the data into, instead of using an array returned otherwise.
$stmt->bind_result($col1, $col2, $col3, $col4);
while($stmt->fetch_assoc())
echo "$col1 $col2 $col3 $col4";
Alternatively, if you don't want to bind the result
while($resultArray = $stmt->fetch_assoc()) {
echo "$resultArray[columnName1] $resultArray[columnName2] ...";
}

Virtuemart / User Fields

I have added a field in 'Manage User Fields' & when an email is sent to the administrator notifying them of the new user registration, I want to include this new field.
I have written some code to get this new field from #__vm_user_info in /administrator/components/com_virtuemart/classes/ps_shopper.php, in the _sendMail function, as well as added the variable to $message2.
ASEND_MSG has been modified to accept the parameter, but the field is not included in the email to the admin when a user is created. When I go look in the table, the data is there. So to trouble shoot, I hard coded a user name in the select statement, added another user & the correct value was sent for the hard coded user, not the one just added. I am now thinking that it is a commit issue with MySQL, so I put a sleep(4) in the code before I attempt to get the value...no luck.
Can anyone shine some light on this for me??
LarryR....
administrator/components/com_virtuemart/classses/ps_shopper.php
Need to add with the following code in function add() before "return true" line :
/**************************** ***********************/
$pwd = $_POST['password'];
$db = JFactory::getDBO();
$query = "SELECT id, name, email, username"
. "\n FROM #__users"
. "\n ORDER by id DESC LIMIT 1"
;
$db->setQuery( $query );
$rows = $db->loadObjectList();
$namee = $rows[0]->name;
$emaill = $rows[0]->email;
$usern = $rows[0]->username;
$pwd;
$lid = $rows[0]->id;
$dbv = new ps_DB;
echo $query = "SELECT *"
. "\n FROM #__{vm}_user_info"
. "\n WHERE user_id=$lid"
;
$dbv->setQuery( $query );
$fid = $db->loadObjectList();
$field = $fid[0]->extra_field_1;
$user = clone(JFactory::getUser());
$usersConfig = &JComponentHelper::getParams( 'com_users' );
if ($usersConfig->get('allowUserRegistration') == '0') {
JError::raiseError( 403, JText::_( 'Access Forbidden' ));
return false;
}
// If user activation is turned on, we need to set the activation information
$useractivation = $usersConfig->get( 'useractivation' );
if ($useractivation == '1')
{
jimport('joomla.user.helper');
$user->set('activation', md5( JUserHelper::genRandomPassword()) );
$user->set('block', '1');
}
$component = 'com_user';
$activation_link = $mosConfig_live_site."/index.php?option=$component&task=activate&activation=".$user->get('activation');
$this->_sendMail( $namee , $emaill, $usern, $pwd, $activation_link);
/************************************************** Spinz ********************************************/
Note : Here we created the mail function for username and password to users mail.
administrator/components/com_virtuemart/classses/ps_shopper.php
Need to comment the line in function register_save() before "return true" line:
// Send the registration email
//$this->_sendMail( $name, $email, $username, $password, $activation_link );
Note: Here the mail function generated we need to comment that mail functions and create another mail function in add() function of ps_shopper.php in first point.
administrator/components/com_virtuemart/classses/ps_shopper.php
Need to get the extra added field (extra_field_1) in jos_vm_user_info table in the function _sendmail() with following code and that field sent through the mail to user.
/****************************************************************/
$db = JFactory::getDBO();
$query = "SELECT id, name, email, username"
. "\n FROM #__users"
. "\n ORDER by id DESC LIMIT 1"
;
$db->setQuery( $query );
$rows = $db->loadObjectList();
$lid = $rows[0]->id;
$dbv = new ps_DB;
$query = "SELECT *"
. "\n FROM #__{vm}_user_info"
. "\n WHERE user_id=$lid"
;
$dbv->setQuery( $query );
$fid = $db->loadObjectList();
$field = $fid[0]->extra_field_1;
$subject = sprintf ($VM_LANG->_('SEND_SUB',false), $name, $mosConfig_sitename);
$subject = vmHtmlEntityDecode($subject, ENT_QUOTES);
if ($mosConfig_useractivation=="1"){
$message = sprintf ($VM_LANG->_('USEND_MSG_ACTIVATE',false), $name, $mosConfig_sitename, $activation_link, $mosConfig_live_site, $username, $pwd, $field );
} else {
$message = sprintf ($VM_LANG->_('PHPSHOP_USER_SEND_REGISTRATION_DETAILS',false), $name, $mosConfig_sitename, $mosConfig_live_site, $username, $pwd, $field);
}
/*************************************/
Note :
Initialize the variable "$field" get the extra added field value using query. Then that the extra field value is assigned by message section of the mail.(initialize variable $field having the a value added extra fields in virtuemart).
administrator/components/com_virtuemart/languages/common/english
replace the messages for the following code:
'USEND_MSG_ACTIVATE' => 'Hello %s,
Thank you for registering at %s. Your account is created and must be activated before you can use it.
To activate the account click on the following link or copy-paste it in your browser:
%s
After activation you may login to %s using the following username and password:
Username - %s
Password - %s
Degree - %s'
2.'PHPSHOP_USER_SEND_REGISTRATION_DETAILS' => 'Hello %s,
Thank you for registering at %s. Your customer account has been created.
You may login to %s using the following username and password:
Username - %s
Password - %s
Degree - %s
'
Note:
The extra added values assigned by the string %s in language file.
The message having the string values of extra added field value in virtuemart.
The degree shows the added extra field