MySQL AND Query Not Working From PHP File - php

This is really bugging me now as I've got this to work in phpmyadmin but can't get it to work from my php script.
The code below is a basic php file (I'm learning) where the user submits a part number and an order number in a form which is then passed to a query (via variables), and the query result is returned to a table in the same page.
I can get it to work fine when only passing the part variable $input, but when I pass the AND criteria, no results are returned. I have checked and checked again the table and the combination tested should work. I've tried hardcoding a part number and order number combination and the same happens (okay with just the part but not when you add the AND section). Testing this part AND order combination on phpmyadmin gives the desired effects. Have I missed something?
<?php include 'database.php' ; ?>
<?php
$input =$_GET['part'];
$ord = $_GET['order'];
// This query works fine with just the $input criteria but when I add AND 'Order' etc... it produces zero results.
$query = "SELECT * FROM `part_status` WHERE `Part` = '$input' AND `Order` = '$ord'";
$result = $conn->query($query);
$status = $result->fetch_assoc();
?>
<!DOCTYPE html>
<html>
<head>
<title>Part Archive</title>
</head>
<body>
<!-- Form for submitting the two criteria of the query -->
<form method="get" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Part Number: <input type="text" name="part" value="<?php echo $part;?>" placeholder="Enter part number">
Order: <input type="text" name="order" value="<?php echo $order;?>" placeholder="Enter order number">
<input type="submit">
</form>
<header><h1>Orders For: <?php echo $input;?></h1></header>
<!-- Table for displaying the result of the slq query at the top -->
<table>
<tr><th>Part</th><th>Qty</th><th>Due Date</th><th>Order No.</th></tr>
<?php while($row = $result->fetch_assoc()) : ?>
<tr><td><?php echo $row['Part']; ?></td><td><?php echo $row['Qty']; ?></td><td><?php echo $row['Due Date']; ?></td><td><?php echo $row['Order']; ?></td></tr>
<?php endwhile ;?>
</table>
</body>
</html>
Always grateful for any pointers or suggestions.

Thanks #dbarthel for this solution...
I removed $status = $result->fetch_assoc(); and also the while loop replacing <?php while($row = $result->fetch_assoc()) : ?> and <?php endwhile ;?> with just <?php $row = $result->fetch_assoc()) ; ?> and this returned a record as requested in the form.
Thanks to all for your help and support. I can now move forward and try to develop this further.

Related

Populate Table from more than one drop-down list

I'm trying to populate a Table after a user picks options from a drop down list when this options are picked the table should be populated based on selected options. I'm not sure how can I get this done and I've searched for tutorias etc but nothing helped me. So I'll be glad if someone can help somehow for example with small test codes etc.
I'm using PHP and the options for the drop-down list come from a MySQL-Database so in summary a person will choose a user from Users-drop down list after that a another option from different drop down list and then there's also going to be a date filter after 1, 2 or all 3 are selected a table will be produced based on the selected values.
So far I've no code done because I have no idea how to do it but I guess I need to put all 3 dropdown lists in a form and after submission I should produce the table, but how can I have more than one <select> ..... </select> in a <form> and submit them all simultaneously.
What I've done so far (I know it's unsafe and that mysql_* doesn't exist anymore in PHP7) but please don't criticize it.
UPDATE
//Database query for User drop-down(DD) population.
$sqlDD = " SELECT DISTINCT `user` FROM `users` " ;
$resultDD = mysql_query($sqlDD);
//Database query for Status drop-down(DD) population.
$sqlDDStatus = " SELECT `status` FROM `status` WHERE `id` = 1 OR
`id` = 123 OR `id` = 182 OR `id` = 12 ";
$resultDDStatus = mysql_query($sqlDDStatus);
<form id="form1" name="form1" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
<select name="userSelect">
<?php
while($rowDD = mysql_fetch_array($resultDD)):
echo "<option value='" . htmlspecialchars($rowDD['user']) ."'>" . htmlspecialchars($rowDD['user']) ."</option>"; ?>
<?php endwhile; ?>
</select>
<!-- Second DD-list in the same form -->
<select name="Status" style="max-width: 250px;" >
<?php
while($rowDDS = mysql_fetch_array($resultDDStatus)):
echo "<option value='" . htmlspecialchars($rowDDS['status']) ."'>" . htmlspecialchars($rowDDS['status']) ."</option>"; ?>
<?php endwhile; ?>
</select>
<input type="submit" name="submit" value='Find'/>
</form>
//Get the submited data
<?php if(isset($_POST['submit'])): ?>
<?php echo 'This is submitted ' . $_POST['submit']; ?>
<?php endif; ?>
I've added echo 'This is submitted ' . $_POST['submit'];
because i wanted to see what is submitted but all it get's echoed out is only
"Find".
Any ideas how can i get the data submitted from both 's in the form and populate a table based on it ?
UPDATE 2
After getting an answer from other users I saw that my forms handles the data correctly but my question now is how can I use the data from the Submitted DDL Form and populate a table with them? So far I've tried the following:
<?php if(isset($_POST['submit'])): ?>
<?php $result = mysql_query( "SELECT * FROM `users` WHERE `user` =
$_POST['userSelect'] AND (`id` = 1 OR `id` = 18)" );
?>
<?php endif; ?>
and then in the table
<table>
<?php while ($row = mysql_fetch_assoc($result)) :; ?>
<tr>
<td><?php echo $row['user']; ?></td>
<?php endwhile; ?>
</table>
But I just don't get any response when I try it. How can I fix my problem and get the wanted output?
EDIT
I think that i've found my mistake after some research im not able to test the code now but i'm almost positive that you can't use $_POST['userSelect'] in the Database query so i just need to assign $_POST['userSelect'] to some variable before i use it in the query. So far i've gotten useful 1 little useful tip...... so disappointed from stackoverflow .......
This is a basis HTML/PHP page for getting data from the backend to the frontend, this should get you started. Try to print the data (in the while loop on the HTML page).
<html>
<head>
<title></title>
</head>
<body>
<form action="dropdown.php" method="POST">
<select name='options'>
<option>option 1</option>
<option>option 2</option>>
<option>option 3</option>>
</select>
<input type="submit" value="Submit">
</form>
</body>
</html>
<?php
$mysqli = new mysqli("localhost", "user", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}else{
if (!empty($_POST)){
if(!empty($_POST['options'])){
$option = $_POST['options'];
$query = "SELECT * FROM table WHERE option='$option'";
$res = $mysqli->query($query);
while($data = $res->fetch_assoc()){
//print data to HTML page
print_f('%s, $s\n', $data['firstname'], $data['lastname']);
}
}
}
}
?>
Your form is probably working, the reason you only get "Find" is because you are printing the value of the submit button.
To get an overview of your form data, try:
echo '<pre>';
print_r($_POST);
echo '</pre>';
You will get the other values of your form by using the name attribute of your <select> with $_POST:
echo $_POST['userSelect'];
echo $_POST['Status'];
By the way, you are using a deprecated extension (written here for example), it is recommended to use MySQLi or PDO (especially PDO is recommended). If you are working with PHP 7, mysql_connect won't work as it has been removed.
And I'm not sure the use of htmlspecialchars() is relevant on each database data you use.
PHP.net - print_r() (See also var_dump())
PHP.net - $_POST

Getting all checked items from a while loop and put them into database as true or false

I am currently doing up a list of names that has signed up for a activity which is then needed to go through another selection process and to be put into the database. I have currently done the getting and displaying of names from the people that has signed up.
However, I am not too sure on the process of how I can get those checked which is being selected in the selection process.
This is currently the codes that I have done to get and display the names of the people who have signed up. Upon clicking submit, it would go to another page which would then process, get those checked and marked as 1 or true to the database (MySQL) or either set as 0 or false if it has not been checked.
<?php
if ($totalShortlist > 0) {
?>
<?php
while ($row = mysqli_fetch_assoc($result)) {
$firstName = $row['first_name'];
$lastName = $row['last_name'];
?>
<form id="selectionProcess" action = "doShortlistProcess.php?id=<?php echo $id ?>" method = "post">
<fieldset data-role="controlgroup">
<label><input type="checkbox" name="selectionProcess" id="selectionProcess" value="<?php echo $id ?>"/><?php echo $firstName; ?> <?php echo $lastName; ?></label>
</fieldset>
<?php
}
?>
<input type="submit" class="btnSelect" data-theme="b" data-inline="true" name="shortlistCandidate" value="Submit Shortlisted Candidates"/>
</form>
<?php
}
// end for loop
else {
echo "No candidates to be shortlisted";
}
mysqli_close($link);
?>
The $id as shown is the brought over from the list of categories on the previous page, which allows to get all the names in that categories to be displayed.
Your code places the form in the wrong place compared to the while loop. The action also doesn't need you to compose a query string. Better code (careful, I've also cut out some presentation):
if ($totalShortlist > 0) {
?>
<form id="selectionProcess" action = "doShortlistProcess.php" method = "post">
<fieldset>
<?php
// use while loop to display a tick box for each item
while ($row = mysqli_fetch_assoc($result)) {
$firstName = $row['first_name'];
$lastName = $row['last_name'];
?>
<label>
<input type="checkbox" name="selectionProcess" id="selectionProcess" value="<?php echo $id ?>"/>
<?php echo $firstName; ?> <?php echo $lastName; ?>
</label>
<?php
} // end of while loop
?>
</fieldset>
<input type="submit"/>
</form>
<?php
} // end of shortlist > 0
I recommend you test this code using the GET method. It will show you what form the submission takes.
To process the result, you should use the list of responses, process it and turn it into one or more SQL statements.
An alternative would be to use an action for each checkbox, but then use ajax to a php page that would modify the status of single subscriber. The change would be made immediately as users click.

UPDATE inside a WHILE statement

So, I have a page with a bunch of workorders on it. Each workorder is a row in a single table, and gets put on the page with a while() statement.
I'm trying to update each row with a simple form that I put inside the while(), and an UPDATE/WHERE statement to actually add the information to the table.
Instead of adding it to the specific row, it adds it to Every row. The only thing I can think of is that my WHERE condition is wrong, but I can't seem to figure it out. Maybe it just needs fresh eyes, or maybe I'm heading in Completely the wrong direction.
Also, any specific instructions on security, a better way to do it, etc. would be very helpful. I'm learning PHP on the fly and could use a helping hand. :)
<?php
$query = "SELECT * FROM client_information";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
$which_ad = $row['ID'];?>
<b>Name:</b> <? echo $row['billing_name']; ?> <br>
<b>Job Type:</b> <? echo $row['job_type']; ?> <br>
<b>Size:</b> <? echo $row['size']; ?> <br>
<b>Text:</b> <? echo $row['text']; ?> <br>
<b>Notes:</b> <? echo $notes; ?> <br>
<br><br>
<form action="small_update.php" method="POST">
<strong>Email Message:</strong><br>
<textarea rows="8" cols="60" name="email_message"></textarea>
<input type="submit" name="submit" value="Submit"></form>
<?
$email_message = htmlspecialchars ("{$_POST['email_message']}", ENT_QUOTES);
if (mysql_errno() != 0) {
die(mysql_error());
}
mysql_query(
"UPDATE client_information
SET email_message='$email_message'
WHERE ID='$which_ad'"
);
if (mysql_errno() != 0) {
die(mysql_error());
}
}
?>
You don't specify the id in your form:
<form action="small_update.php" method="POST">
<strong>Email Message:</strong><br>
<textarea rows="8" cols="60" name="email_message"></textarea>
<input type="hidden" name="id" value="<?php echo $which_ad; ?>">
<input type="submit" name="submit" value="Submit">
</form>
you need to also make sure you know what id was submitted:
"UPDATE client_information
SET email_message='$email_message'
WHERE ID='$_POST['id']'"
Of course, you're wide open to attacks like this as everyone else is saying. You need to look into mysqli or pdo to sanitize your input...
Ans also upon inspection you're evaluating your post data in the loop. Don't do that. Just do your evaluation before everything else is processed on the page...
<?php
if($_POST)
{
//run processing here
}
// do your fetch code here and display the forms...

passing an array through the function

My website is featuring online classified advertisements, programmed by PHP and MySQL. The following code let the administrator delete multiple records using the checkbox tool.
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" >
<table>
<td><? echo $rows['CountryName']; ?></td>
<td><input name="delete_items[]" type="checkbox" value="<?php echo $rows['id']; ?>" /></td>
</table>
<input type="submit" name="deleteSelected" value="Submit" >
</form>
<?php
if(isset($_POST['deleteSelected'])) {
$delete_items = join(', ', $_POST["delete_items"]);
$query = "DELETE FROM $table_name WHERE id IN ($deleted_items)";
$result = mysql_query($query);
header("Location: admin.php"); }
?>
When I press the submit button without checking boxes (all boxes are unchecked), I receive the following error message (p.s. the script is working well without any error message, if any Checkbox being checked):
Warning: join() [function.join]: Invalid arguments passed in C:\xampp\htdocs\admin_listing.php on line 87
I’ve tried the implode function instead of using join, but still I'm getting an error message.
Maybe I do not passing an array through the function correctly, but I cannot find a solution for the above.
Any advise would be appreciated.
It looks like you are displaying all the records from your database into a single input in the form.
The code will probably work well with the implode() as you tried, but you will need to use a loop in the displaying of the form to generate it properly with the options.
Something like this:
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" >
<table>
<?php
while($row=$databaseResult) //however you are getting the data out of the database.
{
echo "<tr><td>".$rows['CountryName']."</td><td><input name='delete_items[]' type='checkbox' value=".$rows['id']."/></td></tr>";
}
?>
</table>
<input type="submit" name="deleteSelected" value="Submit" >
</form>
Thank you all for trying to help, I found a simple solution by adding one code line, as follows:
<?php
if(isset($_POST['deleteSelected'])) {
if(isset($_POST["delete_items"][0])) {
$delete_items = join(', ', $_POST["delete_items"]);
$query = "DELETE FROM $table_name WHERE id IN ($delete_items)";
$result = mysql_query($query);
header("Location: admin.php");
}
}
?>
Hope it can help someone else...

Getting php value in html

I am trying to display the name retrieved from Database in html file . Referred couple of blogs, still I am not able to display the value
<?php
$result=mysql_query("SELECT * from `Data` where Emp_Id = $EmpID")
$info = mysql_fetch_array( $result );
$Emp_ID=$info['Emp_ID'];
<html><head>
<body>
<input name="emp_number" value=<?php echo $Emp_ID?>/>
<input name='emp_name' value="<?php echo (isset($Emp_ID) ? htmlspecialchars($Emp_ID) : ''); ?>" />
<input name='emp_name'<?php echo (isset($Emp_Name)) ? ('value = "'.$Emp_Name.'"') : "value = \"\""; ?>/>
</body></head></html>
?>
Tried three ways, but none of them worked.
You should use a template system.
Beside of that try this:
<?php
$result=mysql_query("SELECT * from `Data` where Emp_Id = $EmpID")
$info = mysql_fetch_array( $result );
$Emp_ID=$info['Emp_ID'];
?>
<html>
<body>
<input name="emp_number" value=<?php echo $Emp_ID; ?>/>
<input name='emp_name' value="<?php echo (isset($Emp_ID) ? htmlspecialchars($Emp_ID) : ''); ?>" />
<input name='emp_name'<?php echo (isset($Emp_ID)) ? ('value = "'.$Emp_ID.'"') : "value = \"\""; ?>/>
</body>
</html>
This is the third time this week I've seen a similar question to this.
Please search SO and look for related questions
$EmpID is never being set
Your code is vulnerable to SQL injection and your site is likely to soon get hacked
Your query has a discrepancy between Emp_ID and your returned result Emp_Id
You've got two input fields with the same name, so only one will be returned on Post/Get
$Emp_Name is never set anywhere (guessing it should come form info?)
Also on the third input, you should have a space before you echo your "value=" field
Looks like the Emp_ID in line three should be Emp_Id or the Emp_Id in line one should be Emp_ID.

Categories