Using radio buttons to get data from PHP query - php

I have a random chat feature which allows users to randomly pair against another based on the parameters set by the user. The parameters are age (min: 17, max: 50) and gender (can chat with male, female, or any which means no preference).
When submit is clicked, it is easy to set queries if the radio values are male or female, because those are the values I am storing in my database, but I am unsure on how I can pair someone with another if the value is any.
Here are the radio buttons:
<input type="radio" name="gender" value="male">Male</input> <br />
<input type="radio" name="gender" value="female">Female</input><br />
<input type="radio" name="gender" value="any">Any</input>
<input type="submit" class="btn btn-info" name="submit" value="Click to start chat! " />
P.s. The radio buttons are in a form but have no action.
<form action="#" method="POST" enctype="multipart/form-data">
And here is my approach so far:
<?php
$age_from = #$_POST['age_from'];
$age_to = #$_POST['age_to'];
$gender = strip_tags(#$_POST['gender']);
if (isset ($_POST ['submit'])){
// Chat with parameters script
$any_chat = mysqli_query($connect, "SELECT * FROM users WHERE age BETWEEN '$age_from' AND '$age_to' AND gender = '$gender'
ORDER BY RAND() LIMIT 1");
$num_of_rows = mysqli_num_rows ($any_chat);
while ($get_any_rand_user = mysqli_fetch_assoc($any_chat)){
$rand_name = $get_any_rand_user['username'];
$acc_type = $get_any_rand_user['account_type'];
if ($acc_type != "admin" ){
if ($rand_name == $username){
$any_chat;
} else{
header ("Location: /messages.php?u=$rand_name");
}
}
if ($num_of_rows == 0){
echo "No results found. Try changing your query.";
}
} // while closed
}
?>
As you can see in the query gender = '$gender' can only retrieve a row if the gender is male or female (because they are the values in the db). But if any is selected, $gender will equal any which is not valid, since their is no user in my system with gender of any.
How can I work my way around this?

I would do something like this. Create a variable to store your query and only add the gender condition if $gender is male or female.
<?php
$age_from = #$_POST['age_from'];
$age_to = #$_POST['age_to'];
$gender = strip_tags(#$_POST['gender']);
if (isset ($_POST ['submit'])){
// Chat with parameters script
$sql = "
SELECT *
FROM users
WHERE age BETWEEN '$age_from' AND '$age_to'
";
if (!empty($gender) && ($gender == 'male' || $gender == 'female')) {
$sql .= " AND gender = '$gender' ";
}
$sql .= " ORDER BY RAND() LIMIT 1 ";
$any_chat = mysqli_query($connect, $sql);
$num_of_rows = mysqli_num_rows ($any_chat);
while ($get_any_rand_user = mysqli_fetch_assoc($any_chat)){
$rand_name = $get_any_rand_user['username'];
$acc_type = $get_any_rand_user['account_type'];
if ($acc_type != "admin" ){
if ($rand_name == $username){
$any_chat;
} else{
header ("Location: /messages.php?u=$rand_name");
}
}
if ($num_of_rows == 0){
echo "No results found. Try changing your query.";
}
} // while closed
}
?>

if (isset ($_POST ['submit'])){
// Chat with parameters script
$sql_builder = "SELECT * FROM users WHERE age BETWEEN '$age_from' AND '$age_to'";
if($gender != 'any'){
$sql_builder .= "AND gender = $gender";
}
$sql_builder .= "ORDER BY RAND() LIMIT 1";
$any_chat = mysqli_query($connect, $sql_builder);

Related

SQL query failing to INSERT new row into table

I have a chunk of PHP code that triggers if a button is pressed by the user. What I expect to happen is it checks to see if the user has the skill already assigned to them, and if not it performs an INSERT. Then if it does do nothing. And finally if the checkbox next to a skill is un-checked it checks to see if they have the skill already assigned and delete it if found.
The code is deleting the skills from the user no matter the condition of the checkboxes. Im sure I must be missing something but after starring at the code for hours I cannot see it.
Can anyone suggest a resolution?
PHP code:
if(isset($_POST['Update']))
{
$default = 0;
foreach($skills_array AS $skills_id=>$skills_name)
{
if (isset($_POST[$skills_name]))
{
if (empty($_POST[$skills_name.'exp']))
{
$exp = $default;
}
else
{
$exp = $_POST[$skills_name.'exp'];
}
$sql = $con->query("SELECT count(`UserID`) as total FROM `userskills` WHERE `UserID` = '$User' AND `SkillID` = ".$skills_id)
or die(mysqli_error($con));
if ($row = mysqli_fetch_assoc($sql))
{
$sql = $con->query("INSERT INTO `userskills` ( `UserID`, `SkillID`, `Experience`) VALUES ('$User', '$skills_id', '$exp')")
or die(mysqli_error($con));
//If the checkbox is not checked it will check to see if skill is already a skill assigned to the user. If they are it will delete it. If not it will ignore.
}
else
{
$sql = $con->query("UPDATE `userskills` SET `Experience` = '$exp' WHERE `UserID` = '$User' AND `SkillID` = ".$skills_id)
or die(mysqli_error($con));
}
}
else
{
$sql = $con->query("DELETE FROM `userskills` WHERE `UserID` = '$User' AND `SkillID` = ".$skills_id)
or die(mysqli_error($con));
}
}
header('Location: Account.php');
die();
}
else
{
echo 'Incorrect password please try again.';
}
}
HTML Code:
<div class="RightBody">
<form id="form2" name="form2" method="post" enctype="multipart/form-data">
<p><h3>Skills:</h3>
<?php
$result1 = $con->query("SELECT skills.`SkillID`, skills.`Description`, COUNT(userskills.`SkillID`) AS SkillUserHas, MAX(`Experience`) AS Experience
FROM `skills`
LEFT OUTER JOIN userskills
ON skills.`SkillID` = userskills.`SkillID` AND userskills.`UserID` = '$User'
GROUP BY skills.`SkillID`, skills.`Description`
ORDER BY FIELD(skills.`SkillID`, 1, 7, 9, 3, 4, 5, 6, 8)")
or die(mysqli_error($con));
while ($skillrow = $result1->fetch_assoc())
{
?>
<div class="CheckboxText">
<?php
echo '<label>';
echo '<input type="checkbox" name="'.$skillrow['Description'].'" id="CheckboxGroup1_'.$skillrow['SkillID'].'" class="skillselect" value="yes" '.(($skillrow['SkillUserHas'] > 0) ? 'checked' : '').'>';
echo $skillrow['Description'].'</label>';
echo '<input type="number" name="'.$skillrow['Description'].'exp" class="expnumber" placeholder="Enter Experience in years." value="'.$skillrow['Experience'].'">';
echo '<br />';
echo '<br />';
}
?>
</div>
</p>
</form>
</div>
Im not familiar with PHP, but yesterday I help in a similar problem
Here you create your query but your COUNT will always return a row, and if not skill the value is 0
$sql = $con->query("SELECT count(`UserID`) as total FROM `userskills` WHERE `UserID` = '$User' AND `SkillID` = ".$skills_id)
or die(mysqli_error($con));
So instead of if ($row = mysqli_fetch_assoc($sql)) you need something like
$row = mysqli_fetch_assoc($sql);
$skill = $row['total'];
if ($skill == 0 )
But that doesnt solve the error you describe, delete all skills or just the one selected?
Any way you have to check this IF that is the branch sending your skill to delete.
if (isset($_POST[$skills_name]))
This mean your $skills_name isnt defined. Maybe you should check for the value inside the array $skills_array?
My second guess check the code create on the webpage. Right click your page and selece see source code

How do I create a method to specify field name and a PK from a DB table?

I have a series of checkboxes that interact with the DB in 3 possible ways; INSERT, DELETE, no action.
I will have a total of 8-10 checkboxes, however each checkboxes requires 32 lines of code (inc 3 if statements) to work. Rather than have 320 lines of code for 10 checkboxes is it possible to to use a php function to define the markup for these elements?
PHP Code:
//If the Java checkbox is checked it will check to see if java is already a skill assigned to the user. If so it will ignore, if not it will add.
if (isset($_POST['java'])) {
if (empty($_POST['javaexp'])) {
//header('Location: UpdateAccount.php');
//die();
}
else {
$javaexp = $_POST['javaexp'];
}
$sql = $con->query("SELECT count(UserID) as total FROM userskills WHERE UserID = $User AND SkillID = 1")
or die(mysqli_error($con));
$row = mysqli_fetch_assoc($sql);
if ($row ['total'] == "0") {
$sql = $con->query("INSERT INTO userskills ( UserID, SkillID, Experience) VALUES ($User, 1, $javaexp)");
//If the Java checkbox is not checked it will check to see if java is already a skill assigned to the user. If they are it will delete it. If not it will ignore.
}
}
else {
$sql = $con->query("SELECT count(UserID) as total FROM userskills WHERE UserID = $User AND SkillID = 1")
or die(mysqli_error($con));
$row = mysqli_fetch_assoc($sql);
if ($row ['total'] == "1") {
$sql = $con->query("DELETE FROM userskills
WHERE UserID = $User AND SkillID = 1");
}
}
$con = sql connection on another php file.
HTML Code:
<p>
<label>
<input type="checkbox" name="java" value="checkbox" id="CheckboxGroup1_0" class="skillselect">
Java</label> <input type="number" name="javaexp" class="expnumber" placeholder="Enter Experience in years.">
<br>
<br>
<label>
<input type="checkbox" name="iOS" value="checkbox" id="CheckboxGroup1_1" class="skillselect">
Checkbox</label> <input type="number" name="" class="expnumber" placeholder="Enter Experience in years.">
<br>
<br>
<label>
<input type="checkbox" name="PHP" value="checkbox" id="CheckboxGroup1_2" class="skillselect">
Checkbox</label> <input type="number" name="" class="expnumber" placeholder="Enter Experience in years.">
<br>
<br>
</p>
<div class="FormElement">
<input name="Update" type="submit" class="button" id="Update" value="Submit Changes">
</div>
You certainly can turn it into a function:
function updateSkillFromPost($skill, $skillId, $User, $con) {
if (isset($_POST[$skill])) {
if (empty($_POST["{$skill}exp"])) {
//header('Location: UpdateAccount.php');
//die();
}
else {
$exp = $_POST["{$skill}exp"];
}
$sql = $con->query("SELECT count(UserID) as total FROM userskills WHERE UserID = $User AND SkillID = $skillId")
or die(mysqli_error($con));
$row = mysqli_fetch_assoc($sql);
if ($row ['total'] == "0") {
$sql = $con->query("INSERT INTO userskills ( UserID, SkillID, Experience) VALUES ($User, $skillId, $exp)");
//If the Java checkbox is not checked it will check to see if java is already a skill assigned to the user. If they are it will delete it. If not it will ignore.
}
}
else {
$sql = $con->query("SELECT count(UserID) as total FROM userskills WHERE UserID = $User AND SkillID = $skillId")
or die(mysqli_error($con));
$row = mysqli_fetch_assoc($sql);
if ($row ['total'] == "1") {
$sql = $con->query("DELETE FROM userskills
WHERE UserID = $User AND SkillID = $skillId");
}
}
}
and then call it like
updateSkillFromPost('java', 1, $User, $con);
updateSkillFromPost('php', 2, $User, $con);
updateSkillFromPost('xml', 3, $User, $con);
... and so on ...
or even better, given an array of $skills in the form $id => $name:
foreach($skills as $skillId => $skill) {
updateSkillFromPost($skill, $skillId, $User, $con);
}
please notice that the code you used, and which I turned into a function, si vulnerable to SQL Injection though.

php/mysql advanced search page

I faced a problem in developing advanced search code using php as an input and output, sql to select and filter data ..
php code:
<form action="index.php?Type=Advance" method="post">
<input type="text" name="name">
<input type="text" name="sponsor">
<select size="1" name="gender" id="">
<option value="male">male</option>
<option value="female">female</femal>
</select>
<select size="1" name="address" id="">
<option value="x">x</option>
<option value="y">y</option>
<option value="z">z</option>
</select>
<input type="submit">
</form>
Then i declare the variables
public function AdvanceSearch($name,$sponsor,$gender,$address)
{
$cheack = "";
if(isset($name)&&$name != ""){
$cheack.=" name = '$name' ";
}
if(isset($sponsor)&&$sponsor != ""){
$cheack.=" AND sponsor = '$sponsor' ";
}
if(isset($gender)&&$gender != ""){
$cheack.=" AND gender = '$gender' ";
}
if(isset($address) &&$address != "" ){
$cheack.=" AND workplace = '$address' ";
}
$DB = mysql_query("SELECT * FROM table WHERE 1 = 1 ".$cheack);
echo "SELECT * FROM user WHERE ".$WHQ;
exit();
actually it works, however if i didn't insert the name ... the sql statement will be like this
SELECT *
FROM table
WHERE AND sponsor = 'www'
AND gender = 'male'
what if i want to search on the table but without inserting the name .. how can i let the sql statement works if i didn't inset the name.
A typical solution to this is always adding a true condition first, such as 1=1. The query without any extra conditions then becomes
SELECT * FROM table WHERE 1=1
and when you add any AND conditions you can just add them to the end, with no special case for the first or last condition:
SELECT * FROM table WHERE 1=1 AND sponsor = 'www' AND gender = 'male'
Note that if you used OR instead of AND the first condition should be false, like 0=1.
You can use a flag variable like :
$cheack = "";
$flag = False;
if(isset($name)&&$name != ""){
$cheack.=" name = '$name' ";
$flag =True;
}
if(isset($sponsor)&&$sponsor != ""){
if($flag){
$cheack.="AND ";
}
$cheack.="sponsor = '$sponsor' ";
}
if(isset($gender)&&$gender != ""){
if($flag){
$cheack.="AND ";
}
$cheack.="gender = '$gender' ";
}
if(isset($address) &&$address != "" ){
if($flag){
$cheack.="AND ";
}
$cheack.="workplace = '$address' ";
}

Check to update and then insert multiple records at once in mysql?

I have 2 tables relating to a survey. When user answers each set of questions and then click the submit button, it will loop each answer according to the form submitted in order to check within the database first, if the CustomerID and QuestionID have been found, then do the Update. If not found, do the Insert instead.
QUESTIONS table
QuestionID (PK)
QuestionText
ANSWERS table
AnswerID (PK)
CustomerID (FK)
QuestionID (FK)
AnswerText
<html>
....
<form action="/db.php" method="POST">
<?php echo $questiontext[1]; ?><input type="text" name="answer1" id="answer1">
<?php echo $questiontext[2]; ?><input type="text" name="answer2" id="answer2">
<?php echo $questiontext[3]; ?><input type="text" name="answer3" id="answer3">
<?php echo $questiontext[4]; ?><input type="text" name="answer4" id="answer4">
<?php echo $questiontext[5]; ?><input type="text" name="answer5" id="answer5">
<?php echo $questiontext[6]; ?><input type="text" name="answer6" id="answer6">
<input type="submit" name="submit" id="submit" value="Submit">
</form>
...
</html>
db.php
<?php
if(isset($_POST['submit'])) {
$cusid = intval($_POST['CustomerID']);
$answer1 = $db->real_escape_string($_POST['answer1']);
$answer2 = $db->real_escape_string($_POST['answer2']);
$answer3 = $db->real_escape_string($_POST['answer3']);
$answer4 = $db->real_escape_string($_POST['answer4']);
$answer5 = $db->real_escape_string($_POST['answer5']);
$answer6 = $db->real_escape_string($_POST['answer6']);
$sql = "INSERT INTO Answers (CustomerID, QuestionID, AnswerText) VALUES
('".$cusid."','".$quesid."','".$answer."')";
$res = $db->query($sql) or die ('Error: ' . mysqli_error($db));
}
?>
My questions are:
How to update each answer(1-6) one by one and then insert into the database if CustomerID and QuestionID have not been found by using array and SQL query, if found, then just update?
How could I reference the QuestionID in order to related with AnswerText in HTML and PHP?
This is just an idea for you. Hope you can understand it. Make sure you replace database driven functions with your $db object.
if(isset($_POST['submit'])) {
$sql = "SELECT QuestionID FROM Questions ORDER BY QuestionID ";
$res = $db->query($sql);
$qus = 1;
while ($row = mysqli_fetch_array($res , MYSQLI_ASSOC)) {
{
$questionID = $row['QuestionID'] ;
$answer = $db->real_escape_string($_POST['answer' . $qus ]);
$sql = "SELECT AnswerID FROM Answers WHERE CustomerID='$cusid' AND QuestionID='$questionID' ";
$resAns = $db->query($sql);
$num_rows = $resAns->num_rows; // This should be replace with your $db object record count obtaining method
if($num_rows == 1)
{
$sql = "UPDATE Answers SET AnswerText = '$answer' WHERE CustomerID='$cusid' AND QuestionID='$questionID' ";
// Execute your update query
}
else
{
$sql = "INSERT INTO Answers (CustomerID, QuestionID, AnswerText) VALUES
('".$cusid."','".$questionID."','".$answer."')";
// Execute your insert statement
}
$qus ++;
}
}
You can run a select query first and then see how many rows have been returned from there something like this
$check = mysql_query("SELECT * FROM Answers WHERE CustomerId = '$cusid' OR QuestionId = '$quesid' LIMIT 1") or die(mysql_error());
$num_rows = mysql_num_rows($check);
if($num_rows == 1)
{
// value exists run the update
}
else
{
// go ahead with insert query
}
If you set a unique key on CustomerID+QuestionID, then you can just do an INSERT ... ON DUPLICATE KEY UPDATE ...
http://dev.mysql.com/doc/refman/5.1/en/insert-on-duplicate.html
Let the database handle the checks.

Remove items in database based on status of checkbox

I am trying to take input from an HTML form where there are checkboxes. The checkboxes are created with the student_ids from the database. Like so:
<td><input type="checkbox" name="{$row['STUDENT_ID']}" />
What I want to do is step through the Students table and check all of the entries against which of the checkboxes are checked. I want to then delete the entries from the database that have been checked with the checkboxes.
8 $query = "SELECT STUDENT_ID From Students";
9 $result = mysql_query($query) or die(mysql_error());
10 while($row=mysql_fetch_array($result)){
11 $checkname=$row['STUDENT_ID'];
12 foreach($_POST[$checkname] as $student_id =>val)
13 {
14 if($val == 'YES'
15 {
16 echo $_POST['STUDENT_ID'];
17 $query = "DELETE FROM Students WHERE STUDENT_ID" . mysql_real_escape_string($STUDENT_ID);
18 }
19 echo $query;
20 $result = mysql_query($query) or die(mysql_error());
21 //echo $POST['STUDENT_ID'];
22 }
23 }
Create an array of checkbox :
<input type="checkbox" name="studentID[]" value="{$row['STUDENT_ID']}" />
From PHP :
$studentID = $_POST['studentID'];
foreach($studentID as $ID){
echo $ID.'<br />'."\n";
}
EDIT :
Not sure but I think this is the right way :
$studentID = $_POST['studentID'];
$i=0;
foreach($studentID as $ID){
$i++;
echo $_POST['studentID'][$i].'<br />'."\n";
}
Try this for your form:
<input type="checkbox" name="STUDENT_ID[<?php echo $row['STUDENT_ID'] ?>]" value="YES" />
and this for your PHP loop:
foreach ($_POST['STUDENT_ID'] as $student_id => $val) {
if ($val == 'YES') {
$query = "DELETE FROM Students WHERE STUDENT_ID=" . mysql_real_escape_string($student_id);
$result = mysql_query($query) or die(mysql_error());
}
}
A better way of doing this is to take the Student IDs from your checkboxes that were submitted and then run deletes on those.
HTML
<input type="checkbox" name="students_to_delete[]" value="{$row['STUDENT_ID']}" />
PHP
$students_to_delete = $_POST['students_to_delete'];
if(is_array($students_to_delete) && count($students_to_delete) > 0) {
$query = "DELETE FROM Students WHERE STUDENT_ID IN (" . implode(",", $students_to_delete) . ")";
$result = mysql_query($query) or die(mysql_error());
}
The above code is vulnerable to SQL injection. If someone posts back to the server a value of 0 OR STUDENT_ID!=0 then all rows in the Students table will be deleted.
Your code is also inefficient - you are returning all the students and then iterating over each student to see if this requires deleting.
You would be better using in your markup:
<input type="checkbox" name="STUDENT_TO_DELETE" value="$row['STUDENT_ID']" />
and then in the php:
foreach ($_POST['STUDENT_TO_DELETE'] as $student_id => $val) {
$sql = "DELETE FROM Students WHERE STUDENT_ID=" . mysql_real_escape_string($student_id);
mysql_query($sql);
}
}

Categories