Multiple MySQL records with same name, different id - php

There might be an easy answer to this, but I can't for the life of me get this to work.
I'm using PHP and MySQL and have something like this set up:
$studentname = mysql_real_escape_string($_POST['sname']);
$studentnumber = mysql_real_escape_string($_POST['snumber']);
$course = mysql_real_escape_string($_POST['courseselect']);
$bike3 = mysql_query("SELECT stoodnumber FROM bikes505 WHERE stoodname='" . $studentname . "'");
$bikestoods = mysql_fetch_array($bike3);
while($row = mysql_fetch_array($stoodlistq))
{
$stoodentname = $row['stoodname'];
$stoodentnumber = $row['stoodnumber'];
//$coursename = $row2['coursename'];
//$coursecode = $row2['coursecode'];
if($studentname == $stoodentname && $studentnumber == $stoodentnumber){
//$success = 1;
//$success = "yupp";
//echo "SUCCESS, WE CAN REGISTER YOOOU!";
echo "<br>";
//echo "INSERT INTO " . $course . "";
switch($course){
case "Biking Safely":
if($studentnumber = $bikestoods[0] or $bikestoods[1]){
echo "Sorry, this student has already registered";
} else if($bikecurrent < $bikemax){
mysql_query("INSERT INTO bikes505 VALUES ('" . $stoodentname . "','" . $stoodentnumber . "')");
echo "Yay, successfully registered " . $stoodentname . " - " . $stoodentnumber . " for " . $course;
echo "<br>";
} else{
echo "Sorry, class is full!";
}
break;
...and so on. The only problem that I'm having is that if I have two students with the same name, the second in the list will echo that the information is not correct.
For example, the MySQL table has 'stoodname' and 'stoodnumber', and if 'Jimmy St.James','1010' and 'Jimmy St.James','1090' are both records in the table it will only let me enroll Jimmy 1010 in the course and not Jimmy 1090.
Am I just way off with how I'm validating? Or am I missing something really obvious? At first I assumed it was just because I was only using the first item in the array $bikestoods[0] so I changed it to $bikestoods[0] or $bikestoods[1] and it still doesn't work.

Per a comment, you have $stoodlistq defined as:
$stoodlistq = mysql_query("SELECT * FROM stoodinfo");
Later, you use the following block of code:
$studentname = mysql_real_escape_string($_POST['sname']);
$studentnumber = mysql_real_escape_string($_POST['snumber']);
...
while($row = mysql_fetch_array($stoodlistq)) {
...
if($studentname == $stoodentname && $studentnumber == $stoodentnumber){
The while() loop in this code iterates over every record, however, the if-statement checks against the POST variables. The POST variables make up a single combination for "one student" - therefore, you'll only ever get a single student that can be enrolled.
To fix the issue, you'll either need to update your form that submits the "student name"/"student number" to accept multiple inputs - or update the if-statement to only check against the student's name (which could lead to a more undesired situation).

You are doing your query looking for stoodname . When you are doing things like this is not good to do this statements by a value that can be repeated. Maybe you want them to login with a username and password, or maybe with an id that you give to them, but unless somebody here has a better idea, i don't think you will be able to do it by the name.

$bikestoods = mysql_fetch_array($bike3);
only refers to the first result of bike3 query and only has 2 cols : [0] and [stoodnumber] no [1]. If you want to collect all ids that are in bike3, you have to curse the result one time.
while($stoodnumbers[] = mysql_fetch_array($bike3));

Related

MySQL + PHP + Query multiple columns in a table based on multiple inputs, not all inputs required

I want to be able to query a table in my database using multiple form inputs which relate to several columns in the table. The problem I am running into is that not all of the form inputs are required.
A little detail...
I have a table called users. This table has many columns, but the ones I am querying are first_name, last_name, location, status (0 or 1).
I have three inputs on the search form. Name (text), Location (select) and Status (select). The user does not have to enter an input for all of the inputs, only one is required.
The main problem I have is writing the query based on the inputs. I can get it to work with multiple else/if statements, for example...
if($_POST['name'] && !$_POST['location'] && !$_POST['status']){
$query = '[QUERY THAT MATCHES NAME]';
} else if($_POST['name'] && $_POST['location'] && !$_POST['status']){
$query = '[QUERY THAT MATCHES NAME AND LOCATION]';
} else if($_POST['name'] && $_POST['location'] && $_POST['status']){
$query = '[QUERY THAT MATCHES NAME AND LOCATION AND STATUS]';
} else if {
etc...
}
But, this gets really messy, really quickly as I would need to have 9 or so "else if" statements to cover all of the possible scenarios.
My question is, is there a cleaner way to handle this in a single query, or at least with out all of these "else if" statements?
You could do something along the lines of:
$query = 'SELECT * FROM TABLE WHERE';
$flag = 0;
if ($_POST['name']) {
$query .= ' NAME = "' . $_POST['name'] . '"';
$flag = 1;
}
if ($_POST['location']) {
if ($flag) { $query .= " AND "; }
$query .= ' LOCATION = "' . $_POST['location'] . '"';
$flag = 1;
}
if ($_POST['status']) {
if ($flag) { $query .= " AND "; }
$query .= ' STATUS = "' . $_POST['status'] . '"';
}
Although, I'm not sure how much better it will make your code look.
Also this is assuming that you will have at least one value passed through your post request.

insert value from drop down box to the database

I am missing something from my code and I don't know how to make it work. I may have programed it wrong and that could be giving me my troubles. I am new at php and things have been going slowly. please understand that the code my not be organized as it should be. After creating about 12 pages of code I found out that I should be using mysqli or pod. Once I get everything working that will be the next project. Enough said here is my issue. I was able to populate my drop down box and there shows no errors on the page. Also all the data does get inserted into the database except for the section made on the drop down box. Here is my code. I will leave out all of the input fields except the drop down.
<?php
{$userid = $getuser[0]['username'];}
// this is processed when the form is submitted
// back on to this page (POST METHOD)
if ($_SERVER['REQUEST_METHOD'] == "POST")
{
# escape data and set variables
$tank = addslashes($_POST["tank"]);
$date = addslashes($_POST["date"]);
$temperature = addslashes($_POST["temperature"]);
$ph = addslashes($_POST["ph"]);
$ammonia = addslashes($_POST["ammonia"]);
$nitrite = addslashes($_POST["nitrite"]);
$nitrate = addslashes($_POST["nitrate"]);
$phosphate = addslashes($_POST["phosphate"]);
$gh = addslashes($_POST["gh"]);
$kh = addslashes($_POST["kh"]);
$iron = addslashes($_POST["iron"]);
$potassium = addslashes($_POST["potassium"]);
$notes = addslashes($_POST["notes"]);
// build query
// # setup SQL statement
$sql = " INSERT INTO water_parameters ";
$sql .= " (id, userid, tank, date, temperature, ph, ammonia, nitrite, nitrate, phosphate, gh, kh, iron, potassium, notes) VALUES ";
$sql .= " ('', '$userid', '$tank', '$date', '$temperature', '$ph', '$ammonia', '$nitrite', '$nitrate', '$phosphate', '$gh', '$kh', '$iron', '$potassium', '$notes') ";
// #execute SQL statement
$result = mysql_query($sql);
// # check for error
if (mysql_error()) { print "Database ERROR: " . mysql_error(); }
print "<h3><font color=red>New Water Parameters Were Added</font></h3>";
}
?>'
Here is the drop down
<tr><td><div align="left"><b>Tank Name: </b> </div></td><td><div align="left">
<?php
echo "<select>";
$result = mysql_query("SELECT tank FROM tank WHERE userid = '$userid'");
while($row = mysql_fetch_array($result))
{
echo "". $row["tank"] . "";
}
echo "";
?>
</div></td></tr>
You missed some code in while loop.
while($row = mysql_fetch_array($result))
{
echo "<option>".$row['tank']."</option>";
}
echo "</select>";
are you able to build drop down menu or box. if not try this query
$sql="SELECT `tank` FROM `tank` WHERE user_name='$user'";
$result=mysqli_query($dbc,$sql)
//here $dbc is a variable which you use to connect with the database.
Otherwise leave that only read from here why you need to change your code. in the while loop
one one more thing you have to give your select attribute a name, because it will return the value through name so give a name to your select attributes as you are using tank while building your drop down menu so i will give a same name tank. Than you dont have to change anything.
and you have to give value to your option as well, thanks
echo "<select name='age'>";
while($row = mysql_fetch_array($result))
{
echo "<option value='" . $row['tank'] . "' >" . $row['tank'] . "</option>";
}
echo "</select>";

Search Form Ability To Ignore Blank Fields

I have made a HTML search form which creates a query to a MySql database based on the contents of a form. What I would love to do is ignore the search parameter if the user leaves that specific form field empty. There are lots of answers online, especially on this website, but I can't get any of them to work.
I have stripped down my code as much as possible to paste into here:
The HTML input:
<form action="deletesearchresults.php" method="GET">
<p><b>First Part Of Postcode</b>
<input type="text" name="searchpostcode"></b> </p>
<p><b>Category</b>
<input type="text" name="searchfaroukcat"></b>
<input type="submit" value="Search">
</p>
</form>
The PHP results display:
<?php
mysql_connect("myip", "my_username", "my_password") or die("Error connecting to database: ".mysql_error());
mysql_select_db("my_db") or die(mysql_error());
$sql = mysql_query("SELECT * FROM
GoogleBusinessData
INNER JOIN TblPostcodeInfo ON GoogleBusinessData.BusPostalCode = TblPostcodeInfo.PostcodeFull WHERE PostcodeFirstPart = '$_GET[searchpostcode]' and FaroukCat = '$_GET[searchfaroukcat]' LIMIT 0,20");
while($ser = mysql_fetch_array($sql)) {
echo "<p>" . $ser['BusName'] . "</p>";
echo "<p>" . $ser['PostcodePostalTown'] . "</p>";
echo "<p>" . $ser['PostcodeArea'] . "</p>";
echo "<p>" . $ser['FaroukCat'] . "</p>";
echo "<p> --- </p>";
}
?>
This works great until I leave one field blank, in which case it returns no results as it thinks I am asking for results where that field is empty or null, which I don't wat. I want all of the results where that form field is empty.
I tried combining a like % [myfeild] % etc but I only want the results to display exactly what is on the field and not just the ones that contain what is in the field, for example searching for the postcode "TR1" would return results for TR1, TR10, TR11 etc.
I believe I may need an array but after 3 days of trying, I just don't know how to get this done.
Any help would be amazing.
edit: Also, I will be adding up to ten fields to this form eventually and not just the two in this example so please bear this in mind with any suggestions you may have.
try using isset()
example
if(isset($_GET[searchpostcode]) && isset($_GET[searchfaroukcat])){
$fields = "WHERE PostcodeFirstPart = '$_GET[searchpostcode]' and FaroukCat = '$_GET[searchfaroukcat]'";
}elseif(isset($_GET[searchpostcode]) && !isset($_GET[searchfaroukcat])){
$fields = "WHERE PostcodeFirstPart = '$_GET[searchpostcode]'";
}elseif(!isset($_GET[searchpostcode]) && isset($_GET[searchfaroukcat])){
$fields = "WHERE FaroukCat = '$_GET[searchfaroukcat]'";
}else{
$fields = "";
}
$sql = "SELECT * FROM
GoogleBusinessData $fields
INNER JOIN TblPostcodeInfo ON GoogleBusinessData.BusPostalCode = TblPostcodeInfo.PostcodeFull LIMIT 0,20";
You do however need to escape your $_GET variables however i would highly recommend using PDO/mysqli prepared statements http://php.net/manual/en/book.pdo.php or http://php.net/manual/en/book.mysqli.php
or try a foreach loop
foreach($_GET as $keys=>$value){
$values .= $keys."='".$value."' and";
}
$values = rtrim($values, " and");
if(trim($values) != "" || trim($values) != NULL){
$query = "WHERE ".$values;
}else{
$values = "";
}
$sql = "SELECT * FROM `test`".$values;

Please help me to debug this code

Bit confused with this one.
Basically, I have a column in a table, and I want to retrieve the value in that column, for a specific row.
I have one set of code that works, but not in this particular situation.
The code I have that works is this:
$qry="SELECT * FROM logins WHERE username='$login' AND password='$password'";
$result=mysql_query($qry);
This obviously retrieves that particular row, and then:
$member = mysql_fetch_assoc($result);
$_SESSION['SESS_MEMBER_ID'] = $member['User ID'];
This successfully sets the session variable, as the value from the user id column from this row.
So that's fine, that works. The code I am trying to use in my new situation is this:
$qry = "SELECT * FROM vote WHERE Username = '" .$_SESSION['SESS_USERNAME']. "'";
$result = mysql_query($qry);
This gets the row based on the current user, and then:
while($row = mysql_fetch_array( $result ))
{
Print "<b>Name:</b> ".$row['Username'] . " <br>";
Print "<b>Vote:</b> ".$row['Vote'] . " ";
}
The while loop works correctly, it displays the current username, and their vote. Obviously I felt the loop was not required as I already have just the one row selected. Removing the loop broke it, so I put it back. Not a big deal, I can live with that if it gets the job done.
The issue I am focusing on, is the use of the
$row['Username']
In this if statement:
if($row['Username'] == "Admin") {
echo ("Win!<br />");
}
else {
echo "Failed!";
}
When printing from the loop above, it prints:
Name, as Admin,
and vote, as 0.
If I then try to validate using the if statement, I ask it to echo Win! if the username == Admin.
Obviously it is true as it has printed it on the line before, however, it always prins Fail! and I can't understand why.
Should I set $row['Username'] as some other variable?
Can anyone offer their guidance please?
Cheers
Eds
The problem stems from your loop:
while($row = mysql_fetch_array( $result ))
{
Print "<b>Name:</b> ".$row['Username'] . " <br>";
Print "<b>Vote:</b> ".$row['Vote'] . " ";
}
The first time through, $row is set to the row of data from the database. It then tries to go through the loop again, but since there is only one row, mysql_fetch_array returns false. now $row is set to false. So any code after the loop won't have access to the data anymore.
The solution would be to replace your loop with a simple if statement:
if ($row = mysql_fetch_array( $result ))
{
Print "<b>Name:</b> ".$row['Username'] . " <br>";
Print "<b>Vote:</b> ".$row['Vote'] . " ";
}
I fail to see how your PHP code could produce that "it prints" sample. However, check that your Username field actually contains an exact "Admin" string. It may have a linebreak or other whitespace in it. Doing a
var_dump($row['Username']);
should show something like
string(5) Admin
The bracketed number (5) is the length of the string. If it's not 5, then you've got some extra stuff in the string causing the == 'Admin' test to fail.

Insert data in multiple tables if a checkbox is checked

I am creating a user registration form with simple requirements.and insert data with simple query
<?php
if (isset($_POST) && isset($_POST["form_register"]))
{
$insert_query = "INSERT INTO users SET
users.first_name='" . mysql_real_escape_string($_POST['fname']) . "',
users.last_name='" . mysql_real_escape_string($_POST['lname']) . "',
users.email='" . mysql_real_escape_string($_POST['email']) . "',
users.password='" . mysql_real_escape_string($_POST['password']) . "';";
if (mysql_query($insert_query))
{
$_SESSION['messageType'] = "success_msg";
}
else
{
$_SESSION['message'] = "-Registration not Successful.";
$_SESSION['messageType'] = "error_msg";
}
}
?>
but now I have 3 extra fields in this form. If I select a checkbox then the other 2 field data go in another table with having this data also. how can i do that?
It is my old code...now I add 3 new columns, 1 checkbox and 2 text boxes.
The query is, if checkbox is selected then other 2 colums values go in another table and if checkbox is not select then working 1 query.
If I understand right you want to insert data in another table IF user check the checkbox.
So you have to use another IF like this:
if (mysql_query($insert_query))
{
if (/* here your condition for checkbox*/)
{
/* here your query for the secund table and the new two values*/
}
$_SESSION['messageType'] = "success_msg";
}
Note that is extremely important you run the secund query after the success of the first, cause if the first fails for some reason, secund will not be executed.
We really need to see your form as what you're providing us is way too vague, also, check the ending syntax for your $insert_query.
If I comprehended the question right, the final code should look something like this.
Tell me if I'm wrong
<?php
if(isset($_POST) && isset ($_POST["form_register"])){
$insert_query1 = "INSERT INTO users SET
first_name='".mysql_real_escape_string($_POST['fname'])."',
last_name='".mysql_real_escape_string($_POST['lname'])."',
email='".mysql_real_escape_string($_POST['email'])."',
password='".mysql_real_escape_string($_POST['password'])."'";
if(mysql_query($insert_query)){
$_SESSION['messageType'] = "success_msg";
} else {
$_SESSION['message'] = "-Registration not Successful.";
$_SESSION['messageType'] = "error_msg";
}
if($_POST['checkbox']) {
$insert_query2 = ""; //Put your second MYSQL Query here
}
if(mysql_query($insert_query2)){
$_SESSION['messageType2'] = "success_msg";
} else {
$_SESSION['message2'] = "-Registration not Successful.";
$_SESSION['messageType2'] = "error_msg";
}
}
?>

Categories