Check for a multiple amount of information in a database - php

For my registration system, when the user registers, I want to make sure that their username, email, etc. is not taken. I have the code to check to see if the username exists, and I can probably do the same with the other stuff.
How can I do this without rewriting the block multiple times?
tl;dr: How can I check for more things in a database in a compact way?
$userquery = "SELECT * FROM users WHERE username = '$username'";
if ($result = $mysqli->query($userquery)) {
if ($result->num_rows > 0) {
die ("Username Already Exists.");
}
}

Use an 'OR' condition in your where clause
$userquery = "SELECT * FROM users WHERE username = '$username' OR email= '$email'";
if ($result = $mysqli->query($userquery)) {
if ($result->num_rows > 0) {
die ("Username/Email Already Exists.");
}
}
EDIT
ok then,
function doesitexist($mysqli,$table,$field,$value) {
$userquery = "SELECT * FROM $table WHERE $field = '$value' LIMIT 1";
if ($result = $mysqli->query($userquery)) {
if ($result->num_rows > 0) {
return true;
} else {
return false;
}
} else {
return('Error running Query');
}
}
ANOTHER EDIT just for fun. This should take an array of fields and values to check in one call.
$check = doesitexist($mysqli,'users',array('username'=>'bob','email'=>'someone#example.com'));
function doesitexist($mysqli,$table,$tocheck = array()) {
if (count($tocheck)>0) {
$where = '';
foreach ($tocheck as $field=>$value) {
$where .= $field." = '".addslashes($value)."' OR ";
}
$where = trim($where," OR ");
$userquery = "SELECT * FROM $table WHERE $where LIMIT 1";
if ($result = $mysqli->query($userquery)) {
if ($result->num_rows > 0) {
return true;
} else {
return false;
}
} else {
return('Error running Query');
}
} else {
return("No Fields/Values to check");
}
}

Related

SQL pulling first character of each column

So I've got a dropdown that has a list of customers that you can select from. It uses a function (that someone else built) which works fine when there are 2 or more customers but dies when there it only one. When there's one customer, each item in the dropdown is the first character of each column for that one customer.
Here is the function:
function getCustomerBy($column = "",$value = "")
{
global $conn;
if ($value == '')
{
return(null);
}
$sel = "SELECT
customers.*,
customerStatus.code customerStatus
FROM customers,
customerStatus
WHERE customer_id
and customerStatus.id = customers.customerStatus_id and ". mysqli_real_escape_string($conn,$column) ."='". mysqli_real_escape_string($conn,$value) ."'";
// error_log($sel);
$run = mysqli_query($conn, $sel);
$check = mysqli_num_rows($run);
if ($check ==1)
{
$row = mysqli_fetch_assoc($run);
return($row);
}
elseif($check >1)
{
$rows = array();
while ($row = mysqli_fetch_assoc($run))
{
$rows[] = $row;
}
return($rows);
}
else
{
return(null);
}
}
I'm fairly certain that it's the ($check == 1) stuff but I can't work out the best way to re-do all of that to make it work without causing other errors (specifically "cannot modify header")
This is what's called up on the page with the dropdown:
$customers = getCustomerBy('users_user_id',$user['user_id']);
Also, here is the code for the dropdown:
<?
foreach ($customers as $customer)
{
$selected = '';
if (isset($gig['customers_customer_id']) && $customer['customer_id'] == $gig['customers_customer_id'])
{
$selected = ' selected ';
}
echo "\t<option value=\"".$customer['customer_id']."\" $selected>".$customer['customer_company_name']."</option>";
}
?>
The code that builds the dropdown is expecting an array of arrays, but instead when it's a single row you're passing it an array of strings. Treat both cases ($check > 0) the same.
function getCustomerBy($column = "",$value = "")
{
global $conn;
if ($value == '')
{
return(null);
}
$sel = "SELECT
customers.*,
customerStatus.code customerStatus
FROM customers,
customerStatus
WHERE customer_id
and customerStatus.id = customers.customerStatus_id and ". mysqli_real_escape_string($conn,$column) ."='". mysqli_real_escape_string($conn,$value) ."'";
// error_log($sel);
$run = mysqli_query($conn, $sel);
$check = mysqli_num_rows($run);
if($check > 0)
{
$rows = array();
while ($row = mysqli_fetch_assoc($run))
{
$rows[] = $row;
}
return($rows);
}
else
{
return(null);
}
}
I assume there's copy/paste errors in your query because it doesn't look right.
I don't know how the returning array is used by the rest of your code but you can try the following:
Change:
if ($check ==1) {
$row = mysqli_fetch_assoc($run);
return($row);
}
To this:
if ($check == 1) {
$rows = array();
$rows[] = mysqli_fetch_assoc($run);
return($rows);
}

My function is returning false when it should return true

My function is always returning false when it should return true, and I can't find why
public function isReselling($key)
{
if ($this->validateKey($key)) {
return false;
}
$apis = mysql_connect("mysql.hostinger.fr", "u770656121_uapi", "testpass") or die(mysql_error());
mysql_select_db("u770656121_api", $apis);
$sql = "
SELECT * FROM api_id
";
$result = mysql_query($sql, $apis);
while($row = mysql_fetch_array($result)) {
$blacklisttho = $row['Banned'];
if ($blacklisttho == 1) {
return true;
}
}
return false;
}
Well, you need to check where exactly the 'return' is beign made, and investigate based on that:
public function isReselling($key)
{
if ($this->validateKey($key)) {
die('validate fails');
return false;
}
$apis = mysql_connect("mysql.hostinger.fr", "u770656121_uapi", "testpass") or die(mysql_error());
mysql_select_db("u770656121_api", $apis);
$sql = "
SELECT * FROM api_id
";
$result = mysql_query($sql, $apis);
while($row = mysql_fetch_array($result)) {
$blacklisttho = $row['Banned'];
if ($blacklisttho == 1) {
return true;
}
}
die('no results.');
return false;
}
and btw, you don't want to have multiple 'returns' around the code, that's bad practice.
I would change your code to something like:
public function isReselling($key)
{
$retValue = false;
if ($this->validateKey($key) === false) {
$apis = mysql_connect("mysql.hostinger.fr", "u770656121_uapi", "testpass") or die(mysql_error());
mysql_select_db("u770656121_api", $apis);
$sql = "SELECT * FROM api_id";
$result = mysql_query($sql, $apis);
while($row = mysql_fetch_array($result)) {
if ($row['Banned'] == 1) {
$retValue = true;
break;
}
}
}
return $retValue;
}

both if and else statements excecuting

I've got a weird problem: both my if and else statements are executing. Here's my code:
if ($sel_user['name'] != $name) {
$query = "UPDATE owner SET
..."
$result = mysql_query($query);
if (mysql_affected_rows() ==1) {
$query2 = "UPDATE queue_acl SET
..."
$result2 = mysql_query($query2);
if (mysql_affected_rows() ==1) {
$_SESSION['updates_occurred'] = true;
} else {
$_SESSION['updates_occurred'] = false;
}
}
}
if ($sel_user['orgId'] != $orgId) {
$query = "UPDATE ownerOrganization SET
..."
$result = mysql_query($query);
if (mysql_affected_rows() ==1) {
$query2 = "UPDATE queue_acl SET
..."
$result2 = mysql_query($query2);
if (mysql_affected_rows() ==1) {
$_SESSION['updates_occurred'] = true;
} else {
$_SESSION['updates_occurred'] = false;
}
}
}
if ($sel_user['date_expires'] != $colVal[0] ||
$sel_user['admin'] != $colVal[4]) {
$query3 = "UPDATE queue_acl SET
..."
$result3 = mysql_query($query3);
if (mysql_affected_rows() ==1){
$_SESSION['updates_occurred'] = true;
} else {
$_SESSION['updates_occurred'] = false;
}
} else {
$_SESSION['updates_occurred'] = false;
$message = "<i>There were no edits to apply</i>";
}
When I run this, the queries are being sent and everything is being updated fine, but the "There were no edits" message is also being printed
Anyone know why?
EDIT: I do not want to use elseif statements; the events are not mutually exclusive. That is, if $sel_user['name'] != $name AND $sel_user['orgId'] != $orgId, it is required that both queries are sent
If you don't want to wrap everything in an if/else if statements, one could set a flag at the end of each if check.
if($sel_user['name'] != $name) {
// CODE HERE
$flag = true;
}
if(!$flag){
$message = "<i>There were no edits to apply</i>";
}
It's that or you can run the if check off $_SESSION['updates_occurred']
Instead of doing lots of ifs, you should be doing elseifs
i.e.
if () {
} elseif () {
} else {
}
hope that helps.
if(!printf("Hello")) {
echo "Hello";
}
else {
echo " World";
}

Is there a more clear and efficient way to rewrite this function?

I am trying to rewrite the following function in different way but it seems that I missed something and I do not get the intended functionality?
Could anyone suggest anything?
Thanks in advance.
Function 1
function user_exists($email) {
$email=mysql_real_escape_string($email);
$query=mysql_query("SELECT COUNT (`user_id`) FROM `users` WHERE `email` = '$email'");
return(mysql_result($query, 0) == 1) ? true : false;
}
Rewritten Function 1
function user_exists($email) {
$email=mysql_real_escape_string($email);
$query=mysql_query("SELECT user_id FROM users WHERE email='$email'");
$count=mysql_num_rows($query);
if ($query !=0) {
return(true);
} else{
return(false)
}
function user_exists($email)
{
$email = mysql_real_escape_string($email);
$query = mysql_query("SELECT user_id FROM users WHERE email='$email'");
if (mysql_num_rows($query) > 0)
{
return true;
}
else
{
return false;
}
}
function user_exists($email) {
// Escape to prevent sql injection
$email = mysql_real_escape_string($email);
// Query to see if the email exists in the DB
if(false === ($query = mysql_query("SELECT user_id FROM users WHERE email='$email'"))){
// handle error
$result = false;
}
else{
// Find a row? Email exists, otherwise does not
$result = (mysql_num_rows($query) > 0);
}
return $result;
}
The DB query itself could be more efficient (select a count, or at least limit to 1 result max), but this is the general idea.
function user_exists($email) {
$email=mysql_real_escape_string($email);
$query=mysql_query("SELECT user_id FROM users WHERE email='$email' LIMIT 1");
return mysql_num_rows($query) == 1;
}
LIMIT 1 is a good practice since the engine stop searching on the first match and does not continue for the next rows
<?php
function user_exists($email)
{
// Perform database query
$email = mysql_query("SELECT user_id FROM users WHERE email='$email'");
if (!$email) {
die("Database query failed: " . mysql_error());
}
// Use returned data
while ($row = mysql_real_escape_string($email)) {
if ($row !=0) {
return(true);
}
}
}
?>

mysql_query() failing very oddly

This is a really simple thing, but it's not working for some reason. Heres my code.
I am making function (its part of a class) which checks if a username or email exists:
public function exists ($what, $who)
{
$sql = "SELECT * FROM users WHERE $what = $who";
$query = mysql_query($sql);
if (mysql_num_rows($query) != 0)
{
return true;
}
else
{
return false;
}
}
The function returns nothing. In fact if I run that query through regular PHP it returns nothing also. I don't understand why.
This following piece of code returns news entries perfectly:
function fetch($id = '')
{
if (empty($id))
{
$query = 'SELECT * FROM news ORDER BY id desc';
}
elseif (is_numeric($id))
{
$query = "SELECT * FROM news WHERE id = $id";
}
else
{
$route->to(SITE_URL);
}
$result = mysql_query($query);
if (mysql_num_rows($result) > 0)
{
return $result;
}
}
I am confused.
The problem is that you are missing quotes in your query:
$sql = "SELECT * FROM users WHERE $what = $who";
//SELECT * FROM users WHERE username = Mario is not a valid query
should be:
$sql = "SELECT * FROM users WHERE $what = '$who'";
the other queries are working because you are checking against an id, in this case against a string (and in this case you need quotes)
maybe the query execution failed and you have error turned off on screen in your php.ini
Try to add an intermediate check on the correct execution of the query:
$query = mysql_query($sql);
if ($query === FALSE) {
// log error with mysql_errno($conn) and mysql_error($conn);
} else {
if (mysql_num_rows($query) != 0) {
return true;
etc. etc.

Categories