Can't execute else in conditional logic - php

I have this code which is supposed to insert some data if certain conditions are met. The first 3 parts of the conditional logic work perfectly bu the else seems not to be executing if the data is a string.
In summary, if the $USSD_STRING is is an integer is(12345) the query executes perfectly. But if there is a letter at the beginning of the value i.e. (AA12345) the else seems not to be working.
I have tried this:
elseif (is_string("$USSD_STRING")) {
$sql = "INSERT INTO userlevel SET phone_number = '$MSISDN', ussd_string = '$USSD_STRING', user_level = '$level', session_id = '$SESSION_ID', mno_id = '$MNOID', partner_id = '$PartnerId'";
$result=mysql_query($sql);
}
but its not working either.
if ( $USSD_STRING <=0) {
}
elseif ( $USSD_STRING ==1) {
$sql = "INSERT INTO userlevel SET phone_number = '$MSISDN', ussd_string = '$USSD_STRING', user_level = '$level', session_id = '$SESSION_ID', mno_id = '$MNOID', partner_id = '$PartnerId'";
$result=mysql_query($sql);
}
elseif ( $USSD_STRING ==2) {
$sql = "INSERT INTO userlevel SET phone_number = '$MSISDN', ussd_string = '$USSD_STRING', user_level = '$level', session_id = '$SESSION_ID', mno_id = '$MNOID', partner_id = '$PartnerId'";
$result=mysql_query($sql);
}
else {
$sql = "INSERT INTO userlevel SET phone_number = '$MSISDN', ussd_string = '$USSD_STRING', user_level = '$level', session_id = '$SESSION_ID', mno_id = '$MNOID', partner_id = '$PartnerId'";
$result=mysql_query($sql);
}
Any workarounds?

I will bet that you are declaring your variable in quotes, something you did not post in your question.
However, I could be wrong. But nonetheless, you have a few options for you below.
The following (and as an example)
$USSD_STRING = "12345";
or
$USSD_STRING = $_POST['var'];
Even though that is technically an integer (being set in quotes), it will still be interpreted as a string using the is_string() function.
"Any workarounds?"
Yes, you have a few.
Using the following will qualify as not being a string using the is_string() function.
$USSD_STRING = 12345;
You would be best using ctype_digit() for this.
$USSD_STRING = "a12345"; // fail
The following will pass as an integer even though it is inside quotes
$USSD_STRING = "12345"; // pass as an integer
if (ctype_digit($USSD_STRING)) {
...
}
while the following will fail if a letter is introduced
$USSD_STRING = "a12345"; // fail. It contains a letter
if (ctype_digit($USSD_STRING)) {
...
}
Another option available for you to use, would be FILTER_VALIDATE_INT.
if(filter_var($USSD_STRING, FILTER_VALIDATE_INT))
Where it will fail with
$USSD_STRING = "a12345";
but pass as (and even inside quotes):
$USSD_STRING = "12345";
References:
http://php.net/manual/en/function.ctype-digit.php
http://php.net/manual/en/function.filter-var.php

Related

How to get response from MySQL database using PHP

I'm working with a system that assigns files to users. Problem is, that the response, userid, is always 0.
$user = htmlentities($_SESSION['username']);
$sql = "INSERT INTO `files`(
`userid`,
`filename`,
`filesize`,
`filetype`,
`filepath`
)
VALUES
(\"". get_user_id($user). "\",\"".
$_FILES['userfile']['name']. "\",\"".
$_FILES['userfile']['size']. "\",\"".
$_FILES['userfile']['type']. "\",\"".
$fileadress.
"\")";
Function get_user_id
function get_user_id($user){
mysql_connect(HOST, USER, PASSWORD)
or die(mysql_error());
$sqlinit = "USE secure_login";
mysql_query($sqlinit);
$sql = "SELECT `id` FROM `members` WHERE `username` = '". $user."'";
$result = mysql_query($sql);
//mysql_fetch_array($result);
echo mysql_error();
$userid = $result;
return $userid;
}
No errors, no warnings, everything else is working fine, only userid is showing always 0, even when id in members is 1,2 etc. Am I missing something? In both tables, userid and id are int.
mysql_query() returns you a mysql object, you put this object in the result variable. So if you do $userid = $result; you just duplicate the array to a new variable.
You're not accessing correctly to the element, you should write instead : $userid = $result['id'];
Take the habit to employ var_dump($result); to see what's exactly in you're variable (here result)
EDIT:
$sql = "SELECT id FROM members WHERE username = '". $user."'";
$queryRes = mysql_query($sql);
$result = mysql_fetch_array($queryRes);
$userid = $result['id'];
I believe you have to use $userid=$result['id']
As per your table, the right index would be userid
i.e:
$userid = $result['id'];

PHP How to check if a string already exists in a MySQL table

I'm having a user enter a desired name, then check the database to see if it exists before I make it. It's not working properly though, sometimes it echos the right thing, sometimes not.
$makeName = $_POST["userName"];
$nameFind = "SELECT userName FROM usertable WHERE userName = $makeName";
$nameCompare = mysqli_query($con, $nameFind);
if($nameCompare == false)
{
echo "This is a new name";
}
else
{
echo "Pick a new name please";
}
The query doesn't fail just because it returns no rows. Use mysqli_num_rows() to find out if there was a match or not.
Also xkcd
Don't do it that way.
Instead,
Create a unique constraint on the column "username".
Insert the user's desired name.
Trap the error when the desired name already exists.
Why? Your approach always requires two round-trips to the database, and it doesn't account for errors. And you have to trap errors anyway; there are lots of things that can go wrong with an insert statement.
Use quotes and escaping:
"select userName FROM usertable WHERE userName = '" . mysqli_real_escape_string($makeName) . "'"
And then use mysqli_num_rows()
$result = mysqli_query($query); $num_rows = mysqli_num_rows($result);
if(mysqli_num_rows($nameCompare))
{
echo "Pick a new name please";
}
else
{
echo "This is a new name";
}
this will check the result, if there is a row, it's already used.
You need two queries for that anyways
$username = mysqli_real_escape_string($con,$username);
$query = "SELECT * FROM tbl_login WHERE username='$username'";
$result = mysqli_query($con,$query)or die(mysqli_error());
$num_row = mysqli_num_rows($result);
$row=mysqli_fetch_array($result);
if( $num_row ==1 ) {
echo 'false';
}
else{
$query_insert = "INSERT INTO login (username, password)VALUES ('$username','$password');";
$result = mysqli_query($con,$query_insert) or die(mysqli_error());
}

INSERT Email address, but ignore (if exists || if suffix = existing suffix && sender name =existingsender name) MYSQL

I'm trying to insert a query into mysql using php, but to have restrictions.
$sql_insert = "
INSERT IGNORE
into `email`
(`message`,`useremail`,`senderemail`)
VALUES
('$emailmessage','$email_address','$fromaddress')
WHERE
";
$fromaddress is the value I want to make the constraints.
Here's an example
"Zazzle" <sender-1234#zazzle.com>
Don't insert if sender-1234#zazzle.com is in the senderemail field
Don't insert if "Zazzle" is in the field and if #zazzle.com is also in the field.
you can pull the email apart and then check the database to see if it exists in the database using preg_match. If using the example:
--"Zazzle" <sender-1234#zazzle.com>
$atIndex = strrpos($fromaddress, "#");
$nameIndex = strrpos($fromaddress, "<");
$domain = substr($fromaddress, $atIndex+1); # returns zazzle.com
$local = substr($fromaddress, $nameIndex+1, $atIndex); # returns sender-123
$name = substring($fromaddress, 0, $nameIndex-1); # returns "Zazzle"
from there all you have to do is do a select/where query and if no results then to insert.
$query = "SELECT * FROM email WHERE senderemail like '".$domain."'";
$result=mysql_query($query);
$num=mysql_num_rows($result);
OR
$query = "SELECT * FROM email";
$result=mysql_query($query);
while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
if(preg_match($domain, $row['senderemail'])) { $isPresent = true; }
}
Preg match will look for the strings in the individual returned value and if present set a value to true. Then you can compare that value to be true/false and then to update your database.

major trouble matching selecting most current row

I am having major trouble selecting the most current/matching row in my database.
For example:
$query = "SELECT * FROM `Password_Reset`";
$request = mysql_query($query,$connection) or die(mysql_error());
$result = mysql_fetch_array($request);
$result['token'] is taking the first row's no matter what every time the query is run.
I am pretty sure it has to do with not being specific enough with my select query but I have not found a way to match it up.
to be even MORE specific. This is the whole query:
$query = "SELECT * FROM `Password_Reset`";
$request = mysql_query($query,$connection) or die(mysql_error());
$result = mysql_fetch_array($request);
$token = $result['token'];
$alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcedfghijklmnopqrstuvwxyz1234567890";
$rand = str_shuffle($alpha);
$salt = substr($rand,0,40);
$hashed_password = sha1($salt . $_POST['Password']);
$user_email = $result['email'];
// these should match, and do so every where else on my other pages and in the db, I'm just not able to pull the corresponding $token. its taking the $token in the first row every time.
if($get_token == $token) {
header("Location: http://www.cysticlife.org/index.php");
exit;
}else{
if(empty($_POST['Password'])) {
$valid = false;
$error_msgs[] = 'Whoops! You must enter a password.';
}
if($_POST['Password'] != $_POST['passwordConfirm'] || empty($_POST['Password'])) {
$valid = false;
$error_msgs[] = "Your password entries didn't match...was there a typo?";
}
if($valid) {
$query = "UPDATE `cysticUsers` SET `encrypted_password` = '$hashed_password' WHERE `Email` = '$user_email'";
mysql_query($query,$connection);
}
}
}
thanks in advance
If you want to order your rows by when they were submitted to the database, you will need to add an ID-Field to your table, if you haven't got one already.
It will probably be the easiest way to add an field called id to the table, set it as index and use auto_increment. Then, you can simply order your rows by ID:
SELECT * FROM `Password_Reset` ORDER BY `id` ASC
Btw, if you only need the first row, it's good to add a LIMIT 1 to your query, for better performance.

PHP Variable in Select Statement

I've written this PHP-Script which is working, and now I want to change the row name into a variable to (not sure if row is correct), I mean the "name" from the select name...
I've tried nearly everything, but nothing gave me the right result.
I know that the normal thing how I can use variables in a statement like ("'. $var .'") won't work.
<?php
require_once 'config.php';
$id = $_GET["id"]; //ID OF THE CURRENT CONTACT
$user = $_GET["user"]; //ID OF THE CURRENT USERS
$query = mysql_query("SELECT name FROM contacts WHERE contact_id='". mysql_real_escape_string( $id ) ."' and user_id='1';");
$retval = mysql_fetch_object($query)->name;
$retval = trim($retval);
echo $retval;
?>
This is much easier isn't it?
$sql_insert =
"INSERT INTO customers (
`name`,
`address`,
`email`,
`phone`
)
VALUES (
'$name',
'$address',
'$email',
'$phone'
)";
Is it this you're looking for? Even your question in German isn't that clear to me :
$field = 'name';
$query = mysql_query("SELECT $field FROM contacts WHERE contact_id='". mysql_real_escape_string( $id ) ."' and user_id='1';");
$retval = mysql_fetch_object($query)->$field;
You can usi it something like this. Currently i assume you get only one row back and want to use only one field.
<?php
require_once 'config.php';
$id = $_GET["id"]; //ID DES DERZEITIGEN KONTAKTES
$user = $_GET["user"]; //ID DES DERZEITIGEN USERS
//Use variable inside closures `` and just in case escape it, depends how you get variable
$query = mysql_query("SELECT `".mysql_real_escape_string($variable)."` FROM contacts WHERE contact_id='". mysql_real_escape_string( $id ) ."' and user_id='1';");
if (!$query) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$row = mysql_fetch_row($query); //Retriev first row, with multiple rows use mysql_fetch_assoc
$retval = $row['0']; //Retriev first field
$retval = trim($retval);
echo $retval;
?>
Please post in English. Everyone else does.
Try using a different fetch method - fetch an associative array, then use the dynamic parameter to retrieve whatever column it is you need.
Have you considered using PDO?
I believe you are confusing matters (unintentionally) due to your use of the word 'row'. Judging by your example you mean field/column. It sounds like you wish to specify the fields to select using a variable which can be done by any of these methods...
$fields = "name, age";
$sql = "SELECT $fields FROM table";
$sql = "SELECT {$fields} FROM table";
$sql = "SELECT ".$fields." FROM table";
NB it is important that you have secure date in the $fields element, I would suggest using a whitelist of allowed values i.e.
// assuming $_POST['fields'] looks something like array('name','age','hack');
$allowed = array('name', 'age');
$fields = array();
foreach ($_POST['fields'] as $field) {
if (in_array($field, $allowed)) {
$fields[] = $field;
}
$fields = implode(', ', $fields);
Wouldn't this work?
$result = mysql_fetch_array($query);
echo trim($result['name']);
You should never put a variable into field list.
If want a variable field name, select *
and then use your variable to fetch particular field
<?php
require_once 'config.php';
$id = mysql_real_escape_string($_GET["id"]); //ID DES DERZEITIGEN KONTAKTES
$user = $_GET["user"]; //ID DES DERZEITIGEN USERS
$query = "SELECT * FROM contacts WHERE contact_id='$id' and user_id='1'";
$result = mysql_query($query) or trigger_error(mysql_error().$query);
$row = mysql_fetch_array($result);
//and finally
$fieldname = "name";
$retval = $row[$fieldname];
echo $retval;
?>

Categories