error on php exact search with multiple options - php

I'd like to create "Exact Search" with multiple options but the answer says "Could not search".
In the table, price, one and pre are rows.
If the answer matches one and pre, the separated price will be come out. If not, the reply will be "Try agian".
Edited : I have three tables - pre, one and price.
- KA 1 will win 100
- KA 5 will win 500
- MA 3 will win 100
- MA 1 will win 200
- BA 3 will win 800
Edited : I changed the code now and no error shown but the result was always 'Try Again'.
<?php
$output = NULL;
$link = mysqli_connect("localhost","root","","searchdemo") or die("Unable to select database" . mysqli_error($link));
if(isset($_GET['search'])){
$searchq = $_GET['search'];
$searchq = preg_replace("#[^0-9a-z]#i","",$searchq);
$query = mysqli_query ($link, "SELECT * FROM `345` WHERE pre = '$searchq' AND one = '$searchq'") or die("<b>Error</b> : ".mysqli_error($link));
$count = mysqli_num_rows($query);
if ($count == 0){
$output = 'Try Again';
}else{
while($row = mysqli_fetch_array($query)){
$onen = $row['one'];
$pren = $row['pre'];
$price = $row['price'];
$output = 'You won '.$price.' now';
}
}
}
?>
<form name="search1" action="index.php" method="GET">
<b>Prefix</b>
<select name="pre">
<option value="">Pick a prefix</option>
<option value="Ka">Ka</option>
<option value="Ba">Ba</option>
<option value="Ma">Ma</option>
</select>
<b>Number</b>
<select name="one">
<option value="">Pick a number</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
<input type="submit" name="search" value="Search" />
</form>
<?php
print ("$output");
//echo ($output);
?>

If die() is called, it means that the query failed, so I'd start looking for a reason there.
You are missing WHERE in your query, it should start with
SELECT * FROM 345 WHERE ...
Keep in mind that your code is open for SQL injecion attack. You must to escape all user input that gets into your query.
Simplest way to do it is to use http://php.net/manual/en/function.mysql-real-escape-string.php (deprecated since PHP 5.5) or http://php.net/manual/en/mysqli.real-escape-string.php. You could also use PDO prepared statements for your queries (http://php.net/manual/en/book.pdo.php)

Some general pointers for you here:
You need a WHERE clause in your SQL statement to define the criteria of your search. The search will work without it but it will return everything, which is not what you want. (This has already been fixed)
You need a AND or an OR statement between your variables, in your WHERE clause, because you are asking "show this WHERE condition1 is true AND/OR condition2 is true"
Replace your die command with a better and more informative feedback:
This will output why the search failed. Use this to fix further errors.
or die("Could not search: ".mysql_error());
As mentioned by jedrzej.kurylo, you are wide open for injection attacks on your database and it is very important to fix these, either as they suggest or by upgrading your code to using MySQLi or PDO . Do this now while you're still learning the basics of SQL because it's far better than getting into the bad habit of using old, deprecated and insecure MySQL.

Finally I got the answer and that was so easy. What a dumb I am! :)
I do really thanks to #Martin and #jedrzej.kurylo
<?php
$output = NULL;
$link = mysqli_connect("localhost","root","","searchdemo") or die("Unable to select database" . mysqli_error($link));
if(isset($_POST['search'])){
$spre = $_POST['pre'];
$sone = $_POST['one'];
$query = mysqli_query ($link, "SELECT * FROM `345` WHERE pre = '$spre' AND one = '$sone'") or die("<b>Error</b> : ".mysqli_error($link));
$count = mysqli_num_rows($query);
if ($count == 0){
$output = 'Try Again';
}else{
while($row = mysqli_fetch_array($query)){
extract($row);
$onen = $row['one'];
$pren = $row['pre'];
$price = $row['price'];
$id = $row['id'];
$output = 'You won '.$price.' now';
}
}
}
?>
<form name="search1" action="index.php" method="POST">
<b>Prefix</b>
<select name="pre">
<option value="">Pick a prefix</option>
<option value="Ka">Ka</option>
<option value="Ba">Ba</option>
<option value="Ma">Ma</option>
</select>
<b>Number</b>
<select name="one">
<option value="">Pick a number</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
<input type="submit" name="search" value="SEARCHING" />
</form>
<?php
print ("$output <br />");
?>

Related

Connect an interactive html form to a sql database

I'm trying to create an html form to provide information about the salaries table in my database, the user should be able to pick year between 1986-1996 and choose if she wants to see the total salary of that year or the average salary of that year.
I have no idea how I link up these scripts and I can't find much online.
html file:
<html>
<body>
<fieldset>
<form id="frmName" method=post action="Oppgave4.php" onsubmit="">
<h1>Oppgave 4</h1>
Choose year:
<select id="frmName" onChange="">
<option selected disabled hidden>----</option>
<option name="1986">1986</option>
<option name="1987">1987</option>
<option name="1988">1988</option>
<option name="1989">1989</option>
<option name="1990">1990</option>
<option name="1991">1991</option>
<option name="1992">1992</option>
<option name="1993">1993</option>
<option name="1994">1994</option>
<option name="1995">1995</option>
<option name="1996">1996</option>
</select>
Total or average salary:
<select id="frmName" onChange="">
<option selected disabled hidden>----</option>
<option name="Total">Total salary</option>
<option name="Average">Average salary</option>
</select>
<input type="submit" value="Submit" id="submit">
</p>
</form>
</fieldset>
</body>
</html>
php file:
<?php
$year = ($_POST['1986'], $_POST['1987'], $_POST['1988'], $_POST['1989'], $_POST['1990'],
$_POST['1991'], $_POST['1992'], $_POST['1993'], $_POST['1994'], $_POST['1995'],
$_POST['1996'], $_POST['Total']);
$average = $_POST['Average'];
$conn = mysqli_connect("localhost", "root", "", "employees");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sqlavg = "SELECT AVG(salaries.salary) AS average FROM salaries
WHERE from_date = '$year'";
$result = $conn->query($sql);
if (!empty($result) && $result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["average"] ."</td></tr>";
}
echo "</table>";
$sqlsum = "SELECT SUM(salaries.salary) AS total FROM salaries
WHERE from_date = '$year'";
$result = $conn->query($sql);
if (!empty($result) && $result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["total"] ."</td></tr>";
}
echo "</table>";
} else { echo "0 results"; }
$conn->close();
?>
What you're trying to do is literally PHP/MySQL 101 and there is a lot online on how to do this. Having said that you are making some mistakes in your code. First, you should name the <select>
<select name="year">
Then you should give each option a value:
<option value="1994">1994</option>
...// do each one like this
This way, when the form is submitted to the PHP you can find it in the POST array:
$year = $_POST['year'];
That is just a start. You have a second drop-down that also needs a name and each option should have a value attribute.
<select name="calculation_type">
<option>----</option>
<option value="Total">Total salary</option>
<option value="Average">Average salary</option>
</select>
Which will be found like this in the POST array:
$average = $_POST['calculation_type'];
Your form needs a name and does not need the onsubmit The action should be the name of the PHP script which will perform the calculations:
<form name="form_name" method=post action="Oppgave4.php">
Warning
Little Bobby says your script is at risk for SQL Injection Attacks. Learn about prepared statements for MySQLi. Even escaping the string is not safe!
Suggestion
You should go work through some basic PHP tutorials like those offered by https://www.learn-php.org/ (a free, interactive website) or other services

Values not being submitted from PHP HTML form [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I am trying to take the input from drop down menus that users enter and submit them to a table in my database. I am trying to submit the values into this table:
I use the POST to check that the values are being pulled from the HTML form and they are, but they won't submit into my table. I've made sure that all of the names with the columns and HTML forms are correct, why won't the values post to the table?
<?php
$databaseName = 'pizza_db';
$databaseUser = 'root';
$databasePassword = 'root';
$databaseHost = '127.0.0.1';
$conn = new mysqli($databaseHost, $databaseUser, $databasePassword, $databaseName);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected sucessfully\n";
if(isset($_POST['submit'])){
$value = mysqli_real_escape_string($conn,$_POST['drink']);
$value2 = mysqli_real_escape_string($conn,$_POST['cheese']);
$value3 = mysqli_real_escape_string($conn,$_POST['veggies']);
$value4 = mysqli_real_escape_string($conn,$_POST['meat']);
$value5 = mysqli_real_escape_string($conn,$_POST['sauce']);
$value6 = mysqli_real_escape_string($conn,$_POST['crust']);
$value7 = mysqli_real_escape_string($conn,$_POST['size']);
$sql = "INSERT INTO order_info(drink,cheese,veggies,meat,sauce,crust,size)
VALUES('$value','$value2','$value3','$value4','$value5','$value6','$value7')";
//Here I am posting the values to check that they are being submitted
echo $_POST["size"];
echo "\n";
echo $_POST["sauce"];
echo "\n";
echo $_POST["crust"];
echo "\n";
echo $_POST["cheese"];
echo "\n";
echo $_POST["meat"];
echo "\n";
echo $_POST["veggies"];
echo "\n";
echo $_POST["drink"];
$conn->close();
}
?>
<!DOCTYPE html>
<html>
<body>
<form action='' method='post'>
<p>Choose a size<p>
<select id="size" name="size">
<option value="small">Small</option>
<option value="medium">Medium</option>
<option value="large">Large</option>
<option value="x-large">X-large</option>
</select>
<p> Choose a sauce <p>
<select id="sauce" name="sauce">
<option value="none">None</option>
<option value="marinara">Marinara</option>
<option value="alfredo">Alfredo</option>
<option value="ranch">Ranch</option>
<option value="bbq">BBQ</option>
</select>
<p> Choose a cheese<p>
<select id="cheese" name="cheese">
<option value="none">None</option>
<option value="mozzarelaa">Mozarella</option>
<option value="cheddar">Cheddar</option>
<option value="parmesan">Parmesan</option>
<option value="three cheese">Three-Cheese</option>
</select>
<p> Choose a meat <p>
<select id="meat" name="meat">
<option value="none">None</option>
<option value="Pepperroni">Pepperroni</option>
<option value="sausage">Sausage</option>
<option value="bacon">Bacon</option>
<option value="canadian bacon">Canadian Bacon</option>
<option value="chicken">Chicken</option>
<option value="salami">Beef</option>
<option value="anchovies">Anchovies</option>
</select>
<p> Choose a veggies <p>
<select id="veggies" name="veggies">
<option value="none">None</option>
<option value="onions">Onions</option>
<option value="green peppers">Green Peppers</option>
<option value="Red peppers">Red peppers</option>
<option value="Black olives">Mushrooms</option>
<option value="jalapenos">Jalapenos</option>
<option value="tomatoes">Tomatoes</option>
<option value="pineapple">Pineapple</option>
</select>
<p> Choose a crust <p>
<select id="crust" name="crust">
<option value="regular">Regular</option>
<option value="deep-dish">Deep-dish</option>
<option value="thin-crust">Thin Crust</option>
<option value="stuffed crust">Stuffed Crust</option>
<option value="gluten free">Gluten Free</option>
</select>
<p> Choose a drink <p>
<select id="drink" name="drink">
<option value="none">None</option>
<option value="rootbeer">Root Beer</option>
<option value="coke">Coke</option>
<option value="diet coke">Diet Coke</option>
<option value="dr pepper">Dr Pepper</option>
</select>
<input type="submit" name="submit" value="Submit"/>
</form>
</body>
</html>
Seems like you are not running the query.
// sql
$sql = "INSERT INTO order_info(drink,cheese,veggies,meat,sauce,crust,size)
VALUES('$value','$value2','$value3','$value4','$value5','$value6','$value7')";
// run query
mysqli_query($conn, $sql);
// or
$conn->query($sql);
You prepared string query but you are not executing it.
$sql = "INSERT INTO order_info(drink,cheese,veggies,meat,sauce,crust,size)
VALUES('$value','$value2','$value3','$value4','$value5','$value6','$value7')";
// run query with below mentioned function
mysqli_query($conn, $sql);
Then check your table. You will see the data saved.

PHP Add value to each table row data

i'm working on a php script wherein i must add certain score value at each row. I was able to display all the rows but i'm not sure on how would I able to store each of the given score in a variable and what query should I make to add all of them.
Here's my code
<?php
echo '<html>';
?>
<body>
<table border=0 cellspacing=0 cellpadding=0>
<?php
$connect = mysql_connect('localhost', 'root', '');
$db = 'labs';
$tb = 'comments';
$seldb = mysql_select_db($db, $connect);
echo '<form method="POST" action="..'.$_SERVER["PHP_SELF"].'">';
$query = mysql_query('SELECT com_id, comments FROM comments ORDER BY com_id ASC');
while($i = mysql_fetch_assoc($query)) {
echo'<tr><td>'.$i['comments'].'</td>';
echo'<td><select name="score" id="score" size="1">
<option value="5">5</option>
<option value="10">10</option>
<option value="15">15</option>
<option value="20">20</option>
<option value="25">25</option>
<option value="30">30</option>
<option value="35">35</option>
<option value="40">40</option>
<option value="45">45</option>
<option value="50">50</option>
</select></td></tr>';
echo'<br>';
}
echo'<input type="submit" name="submit" value="submit">';
echo'</form>';
if(isset($_POST['submit'])) {
//not sure if all the scores will be stored in here.
$id = $_POST['id'];
$query = mysql_query('insert query here');
}
?>
</table>
</body>
</html>
any suggestions are appreciated. Thanks in advance.:D
I think you need the id of each changed row (maybe as a hidden field for each row. Then just do a loop through all received rows and UPDATE each one.
You might also want to change all of your form field names to use the array format. This way it's easier to make your PHP loop throught them.
Sample row:
echo'<tr><td>'.$i['comments'].'</td>';
echo'<td><select name="score['.$i["id"].']" id="score" size="1">
<option value="5">5</option>
<option value="5">10</option>
<option value="5">15</option>
<option value="5">20</option>
<option value="5">25</option>
<option value="5">30</option>
<option value="5">35</option>
<option value="5">40</option>
<option value="5">45</option>
<option value="5">50</option>
</select></td></tr>';
Now just loop through the $_POST["score"] array and use the appropriate ID for your update.
foreach($_POST["score"] as $id => $value{
// ESCAPE your db values!!!!!
// query stuff with $value and $id
}
Also keep in Mind
mysql is deprecated! Use mysqli
Escape anything from outside sources like $_POST before use in SQL
You just needs to make an array of your drop down box like below,
while($i = mysql_fetch_assoc($query)) {
echo'<tr><td>'.$i['comments'].'</td>';
echo'<td><select name="score[".$i['com_id']."]" id="score" size="1">
<option valyue="5">5</option>
<option valyue="5">10</option>
<option valyue="5">15</option>
<option valyue="5">20</option>
<option valyue="5">25</option>
<option valyue="5">30</option>
<option valyue="5">35</option>
<option valyue="5">40</option>
<option valyue="5">45</option>
<option valyue="5">50</option>
</select></td></tr>';
echo'<br>';
}
and you can access it for all of your comments
<option valyue="5">50</option>
should be
<option value="5">50</option>
To send the value of a comment to database you need to add a ID of the comment
you should loop something like this.
$query = mysql_query('SELECT com_id, comments FROM comments ORDER BY com_id ASC');
while($i = mysql_fetch_assoc($query)) {
echo '<form method="POST" action="..'.$_SERVER["PHP_SELF"].'">';
echo '<input type="hidden" name="id" value="'.$i['com_id'].'">';
echo'<tr><td>'.$i['comments'].'</td>';
echo'<td><select name="score" id="score" size="1">
<option value="5">5</option>
<option value="5">10</option>
<option value="5">15</option>
<option value="5">20</option>
<option value="5">25</option>
<option value="5">30</option>
<option value="5">35</option>
<option value="5">40</option>
<option value="5">45</option>
<option value="5">50</option>
</select></td></tr>';
echo'<br>';
echo'<input type="submit" name="submit" value="submit">';
echo'</form>';
}
I guess the easiest way for you is the following (a mix of the other solutions and comments):
<?php
echo '<html>';
?>
<body>
<table border=0 cellspacing=0 cellpadding=0>
<?php
$x = 0;
$connect = mysql_connect('localhost', 'root', '');
$db = 'labs';
$tb = 'comments';
$seldb = mysql_select_db($db, $connect);
echo '<form method="POST" action="..'.$_SERVER["PHP_SELF"].'">';
$query = mysql_query('SELECT com_id, comments FROM comments ORDER BY com_id ASC');
while($i = mysql_fetch_assoc($query)) {
$x++;
echo'<tr><td>'.$i['comments'].'</td>';
echo'<td><select name="score_'.$x.'" id="score" size="1">
<option value="5">5</option>
<option value="10">10</option>
<option value="15">15</option>
<option value="20">20</option>
<option value="25">25</option>
<option value="30">30</option>
<option value="35">35</option>
<option value="40">40</option>
<option value="45">45</option>
<option value="50">50</option>
</select></td></tr>';
echo'<br>';
}
echo'<input type="submit" name="submit" value="submit">';
echo'</form>';
if(isset($_POST['submit'])) {
//not sure if all the scores will be stored in here.
$id = $_POST['id'];
for($y = 0;$y <= $x; $y++)
{
//This query is no sql injection save. Please add filters for productive uses!!
$query = mysql_query('UPDATE table_name SET score = '.$_POST["score_".$y].' WHERE id='.$id);
}
?>
</table>
</body>
</html>
Code is no tested!

Html form select blank to search all of the table where the other fields match

I have a form that searches a database and returns rows that match the fields specified. I want to give an option to the user that if the field is left blank, it won't matter what is is that column as long as the other fields match. Right now, if I leave a field 'blank' it will return every entry in the database.
Hair Color: <select name="hair">
<option value="hairall" selected="selected">--</option>
<option value="black" >Black</option>
<option value="brown">Brown</option>
<option value="blonde">Blonde</option>
<option value="white">White</option>
<option value="red">Red</option>
<option value="other">Other</option>
</select>
Height: <select name="height">
<option value="heightall" selected="selected">--</option>
<option value="smaller">Smaller</option>
<option value="small">Small</option>
<option value="average">Average - 70in</option>
<option value="tall">Tall</option>
<option value="taller">Taller</option>
</select>
Body Type: <select name="body">
<option value="bodyall" selected="selected">--</option>
<option value="skinny">Skinny</option>
<option value="average">Average - 194lb</option>
<option value="heavy">Heavy</option>
</select>
Ethnicity: <select name="ethnicity">
<option value="ethnicityall" selected="selected">--</option>
<option value="white">White</option>
<option value="black">Black</option>
<option value="asian">Asian</option>
<option value="hispanic">Hispanic</option>
<option value="middleeast">Middle Eastern</option>
<option value="other">Other</option>
</select><br/>
<center><input type="submit" value="Find Me" name="submit" ></center>
</form>
</div>
<div id="results">
<?php
$submit = $_GET['submit'];
$gender = $_GET['gender'];
$hair = $_GET['hair'];
$height = $_GET['height'];
$body = $_GET['body'];
$race = $_GET['ethnicity'];
//Hair All/Specific
if ($hair=='hairall'){
$newhair = "black' OR `hair`='brown' OR `hair`='blonde' OR `hair`='white' OR `hair`='red' OR `hair`='other";
}else
$newhair=$hair;
//Height All/Specific
if ($height=='heightall'){
$newheight = "smaller' OR `height`='small' OR `height`='average' OR `height`='tall' OR `height`='taller";
}else
$newheight=$height;
//Body Type All/specific
if ($body=='bodyall'){
$newbody = "skinny' OR `body`='average' OR `body`='heavy";
}else
$newbody=$body;
//Etnicity All/Specific
if ($race=='ethnicityall'){
$newrace = "white' OR `race`='black' OR `race`='asian' OR `race`='hispanic' OR `race`='middleeast' OR `race`='other";
}else
$newrace=$race;
//echo "$newhair <br/> $newheight <br/> $newbody <br/> $newrace<br/>";
require 'connect.inc.php';
$query = "SELECT * FROM `table` WHERE `gender`='$gender' AND `hair`='$newhair' AND `height`='$newheight' AND `body`='$body' AND `race`='$race' ORDER BY `id` DESC";
Put parenthesis around each of your values - i.e. ('$gender') instead of '$gender'. That will prevent your OR clauses from messing up your AND clauses, which is the problem you're having.
A better solution would be to remove the check from the query entirely if the field is left blank, but that would require rewriting about half your code. In any case, here's roughly how I would do it:
// Only accept the specific fields that are expected
$query_fields = array_intersect_key($_GET, array(
'gender'=>true,
'hair'=>true,
'height'=>true,
'body'=>true,
'ethnicity'=>true,
));
// Exclude blank fields
$query_fields = array_filter($query_fields, 'strlen');
$database = (require 'connect.inc.php'); // Get connection to database in this variable somehow
$where_parts = array();
foreach($query_fields as $k=>$v) {
$v = $database->real_escape_string($v);
$where_parts[] = "`$k` = '$v'";
}
if(!$where_parts)
die('No filters selected!');
$query = 'SELECT * FROM `table` WHERE '.implode(' AND ', $where_parts).' ORDER BY `id` DESC';

Php syntax Error

Hello im trying to swamp all my php scripts oto a new html template. This script was working be for i swapped it over to the new template but now it has stopped working...
I think maybe i could be missing a ' or have a space some were were i shouldn't
Here is my page
<?php
include 'config.php';
$myName = $_POST['myName'] ;
$mydropdown = $_POST['mydropdown'] ;
$_POST['mydropdown'] = mysql_real_escape_string($_POST['mydropdown']);
$_POST['myName'] = mysql_real_escape_string($_POST['myName']);
$sql = "SELECT * FROM user_pokemon WHERE id='".$_POST['myName']."'";
$result = mysql_query($sql) or die(mysql_error());
$battle_get = mysql_fetch_array($result);
$result = mysql_query("UPDATE user_pokemon SET slot=".$_POST['mydropdown']." WHERE id = '".$_POST['myName']."'")
or die(mysql_error());
?>
In side the config.php file i have the sql connect and and the session start which works fine on other page's so i don't think it is that im getting this 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 'WHERE id = ''' at line 1
I have a php form which posts to this page.
echo '
<div class="auction_box" style="height:150px">
<form name="myform" action="http://pokemontoxic.net/newy/testing.php" method="POST">
<p> </p>
<p> </p>
<p> </p>
<img src="http://pokemontoxic.net/'.$battle_get['pic'].'" height="96px" width="96px"/><br/>
Name:<br/>' .$v->pokemon. '<br/>
Level:' .$v->level. '<br/>
Exp:' .$v->exp. '<br/>
Slot you want to put your pokemon in
<select name="mydropdown">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
</select>
<input type="hidden" name="myName" value="' . $v->id . '" />
<input type="submit" value="Submit" />
</form>
Which works fine but is sending the info over to the top bit of code.
Let me see. i think this code is redundunt change it
$myName = $_POST['myName'] ;
$mydropdown = $_POST['mydropdown'] ;
$_POST['mydropdown'] = mysql_real_escape_string($_POST['mydropdown']);
$_POST['myName'] = mysql_real_escape_string($_POST['myName']);
to this :
$myName = mysql_real_escape_string($_POST['myName']);
$mydropdown = mysql_real_escape_string($_POST['mydropdown']);
and on your select query try this if it does not solve tell me the error:
$sql = "SELECT * FROM user_pokemon WHERE id='{$myName}'";

Categories