How do I conditionally add a clause to my query in PHP? - php

In my search form I have, value male, value female, and value both. If you select both, I do not wish to have at WHERE the "sex = '$sex'"
Should i do it like this:
if(empty($sex)){ // value empty if you chose "both"
$query = "SELECT firstname, lastname, id, user_name, sex, last_access, bostadsort FROM users WHERE (firstname LIKE '%$firstname%' OR lastname LIKE '%$lastname%')";
}else{
$query = "SELECT firstname, lastname, id, user_name, sex, last_access, bostadsort FROM users WHERE (firstname LIKE '%$firstname%' OR lastname LIKE '%$lastname%') AND sex = '$sex'";
}
Or is there a smart way to write this?

Do never build an SQL string from user input. That's what prepared statements are for. They are secure, perform faster when re-executed and they're easy to use, so use them:
$sql = "
SELECT
firstname, lastname, id, user_name, sex, last_access, bostadsort
FROM
users
WHERE
(firstname LIKE '%'|| ? || '%' OR lastname LIKE '%'|| ? || '%')
AND Sex = CASE ? WHEN 'both' THEN Sex ELSE ? END
";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param('ssss', $firstname, $lastname, $sex, $sex);
$result = $stmt->execute();

How about not repeating yourself:
$query = "SELECT firstname, lastname, id, user_name, sex, last_access, bostadsort FROM users WHERE (firstname LIKE '%$firstname%' OR lastname LIKE '%$lastname%')";
if(!empty($sex)){
$query = $query . " AND sex = '$sex'";
}

You could do this:
$sql = "SELECT ...";
if (!empty($gender))
{
$sql .= " AND gender = '$gender'";
}
And make sure to watch for sql injection.

Related

mistake in query or by post method

I am getting result with $id='S%', but not with $id = $id.'%' when recieved $id = 's' by post
$id = $_POST['user_data'];
if($_POST['user_data'].lenght<2)
{
$query = "SELECT id, oauth_provider, first_name, last_name, email, phone, STATUS , picture, link, createdFROM users WHERE first_name LIKE ? ORDER BY id DESC " ;
$id = $id.'%';
echo ''.$id;
$stmt = $conn->prepare($query);
$stmt->bind_param('s', $id);
$stmt->execute();
$result = $stmt->get_result();
echo $result->num_rows;
}
ialready recieved $id= s by post also checked it by echo it.
output when id= $id='S%' :
9
output when id= $id=$id.'%' :
0
Your query seems to be wrong, it should be
$query = "SELECT id, oauth_provider, first_name, last_name, email, phone, STATUS , picture, link, created FROM users WHERE first_name LIKE ? ORDER BY id DESC " ;
and here is a workaround
$variable = mysql_real_escape_string($id);
$query = "SELECT id, oauth_provider, first_name, last_name, email, phone, STATUS , picture, link, created FROM users WHERE first_name LIKE '% $variable' ORDER BY id DESC";

How can I use a condition in PDO object while a query

I am trying to Select Data With PDO (+ Prepared Statements)
The following example uses prepared statements.
http://www.w3schools.com/php/showphpfile.asp?filename=demo_db_select_pdo
I need to know how to make a condition to display only the LASTNAME = PETER. I tried like the below, but not working
$stmt = $conn->prepare("SELECT id, firstname, lastname FROM MyGuests WHERE lastname =PETER");
If you want to prepare and execute use like this
$stmt = $conn->prepare("SELECT id, firstname, lastname FROM MyGuests WHERE lastname = :lastname");
$result = $stmt->execute(array(':lastname'=>'PETER'));
And if you want to run directly (which is not recommended if 'PETER' is coming from an user input).
$result = $conn->query("SELECT id, firstname, lastname FROM MyGuests WHERE lastname = 'PETER');
The condition being handed to the WHERE clause needs to be single quoted as it is (I presume) a string. So:
$stmt = $conn->prepare("SELECT id, firstname, lastname FROM MyGuests WHERE lastname = 'PETER'");
Remember if you are going to make this dynamic in future to sanitise your inputs and use some kind of named parameters like so:
$stmt = $conn->prepare("SELECT id, firstname, lastname FROM MyGuests WHERE lastname = :lastname");
$stmt->execute([':lastname' => 'PETER']); // the string here can be a variable of course

You have an error in your SQL syntax Mysql

My sql query is :
"INSERT INTO
order customer_id = $customer_id
, firstname = '".$firstname."'
, lastname = '".$lastname."'
, email = '".$email."'
, telephone = '".$telephone."'
, fax = '".$fax."'
, ip = '".$ip."'
, date_added = NOW()
, date_modified = NOW()
";
I get the error
Notice: Error: You have an error in your SQL syntax; check the manual
that corresponds to your MySQL server version for the right syntax to
use near 'order customer_id =1,firstname ='kuldeep',lastname
='pathak',email ='kuldeep.pat' at line 1 Error No: 1064
You didnt understand how to write SQLs as it seems.
$sql = 'INSERT INTO `order` (customer_id, firstname, blablabla) VALUES ('.$custormer_id.','.$firstname.','.$blablabla.')';
Please look at some basic tutorials about SQL.
"INSERT INTO
`order` SET customer_id = " . $customer_id . "
, firstname = '".$firstname."'
, lastname = '".$lastname."'
, email = '".$email."'
, telephone = '".$telephone."'
, fax = '".$fax."'
, ip = '".$ip."'
, date_added = NOW()
, date_modified = NOW()
";
Should be alright. DonĀ“t forget to escape your data though.
Try
"INSERT INTO `Order` (customer_id, firstname, lastname, email, telephone, fax, ip, date_added, date_modified)
VALUES ($customer_id, '$firstname', '$lastname', '$email', '$telephone', '$fax', '$ip', NOW(), NOW())"
The right syntax is : INSERT INTO tablename (columns) VALUES (values);
If you're likely to have user submitted fields in the dataset or appostrophes or anything else that could cause problems for any reason you'd want something more like
$query = sprintf("INSERT INTO `table` (`Name`, `Email`, `AnotherField`) VALUES ('%s', '%s', '%s'",
mysql_real_escape_string( $_POST['Name'] ),
mysql_real_escape_string( $_POST['Email'] ),
mysql_real_escape_string( $_POST['AnotherField'] )
);
This will sanitise your inputs as well
Use prepared statement to avoiding sql injection.
$custormer_id = "2000";
$firstname = "first name";
$etc = "some other values";
$mysqli = new mysqli('localhost', 'user', 'password', 'database');
$stmt = $mysqli->prepare("INSERT INTO order(customer_id, firstname, etc) VALUES (?, ?, ?)");
$stmt->bind_param('iss', $custormer_id, $firstname, $etc);
// first parameter is corresponding variable type of inserting values,eg i=interger, s=string
$stmt->execute();
$stmt->close();
http://php.net/manual/en/mysqli-stmt.bind-param.php

mysql/php wrong logic with sql statement

I'm doing a project which has an ability of a user to approve or revoke application (like scholarship). But I can't seem to find out why it's not doing what I wanted to do. Please do check my code below:
$try = mysql_query("UPDATE new_applicants SET ApplicantStatusId='$status', DateManaged = NOW() WHERE ApplicantId='$id'") or die(mysql_error());
$try1 = mysql_fetch_assoc($try);
$status1 = $try1["ApplicantStatusId"];
if( $status1 == 2 ){
header('location: ../employeepage.php');
exit();
}
else{
$sql1 = "INSERT INTO scholar_profile (Firstname, Middlename, Lastname, Address, EmailAddress, BirthDate, BirthPlace, Religion, Age, Gender, ContactNo, Skill, Talent, LevelId, GWA, CategoryId, StatusId, SchoolId, BarangayId) SELECT Firstname, Middlename, Lastname, Address, EmailAddress, BirthDate, BirthPlace, Religion, Age, Gender, ContactNo, Skill, Talent, LevelId, GWA, CategoryId, StatusId, SchoolId, BarangayId
FROM new_applicants
WHERE new_applicants.ApplicantId = '$id'" or die(mysql_error());
}
When the applicantstatus becomes 2 = revoked, it should not copy the data to scholar_profile. But when I tried this, it still copies. What's wrong with this? thanks.
You're updating a table, so mysql_fetch_assoc won't return anything. I.e. $status1 will be null. If you want to select that data (ApplicantStatusID, ...) you'll have to use a SELECT statement instead.
You could just change the where clause of the SQL statement:
WHERE new_applicants.ApplicantId = '$id' and new_Applicants.ApplicantStatusId <> 2"
Then you don't have to worry about the logic in php.
you are fetching $try1 = mysql_fetch_assoc($try); on an UPDATE statment
which is not true.
fetch is only with SELECT statment

insert data from select query results with other external/posted variables

how can i insert data from query results and other variables in one insert query?
sample:
$id = $_POST['id'];
$address = $_POST['address'];
$email = $_POST['email'];
$query = "INSERT INTO info_table(fname, lname, address, email) VALUES (SELECT fname, lname, FROM info WHERE id = '$id')";
$result = db->prepare($query);
$result->execute();
how can i insert $address and $email together with the select results variables?
This should do the trick for the query:
INSERT INTO info_table (
fname,
lname,
address,
email
)
SELECT
fname,
lname,
':address',
':email'
FROM
info
WHERE
id = ':id'
You aren't using the prepare right here. You really should bind to the paramters :address, :email, and :id
$result = db->prepare($query);
$result->bindParam(':id', $id, PDO::PARAM_STR);
$result->bindParam(':email', $email, PDO::PARAM_STR);
$result->bindParam(':address', $address, PDO::PARAM_STR);
$result->execute();
Answering precisely to your question:
$query = "INSERT INTO MyInsecureTable (fname, lname, address, email) SELECT fname, lname, '$address', '$email' FROM info WHERE id = '$id'";
But it is scares the . out of me.

Categories