I'm trying to make a system where an administrator can add multiple people at the same time into a database. I want this system to prevent the administrator from adding people with email addresses already existing in the database.
IF one of the emails in the _POST["emailaddress"] matches with one of the emailaddresses in the db, the user should get a message saying one of the emails already exists in the database. To achieve this, I've tried using the function array_intersect(). However, upon doing so I get a warning saying:
Warning: array_intersect(): Argument #2 is not an array in ... addingusers.php on line 41
At first i thought it had something to do with the fact my second argument was an associative array, so I tried the function array_intersect_assoc, which returns the same warning. How can I solve this?
The code on addingusers.php
<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors',1);
$conn = mysqli_connect('localhost','*','*','*');
$condition = false; // this is for the other part of my code which involves inserting the output into db
$name = $_POST["name"];
$affix = $_POST["affix"];
$surname = $_POST["surname"];
$emailaddress = $_POST["emailaddress"];
$password = $_POST["password"];
//amount of emailaddresses in db
$checkquery2 = mysqli_query($conn, "
SELECT COUNT(emailaddress)
FROM users
");
$result2 = mysqli_fetch_array($checkquery2);
// the previously mentioned amount is used here below
for($i=0; $i<$result2[0]; $i++){
// the actual emails in the db itself
$q1 = mysqli_query($conn, "
SELECT
emailaddress
FROM
users
");
// goes through all the emails
$result_array1 = array();
while ($row1 = mysqli_fetch_assoc($q1)) {
$result_array1[] = $row1;
}
$query1 = $result_array1[$i]["emailaddress"];
}
// HERE LIES THE ISSUE
for($i=0; $i<count($emailaddress); $i++){
if (count(array_intersect_assoc($emailaddress, $query1)) > 0) {
echo "One of the entered emails already exists in the database...";
echo '<br><button onclick="goBack()">Go Back</button>
<script>
function goBack() {
window.history.back();
}
</script><br>';
$condition = false;
}
else{
$condition = true;
}
}
EDIT
as the comments point out, $query1 is indeed not an array it is a string. However, the problem remains even IF i remove the index and "[emailaddress]", as in, the code always opts to the else-statement and never to if.
$query1 is not an array, it's just one email address. You should be pushing onto it in the loop, not overwriting it.
You also have more loops than you need. You don't need to perform SELECT emailaddress FROM users query in a loop, and you don't need to check the intersection in a loop. And since you don't need those loops, you don't need to get the count first.
<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors',1);
$conn = mysqli_connect('localhost','*','*','*');
$condition = false; // this is for the other part of my code which involves inserting the output into db
$name = $_POST["name"];
$affix = $_POST["affix"];
$surname = $_POST["surname"];
$emailaddress = $_POST["emailaddress"];
$password = $_POST["password"];
$q1 = mysqli_query($conn, "
SELECT
emailaddress
FROM
users
");
// goes through all the emails
$result_array1 = array();
while ($row1 = mysqli_fetch_assoc($q1)) {
$result_array1[] = $row1['emailaddress'];
}
$existing_addresses = array_intersect($emailaddress, $result_array1);
if (count($existing_addresses) > 0) {
echo "Some of the entered emails already exists in the database: <br>" . implode(', ', $existing_addresses);
echo '<br><button onclick="goBack()">Go Back</button>
<script>
function goBack() {
window.history.back();
}
</script><br>';
$condition = false;
}
else{
$condition = true;
}
Related
I'm using a fetchAll and a for loop to do the trick. In the if statement with $validate as result I tried numbers, boolean and now strings to get the result. Nothing worked so far. Here is my code:
$groep_naam = $_POST['groep'];
$naam = $_POST['naam'];
$adres = $_POST['adres'];
$mail2 = $_POST['mail2'];
$pass1 = md5($_POST['pass1']);
$pass2 = md5($_POST['pass2']);
$select = $db->prepare("SELECT * FROM deelnemers");
$select->execute();
$result = $select->fetchAll();
$len = count($result);
for ($x=0;$x<$len;$x++) {
$mail1 = $_POST['mail1'];
$db_mail = $result[$x][mail];
if ($db_mail != $mail1) {
$validate = "true";
}
if ($db_mail == $mail1) {
$validate = "false";
}
}
if (isset($_POST['submit'])) {
if ($mail1 == $mail2 && $pass1 == $pass2) {
if ($validate == "true") {
$add = $db->prepare("INSERT INTO deelnemers (groep_naam, naam, adres, mail, pass, rechten) VALUES ('$groep_naam', '$naam', '$adres', '$mail1', '$pass1', 'user')");
$add->execute();
} if ($validate == "false") {
echo '
<script>
$("#duplicateEntry").modal("show");
</script>
';
}
You are doing it wrong. Instead of fetching all emails, you should do a query to check if that particular email exists in db.
Pseudocode:
$select = $db->prepare("SELECT 1 FROM deelnemers WHERE mail = :email");
$select->bindValue(':email', $_POST['mail1']);
$select->execute();
$validate = $select->rowCount() > 0; //rowCount/rowExists/whatever to check if the query returned anything
Looking at your current code, probable mistake is on line
$db_mail = $result[$x][mail];
It probably should've been
$db_mail = $result[$x]['mail'];
Another thing, you loop through all emails comparing them with the one from request, so even if you find the one email matching it, later in another loop you rewrite your $validate value.
end web developer, i was given a CMS done from another team and i have to link with my front-end. I have made some modifications, but due to my lack of php knowledge i have some issue here.
My users are able to fill up a form, where 1 text field is asking for their photo link. I want to check for if the value entered is not equal to what i want, then i will query insert a default avatar photo link to mysql to process.
code that i tried on php
// check if the variable $photo is empty, if it is, insert the default image link
if($photo = ""){
$photo="images/avatarDefault.png";
}
doesn't seem to work
<?php
if($_SERVER["REQUEST_METHOD"] === "POST")
{
//Used to establish connection with the database
include 'dbAuthen.php';
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else
{
//Used to Validate User input
$valid = true;
//Getting Data from the POST
$username = sanitizeInput($_POST['username']);
$displayname = sanitizeInput($_POST['displayname']);
$password = sanitizeInput($_POST['password']);
//hash the password using Bcrypt - this is to prevent
//incompatibility from using PASSWORD_DEFAULT when the default PHP hashing algorithm is changed from bcrypt
$hashed_password = password_hash($password, PASSWORD_BCRYPT);
//Determining Type of the User
//if B - User is student
//if A - User is adin
if($_POST['type'] == 'true')
$type = 'B';
else
$type = 'A';
$email = sanitizeInput($_POST['email']);
$tutorGroup = sanitizeInput($_POST['tutorGroup']);
$courseID = sanitizeInput($_POST['courseID']);
$description = sanitizeInput($_POST['desc']);
$courseYear = date("Y");
$website = sanitizeInput($_POST['website']);
$skillSets = sanitizeInput($_POST['skillSets']);
$specialisation = sanitizeInput($_POST['specialisation']);
$photo = sanitizeInput($_POST['photo']);
// this is what i tried, checking if the value entered is empty, but doesn't work
if($photo = ""){
$photo="images/avatarDefault.png";
}
$resume = sanitizeInput($_POST['resume']);
//Validation for Username
$sql = "SELECT * FROM Users WHERE UserID= '$username'";
if (mysqli_num_rows(mysqli_query($con,$sql)) > 0){
echo 'User already exists! Please Change the Username!<br>';
$valid = false;
}
if($valid){
//Incomplete SQL Query
$sql = "INSERT INTO Users
VALUES ('$username','$displayname','$hashed_password','$type','$email', '$tutorGroup', ";
//Conditionally Concatenate Values
if(empty($courseID))
{
$sql = $sql . "NULL";
}
else
{
$sql = $sql . " '$courseID' ";
}
//Completed SQL Query
$sql = $sql . ", '$description', '$skillSets', '$specialisation', '$website', '$courseYear', '$photo', '$resume', DEFAULT)";
//retval from the SQL Query
if (!mysqli_query($con,$sql))
{
echo '*Error*: '. mysqli_error($con);
}
else
{
echo "*Success*: User Added!";
}
}
//if student create folder for them
if ($type == 'B')
{
//Store current reporting error
$oldErrorReporting = error_reporting();
//Remove E_WARNING from current error reporting level to prevent users from seeing code
error_reporting($oldErrorReporting ^ E_WARNING);
//Set current reporting error();
error_reporting($oldErrorReporting);
}
mysqli_close($con);
}
}
function sanitizeInput($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
i've tried finding a way on mysql to insert default values but it seem impossible, so i have no choice but to query insert through php.
I have the logic but i'm not sure how to implement on the php with my lack of knowledge, i was thinking of checking either
1) if the photo link does not have the word .png/.jpg, $photo != ".png"
2) if the photo link length is too low $.photo.length < 10
can someone help me look into the code and tell me what i'm doing wrong? Thanks!
A very simple way with default values could be:
$photo = isset($photo) ? $photo : 'images/avatarDefault.png' ;
How it works is that it first it asks if the photo is set, if it is, use all ready inserted value, otherwise insert your default value,
Another (very alike) method to use:
$photo = !empty($photo) ? $photo : 'images/avatarDefault.png' ;
UPDATE
To check if it contains a certain "extension" would be a simple rewrite
$photo = preg_match('#\b(.jpg|.png)\b#', $photo ) ? $photo : "images/avatarDefault.png" ;
This way it checks wether the text / image link in $photo contains the .png file type, if it doesn't it inserts your default image
First thing that I notice is to use double =
if($photo == ""){
//...
}
I am getting the id from another page but i am not being able to pass it to the sql query. If i define any value to $id instead of 0 then the query works but otherwise it fails.
Secondly, i would like to display the values of the array in respective input fields. I tried using
<?php
echo $result_array['institutename'][0];
?>
in the body part but it didnt work out.
My rest code is as follows:
(I know the mysql functions are deprecated but i would move on to mysqli as soon as i have solved this problem)
<?php
include 'connect.php';
$id=0;
$result_array=array();
if(isset($_REQUEST['id'])){
$id=(int)$_REQUEST['id'];
//$uid=$id;
if(!empty($id)){
$sql = "SELECT * FROM institute WHERE id =$id";
$result = mysql_query($sql);
while($row = mysql_fetch_assoc($result)){
$result_array[]=$row;
}
}
}
if ($_SERVER['REQUEST_METHOD'] == 'POST' && $_POST['form_institutedetails'] == 'saveinstitutedetails')
{
$mysql_table='institute';
$institutename = $_POST['institutename'];
$established = $_POST['established'];
$regno = $_POST['reg_no'];
$branch = $_POST['branch'];
$initials = $_POST['initials'];
$address=$_POST['address'];
$pin=$_POST['pin'];
$contact1=$_POST['contact1'];
$contact2=$_POST['contact2'];
$contact3=$_POST['contact3'];
$fax1=$_POST['fax1'];
$fax2=$_POST['fax2'];
$email=$_POST['email'];
$website=$_POST['website'];
if(isset($_POST['head_office'])){
$head_office=$_POST['head_office'];
}
else{
$head_office="Branch";
}
if (!preg_match("/^.+#.+\..+$/", $email))
{
$error_message = 'Email is not a valid email address. Please check and try again.';
}
if (empty($error_message))
{
$newinstitutename = mysql_real_escape_string($institutename);
$newestablished = mysql_real_escape_string($established);
$newregno = mysql_real_escape_string($regno);
$newbranch = mysql_real_escape_string($branch);
$newaddress = mysql_real_escape_string($address);
$newpin = mysql_real_escape_string($pin);
$newemail = mysql_real_escape_string($email);
$newwebsite = mysql_real_escape_string($website);
$ho = mysql_real_escape_string($head_office);
include 'connect.php';
$sql = "UPDATE `".$mysql_table."` SET `institutename`='$newinstitutename', `established`='$newestablished', `regno`='$newregno', `branch`='$newbranch', `initials`='$initials', `address`='$newaddress', `pin`='$newpin', `contact1`='$contact1', `contact2`='$contact2', `contact3`='$contact3', `fax1`='$fax1', `fax2`='$fax2', `email`='$newemail', `website`='$newwebsite', `head_office`='$ho' WHERE `id`=$id";
$result = mysql_query($sql, $db);
mysql_close($db);
$error_message='Updated Successfully!.';
}
}
?>
When you are unsure about the structure of an array, you can always do a print_r during development.
print_r($result_array);
In this case, it is an index array of associative arrays.
To access the first record's institutename (and probably the only record since it looks like you used an unique key in your query), you can use
echo $result_array[0]['institutename'];
I try to get the data from database to display data via ajax but failed to worked. It's partially working because data from mysql make this thing failed to function.
Here is my funds_transfer_backend.php page. This page will assign variable to json array.
session_start();
if(!isset($_SESSION['myusername']))
{
header("Location: ../index.html");
die();
}
include("../connect.php");
$myusername = $_SESSION['myusername'];
$sql="SELECT client_id FROM `client` WHERE username='$myusername'";
$result=mysqli_query($conn, $sql);
while ($row=mysqli_fetch_row($result)){
$id = $row['0'];
}
$index_num = $_POST['index_num'];
$to_account_num = $_POST['recipient'];
$amount = $_POST['amount'];
if ($amount == '' || $to_account_num == '' || $index_num == -1){
//echo "Please complete the form!";
$response = -1;
}
else {
// check account number exist
$query2 = "SELECT 1 FROM account WHERE id='$to_account_num' LIMIT 1";
if (mysqli_num_rows(mysqli_query($conn, $query2))!=1) {
//echo "Recipient account number is invalid!";
$response = -2;
}
else {
$query2 = "SELECT client.name, client.email FROM account JOIN client USING (client_id) WHERE account.id = '$to_account_num' LIMIT 1";
$result=mysqli_query($conn, $query2);
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$name = $row['name'];
$email = $row['email'];
}
$response = 1;
}
} // check account num else bracket
$display = array('response' => $response, 'name' => $name);
echo json_encode($display);
However if I remove 'name' => $name from array the #stage div will trigger like image below:
Here is my funds_transfer.php page
<script type="text/javascript">
function update() {
var two = $('#index_num').val();
var three = $('#recipient_box').val();
var five = $('#amount_box').val();
$.post("funds_transfer_backend.php", {
index_num : two,
recipient : three,
amount : five
},function(data){
if (data.response==-1) {
$('#stage').show().html("Please complete the form!");
}
$('#stage').delay(2000).fadeOut();
},"json");
}
</script>
...other code goes here
<div id="stage" style="background-color:#FF6666; padding-left:20px; color: white;"></div>
<div id="confirm" style="background-color:#FF7800; padding-left:20px; color: white;"></div>
I try to check the data from db whether it exist using manual form method="post" and I can see the name being echo. Any help is appreciated and thanks in advance.
When your response is -1, your $name variable is undefined. So php could show a warning (depending on your settings) and you are trying to add an undefined variable to your array. This will invalidate your output / json.
You can set for example:
$name = '';
at the start of your script or check whether the variable is set with isset($name) before you try to use it to avoid these problems.
There are of course other solutions, like outputting your -1 directly and exiting the script there.
I always initialize my variables.
$myusername = isset($_SESSION['myusername']) ? $_SESSION['myusername'] : false;
Then you can safely do:
if ($myusername) {} without throwing warnings.
I do this weather I get my data from a db, post/get/session or json/ajax.
It takes a little extra time upfront but removes dozens of errors in the back end so you net more time.
I have a signup page on my website where a user must provide a email address and password only.
I want to be able to create a username for this user automatically by using the first part of the email provided;
User supplies gordon#yourdomain.com, i want to make username 'gordon'
I don't need explanation on how to create form or submission of data to database, just the code to extract data from email provided, and if necessary, if duplicate occurs add number to end.
Hope this makes sense, seems like a basic function but couldn't find examples of it anywhere on net!
This is not a good idea, just use their full email address. The following email addresses could be different people, but they will become the same under your system.
samename#gmail.com
samename#yahoo.com
Adding a number to the end will make the user remember something unique to your system and cause much confusion on their end.
Agreed, you're stripping a necessarily unique ID into a non-unique ID. Unless you want to add some sort of handling to add a number to the username or something. If that's what you really want to do, this should set $username to the stuff before the email address:
<?php
$username = preg_replace('/([^#]*).*/', '$1', $email);
?>
Something like:
$username = left($email, stripos($email, '#'));
should do. You may want to learn regular expressions for these kinds of task.
Then you add the counter:
function countOccurrences($name)
{
$con = mysql_connect(___, ___, ___);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db(___, $con);
$result = mysql_query("
SELECT COUNT(*) AS countOccurrences
FROM users
WHERE username LIKE '" . mysql_real_escape_string($name, $con) . "%'
");
$row = mysql_fetch_array($result);
$number = $row['countOccurrences'];
mysql_close($con);
return $number;
}
and then:
$countUsers = countOccurrences($username);
if ($countUsers>0)
{
$username = $username . $countUsers;
}
IMPORTANT: Consider using the whole email as username: you don't want gordon#flash.net to be considered equal to gordon#clash.com
NOTE: example code counts gordon, gordon1, gordon2 but gordonbah, gordonq, gordonxxx too
NOTE: this is pretty rough, and should not be considered best PHP practice; it's just to give the general idea
$username = gordon#example.com;
$username_arr = explode('#',$username);
$username = $username_arr[0];
if( !is_taken( $username ) )
{
//The name is not taken.
}
else
{
//The name is taken, add numbers and do the search again.
}
function is_taken( $username )
{
$db_link = mysql_connect($host,$user,$pass) or die('Could not connect to database');
$username = mysql_real_escape_string( $username );
$sql = "SELECT * FROM `database`.`users` WHERE `username` = '$username'";
$res = mysql_query( $sql , $db_link );
return mysql_num_rows( $res ) == 1;
}
<?php
preg_match('/[^#]+)#/',$email,$matches);
$username = $matches[1];
check_availability($username);
?>
Should suit your needs :D
$username = substr($username, 0, strpos($username, '#'));
$username = mysql_real_escape_string($username);
$result = mysql_query('SELECT `username` FROM `users` WHERE `username` = \'' . $username . '%\';');
if (mysql_num_rows($result) > 0) {
$i = 0;
while ($name_arr = mysql_fetch_assoc($result)) {
$name = $name_arr['username'];
$after = substr($name, strlen($username));
if (ctype_digit($after)) {
if (($after = (int) $after) > $i) {
$i = $after;
}
}
}
if ($i > 0) {
$username .= $i;
}
}
As of PHP 5.3.0 you can also use:
$email = 'test#stackoverflow.com';
$user = strstr($email, '#', true);
This will return all the string from the beginning to the first occurrence of '#'. Which in this case is:
test
I use something like this,
$cust_email = "test#gmail.com";
$parts = explode("#", $cust_email);
$cust_name = $parts[0];
I use to set default User Name if user do not set his / her name in the profile.
You can use strstr function to find specific word from string
<?php
$username = strstr("username#domain.com",'#',true); //get text before #
/*
echo strstr("username#domain.com","#"); // get text after #
*/
check_availability($username);
?>