Im trying to come up with MySQL logic for a search function I got on my page. Its a simple form where the user can choose to fill in search criteria. The criteria(s) is send as arguments to a function that generates the mysql logic. This is whats inside the PHP controller file:
case 'search':
if((empty($_POST['username'])) && (empty($_POST['firstname'])) && (empty($_POST['lastname']))
&& (empty($_POSt['agemin'])) && (empty($_POST['agemax'])) && (empty($_POST['country']))){
$members = get_all_username();
} else {
if(isset($_POST['username'])){
$otheruser = $_POST['username'];
} else { $otheruser = null; }
if(isset($_POST['agemin'])){
$ageMin = $_POST['agemin'];
} else { $ageMin = null; }
if(isset($_POST['agemax'])){
$ageMax = $_POST['agemax'];
} else { $ageMax = null; }
if(isset($_POST['country'])){
$country = $_POST['country'];
} else { $country = null; }
//if(isset($_POST['isonline']))
$members = search_members($otheruser, $ageMin, $ageMax, $country);
}
include('displaySearch.php');
break;
So if nothing is set a complete list of all the members is generated and displayed. This is the function that is called if any of the inputs is set:
function search_members($username, $ageMin, $ageMax, $country){
global $db;
$query = "SELECT username FROM profiles WHERE username = :username
AND age > :ageMin AND age < :ageMax AND country = :country";
$statement = $db->prepare($query);
$statement->bindValue(':username', $username); $statement->bindValue(':ageMin', $ageMin);
$statement->bindValue(':ageMax', $ageMax); $statement->bindValue(':country', $country);
$statement->execute();
if($statement->rowCount() >= 1){
return $statement->fetchAll();
} else {
return false;
}
}
The mysql logic is obviously wrong. I need a set of conditions (in the MySQL logic if possible) that checks the PHP variables for value and if there is none it should not be accounted for when querying the database. So if only the username is set in the form the other variables should not be included in the SQL logic.
I've looked up the MySQL IF() condition but Im still not able to come up with proper code that does what I need. If someone could point me in the right direction I would be able to do the rest myself. Any other approach for solving this kind of problem is also welcome.
If i understand your problem, then the simple way is to use if else to build sql query, for example
$sql = "SELECT username FROM profiles WHERE 1 "
if (!is_null($username)) {
$sql .= " AND username = :username ";
}
// All other checks
Related
The data is not inserting into another table, here's the code below :
if (isset($_POST))
{
$job = $_POST['jobtitle'];
$dur = $_POST['duration'];
$deg = $_POST['requireddegree'];
$exp = $_POST['experiance'];
$sal = $_POST['salary'];
$mark = $_POST['marks'];
if ( !empty($job) && !empty($dur) && !empty($deg) && !empty($exp) && !empty($sal) && !empty($mark))
{
$dur = mysql_real_escape_string($dur);
$deg= mysql_real_escape_string($deg);
$exp = mysql_real_escape_string($exp);
$sal = mysql_real_escape_string($sal);
$mark = mysql_real_escape_string($mark);
$job = mysql_real_escape_string($job);
$query="INSERT INTO jobposting (duration,degree,experiance,salary,marks,Jobtitle) VALUES ('".$dur."','".$deg."','".$exp."','".$sal."','".$mark."','".$job."') ";
if ($query_run= mysql_query($query))
{
header('location : Main.html');
}
else
{
echo ' Data not Inserted! ';
}
}
With this it gives me server error or there was an error in CGI script.But when I write the variables in this form '$dur' instead of '".$dur." then the else conditon runs after insert query and displays data is not inserted.
However, i have written the same logic while inserting data in my another table and it inserts successfully.But there I put '$dur'.
I can't find the problem.Will be glad for your suggestions :)
I can't seem to find any other error by seeing this code expect for
$query="INSERT INTO jobposting (duration,degree,experiance,salary,marks,Jobtitle) VALUES ('$dur','$deg','$exp','$sal','$mark','$job') ";
//Use ".$job." only for stuff like '".md5($_POST['password'])."' otherwise this creates problem some times.
// Adding this always helps
if(!mysqli_query($con,$query))
{
die('error'.mysqli_error($con));
}
// in $con = $con=mysqli_connect("localhost","root","");
else
{
if ($query_run= mysql_query($query))
{
header('location : Main.html');
}
else
{
echo ' Data not Inserted! ';
}
}
I think by making these changes and making sure that your db name and other basic stuff are correct then you should be good to go otherwise, specify your exact error.
This script is selecting data based on optional fields in a HTML form. Although they are optional fields, at least 1 must be entered with the idea being that the more fields entered, the more likely you are to get a single result. For test I have two records with the same first and last name but different ID's and mobile numbers. At the moment when entering a name, 2 fields are given... Correct but when entering a mobile or ID, two results are still displayed.
Ive tried reading into passing missing variables in an SQL query but haven't got very far. Anything blindingly obviously wrong?
Thanks
<?php
include "checkmysqlconnect.php";
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$mobile = $_POST['mobile'];
$attendid = $_POST['attendid'];
$search = $_POST['search'];
if ($search == "Search") {
if ($firstname == '' AND $lastname == '' AND $attendid == '' AND $mobile == '') {
header("Location: searchattendform.php?result=1");
$error = true;
}
if($error != true) {
$sql = "SELECT * FROM `attend` WHERE `firstname` = '".$firstname."' AND `lastname` = '".$lastname."' AND `attendid` = '".$attendid."' AND `mobile` = '".$mobile."'";
$query = mysql_query($sql);
$count = mysql_num_rows($query);
if ($count > 1) {
while($value = mysql_fetch_assoc($query)) {
echo "More than one attendee with this name. Entering more details will help narrow down results.";
echo "<tr><td>".$value['attendid']."</td><td>".$value['wristband']."</td><td>".$value['firstname']."</td><td>".$value['lastname']."</td><td>".$value['telephone']."</td><td>".$value['mobile']."</td><td>".$value['address1']."</td><td>".$value['address2']."</td><td>".$value['town']."</td><td>".$value['postcode']."</td><td>".$value['email']."</td><td>".$value['medical']."</td></tr>";
} } else {
if ($count == 0) {
header("Location: searchattendform.php?result=2");
} else {
if ($count == 1) {
($value = mysql_fetch_assoc($query));
echo "<tr><td>".$value['attendid']."</td><td>".$value['wristband']."</td><td>".$value['firstname']."</td><td>".$value['lastname']."</td><td>".$value['telephone']."</td><td>".$value['mobile']."</td><td>".$value['address1']."</td><td>".$value['address2']."</td><td>".$value['town']."</td><td>".$value['postcode']."</td><td>".$value['email']."</td><td>".$value['medical']."</td></tr>";
} else {
echo "The was an issue searching attendees. Please contact SOFia Admin.";
} }
}
}
}
?>
One issue you have is that your query always checks all the variables:
$sql = "SELECT * FROM `attend` WHERE `firstname` = '".$firstname."' AND `lastname` = '".$lastname."' AND `attendid` = '".$attendid."' AND `mobile` = '".$mobile."'";
You probably want to break it up, and build it dynamically, something like this:
$sql = "SELECT * FROM `attend` WHERE ";
$whereArray = [];
if ($lastName){
$whereArray[] = "`lastname` = '".$lastname."'";
}
if ($firstname){
$whereArray[] = "`firstname` = '".$firstname."'";
}
//etc...
$sql .= join(" AND ", $whereArrray);
You will need to modify this to use parametrization, but this should see you in the right direction:
include "checkmysqlconnect.php";
((isset($_POST['firstname']) && $_POST['firstname'] != '') ? $firstname = '%'.$_POST['firstname'].'%' : null); //prevents unneeded variables
...
if (!(isset($firstname) or isset($lastname) or isset($attendid) or isset($mobile))) { //checks that at least one variable has been provided
...
$sql = "SELECT * FROM `attend` WHERE 1=1"; //returns all; necessary for building the query since you have an unknown number of parameters
(isset($firstname) ? $sql .= " AND `firstname` like '".$firstname."': null); //adds to the query only if the variable exists
...
?>
I highly recommend using some kind of database wrapper class. This will help generate the SQL for you. There are many other reasons why this is a good idea.
There are plenty of MySQL wrappers and most frameworks have one. You could try for example, CodeIgniter, which is very simple framework to install and work with. Then, to create the query you would do something like:
<?php
if(isset($_POST['firstname']) && !empty($_POST['firstname'])) {
$this->db->where('firstname', $_POST['firstname']);
}
if(isset($_POST['lastname']) && !empty($_POST['lastname'])) {
$this->db->where('lastname', $_POST['lastname']);
}
...
$results = $this->db->>get('attend');
foreach($results->result() as $row)
{
echo $row->firstname;
}
?>
Try to place var_dump($sql); die(); after the $sql statement and test what that returns.
I have this PHP code:
function getusers($user) {
$result = query("SELECT IdUser, username FROM login WHERE username='%s'",$user);
if (count($result['result'])>0) {
//authorized
print json_encode($result);
} else {
errorJson('Actualization failed');
}
}
But this only returns the user that matches the name exactly.
I'd like to return all users containing that name string, for example:
dani -> daniel, dani_56, dani563, elnenedani, ...
It is usually done by putting in PHP: %dani% but as I have put the %s to grab the variable $user, I do not know how to put it.
Any idea?
It is not a great Question. If you have searched well in Stackoverflow you would have go it the answer.. As you asked the Question the answer is.. Instead of Equal use LIKE:
function getusers($user) {
$result = query("SELECT IdUser, username FROM login WHERE username LIKE %'%s'%",$user);
if (count($result['result'])>0) {
//authorized
print json_encode($result);
} else {
errorJson('Actualization failed');
}
}
It seems the PHP code and DB is working well. Checkout the below links for the error:
iOS 5 JSON Parsing Results in Cocoa Error 3840
Cocoa error 3840 using JSON (iOS)
The Operation couldn't be completed. (Cocoa error: 3840.)
Cocoa Error 3840 - NSJSONSerialization
You should use the LIKE syntax. Make sure to include % to indicate wildcards:
query('SELECT IdUser, username FROM login
WHERE username LIKE "%' . $user . '%"')
My query() function is
function query() {
global $link;
$debug = false;
//get the sql query
$args = func_get_args();
$sql = array_shift($args);
//secure the input
for ($i=0;$i<count($args);$i++) {
$args[$i] = urldecode($args[$i]);
$args[$i] = mysqli_real_escape_string($link, $args[$i]);
}
//build the final query
$sql = vsprintf($sql, $args);
if ($debug) print $sql;
//execute and fetch the results
$result = mysqli_query($link, $sql);
if (mysqli_errno($link)==0 && $result) {
$rows = array();
if ($result!==true)
while ($d = mysqli_fetch_assoc($result)) {
array_push($rows,$d);
}
//return json
return array('result'=>$rows);
} else {
//error
return array('error'=>'Database error');
}
}
I do not get fixed. This code is for an ios app that uses AFNetworking, might please that helps you know what happens because I do not get it
I'm having an issue with one of my classes (I believe). On a high level, I'm sending a form to a php file that initiates a class. By accessing several of it methods, it determines whether or not a value is in the database. If it is, it returns a boolean.
Here's the code that I believe is the issue:
public function territoryCheck($numberOut)
{
$this->numberOut = $numberOut;
//Execute test
$this->checkConnect();
$stmt = $this->dbh->prepare("SELECT t_id FROM Territory WHERE t_id = :param1");
$stmt->bindParam(':param1', $this->numberOut);
$stmt->execute();
$count = $stmt->rowCount();
//Determine value of test
if($count == 0)
{
return FALSE;
}
}
public function publisherCheck($lName, $fName)
{
$this->lName = $lName;
$this->fName = $fName;
//Execute test
$this->checkConnect();
$stmt = $this->dbh->prepare("SELECT p_id FROM People WHERE lastName = :param1 AND firstName = :param2");
$stmt->bindParam(':param1', $this->lName);
$stmt->bindParam(':param2', $this->fName);
$stmt->execute();
$count = $stmt->rowCount();
//Determine value of test
if($count == FALSE)
{
return FALSE;
}
else
{
$dummyvar = $stmt->fetch();
$this->p_id = implode($dummyvar);
}
}
public function isTerritoryOut($numberOut)
{
//Execute test
$this->checkConnect();
$this->numberOut = $numberOut;
$stmt = $this->dbh->prepare("SELECT t_id FROM checkIn WHERE t_id = :param1");
$stmt->bindParam(':param1', $this->numberOut);
$stmt->execute();
$count = $stmt->rowCount();
//Determine value of test
if($count != 0)
{
return TRUE;
}
}
There are three methods, each are a test that will return either true or false.
I was testing with execute(), fetch(), and finally rowCount() to try to emulate the values I want. Neither seem to work. Here's the code that calls these methods:
//Begin tests
$checkOut->territoryCheck($numberOut);
if($checkOut == FALSE)
{
$fail = "Territory number ".$numberOut." does not exist in our records. Please enter a valid territory. For more information, navigate to About.<\ br>";
}
$checkOut->publisherCheck($lName, $fName);
if($checkOut == FALSE)
{
if($fail !== "")
$fail .= "The publisher, ".$fName." ".$lName.", is not in our records. For more information, navigate to About.<\ br>";
else
$fail = "The publisher, ".$fName." ".$lName.", is not in our records. For more information, navigate to About.<\ br>";
}
$checkOut->isTerritoryOut($numberOut);
if($checkOut === TRUE)
{
if($fail !== "")
$fail .= "Territory number ".$numberOut." is currently checked out. Either the wrong number was entered or the territory hasn't been properly checked in.<\ br>";
else
$fail = "Territory number ".$numberOut." is currently checked out. Either the wrong number was entered or the territory hasn't been properly checked in.<\ br>";
}
For clarity, fail was set to "" earlier in the code. What happens is that it goes through all of these tests as if they had passed when I purposely create situations that should have failed. For instance, I only have territory numbers 1-130 in my database. If I put in 150, it essentially tells me that it exists.
I'm not sure what is going on, typecasting? == vs. ===?, etc.
Any help is appreciated.
I must admit, the cause is a rather obvious question that is so obvious I didn't even consider it. In each test, I simply call the method without assigning any variable to accept the return value(i.e $checkOut->publisherCheck(); instead of $test = $checkOut->publisherCheck();. Regardless, it works now.
I am trying to write a simple function that checks if a username exists in the db and if so to call another function to generate a new username. My code seems to fall over though:
Username Function:-
$user1=create_username($fname, $company);
function create_username($surname, $company){
//$name_method=str_replace(" ", "", $surname);
$name_method=$surname.$forename;
$company_name_method=str_replace(" ", "", $company);
if(strlen($name_method)<=5)
{
$addition=rand(11,99);
$first=$addition.$name_method;
}
else
{
$first=substr($name_method,0,5);
}
if(strlen($company_name_method)<=5)
{
$addition2=rand(11,99);
$second=$addition2.$company_name_method;
}
else
{
$second=substr($company_name_method,0,5);
}
$middle=rand(100,1000);
$username=$first.$middle.$second;
return($username);
}
Check Username Function:
check_user($user1, $dbc, $fname, $company);
function check_user($user1, $dbc, $surname, $company){
$check_username="SELECT username FROM is_user_db WHERE username='$user1'";
$resultx=mysqli_query($dbc, $check_username) or die("Could not check username");
$num_rows=mysqli_num_rows($resultx);
if($num_rows>0)
{
$user1=create_username($fname, $company);
check_user($user1, $dbc, $fname, $company);
}
else
{
return($user1);
}
}
It just seems to return the original username.
You probably need to re-factor your code a little. Write out the steps on paper; that helps me. So far, I can see:
You want to check a username is unique on form submission
If it's not, generate a new username
So, check the username when your form is POSTed:
<?php
if (isset($_POST['submit'])) {
if (username_unique($_POST['username'])) {
// carry on processing form
}
else {
$suggested_username = suggest_username($_POST['username']);
// display form, with new suggested username?
}
}
And then write your functions:
<?php
// following on from code from above
function check_username($username) {
// get database connection (I use PDO)
$sql = "SELECT COUNT(*) AS count FROM users_tbl WHERE username = ?";
$stmt = $pdo->prepare($sql);
$stmt->execute(array($username));
$row = $stmt->fetchObject();
return ($row->count > 0); // if 'count' is more than 0, username already exists
}
function suggest_username($username) {
// take username, and add some random letters and numbers on the end
return $username . uniqid();
}
Hopefully this will help. Obviously it'll need some modification to work in your set-up, but this is the general flow you'll need.