Getting no matching results for query mysql php [duplicate] - php

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 7 years ago.
I am trying to find matching results to my query in my database and put it in the table form I made, however I get no matching results back. I ran my query in phpmyadmin and got the desired output. I used var_dump on my $result variable and get the following: resource(4) of type (mysql result). here is my code:
<?php
function renderSearchForm($search, $search_by, $search_by, $error){
?>
<!DOCTYPE HTML5>
<head>
<title>Search Query</title>
</head>
<body>
<?php
//display errors
if($error != ''){
echo '<div style="padding:4px; border:1px solid red; color:red;">' . $error . '</div>';
}
?>
<form action="" method="post">
<div>
<p>Search For:</p>
<strong>Name: *</strong> <input type="text" name="search" value="<?php echo $search; ?>" /><br/>
<p>Search by:</p>
<input type="radio" name="search_by"
<?php if (isset($search_by) && $search_by=="firstname") echo "checked";?>
value="firstname"/>Firstname*
<input type="radio" name="search_by"
<?php if (isset($search_by) && $search_by=="surname") echo "checked";?>
value="surname"/>Surname*
<br><br>
<input type="submit" name="submit" value="Submit">
<p>* required</p>
</div>
</form>
</body>
</html>
<?php
}
//connect to db
include('connect_db.php');
//check if submitted
if (isset($_POST['submit'])) {
$search = mysql_real_escape_string(htmlspecialchars($_POST['search']));
$search_by = mysql_real_escape_string(htmlspecialchars($_POST['search_by']));
//check if search is empty
if (empty($_POST["search"])) {
$error = "Error: Name is required";
//error, display form
renderSearchForm($search, $search_by, $search_by, $error);
}
elseif
// check if name only contains letters and whitespace
(!preg_match("/^[a-zA-Z ]*$/",$search)) {
$error = "Error: Only letters and white space allowed";
//error, display form
renderSearchForm($search, $search_by, $search_by, $error);
}
//check if radio button selected
elseif (empty($_POST["search_by"])) {
$error = "Error: Search_by is required";
//error, display form
renderSearchForm($search, $search_by, $search_by, $error);
}else{
//save data
$query = "SELECT * FROM members WHERE '$search_by' LIKE '%$search%'";
$result = mysql_query($query)
or die(mysql_error());
var_dump($result);
//display data from db
echo "<table border='1' cellpadding='10'>";
echo "<tr> <th>ID</th> <th>Firstname</th> <th>Surname</th> <th>Telephone</th> <th>Cell</th> <th>Address</th> <th></th> <th></th> </tr>";
//loop through results of db and display in table
while ($row = mysql_fetch_array($result)) {
//echo contents in table
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['firstname'] . "</td>";
echo "<td>" . $row['surname'] . "</td>";
echo "<td>" . $row['telephone'] . "</td>";
echo "<td>" . $row['cellphone'] . "</td>";
echo "<td>" . $row['address'] . "</td>";
echo "<td><a href='edit.php?id=" . $row['id'] . "'>Edit</a></td>";
echo "<td><a href='delete.php?id=" . $row['id'] . "'>Delete</a></td>";
echo "</tr>";
}
echo "</table>";
//This counts the number or results
$anymatches=mysql_num_rows($result);
if ($anymatches == 0) {
echo "Sorry, but we can not find an entry to match your query<br><br>";
}
//And we remind them what they searched for
echo "<b>Searched For:</b> " .$search. "<b> In: </b>" .$search_by;
}
}else{
//if form not submitted, display form
renderSearchForm('','','','');
}
?>

You need to remove the single quotes between $search_by. Try this:
"SELECT * FROM members WHERE $search_by LIKE '%$search%'"

Related

PHP POST yields empty result using sqlite3 database

I have a simple web form in HTML using POST and PHP against an SQLite3 database. The form asks for a database id. When entered and hitting submit, the result does not output to the screen.
Here is the code. Please help! It appears the variable is empty. Where am I going wrong?
Original Form HTML (edit_entry1.html):
<body bgcolor = "#C7CFCA">
</p></p>
<center><h2>Update a Record<br>
<form method="POST" action="update_record.php">
<br />
<center>
<h3>To update a record click on 'View Database' and find the record ID you want to update and enter that ID here.</h3>
</center>
<table>
<tr><td><h2>Record ID: </td><td><h2><input style="font-size:20px" type="text" name="archivo" size="80"></td></tr>
<tr><td><input type="submit" name="save" value="Submit" style="font-size:20px"></td><td><input type=reset value="Reset Form" style="font-size:20px"></td>
</table>
</form>
</center>
</html>
This is the corresponding php script (update_record.php):
<?php
{
//open the database
$db = new SQLite3('wc.db');
// Set Variables from POST
$record = $_POST["archivo"];
//now output the data to a simple html table...
echo "<!DOCTYPE html>\n";
echo "<html lang=\"en\">\n";
echo "<body bgcolor = \"#C7CFCA\" text = \"black\">\n";
echo "<center>";
echo "<p>Record ID is <?php echo $record ?>.</p>";
echo "<table>\n";
echo "<h2>Update a Record</h2>";
echo "<tr><th><u><h3>ID</th><th><u><h3>Last Name</th><th><u><h3>First Name</th>";
echo "<th><u><h3>Middle Name</th><th><u><h3>Section</th>";
echo "<th><u><h3>Lot</th><th><u><h3>Plot</th><th><u><h3>Burial Date</th><th><u><h3>Veteran</th></tr>\n";
$results = $db->query('SELECT id,last_name,first_name,middle_initial,section,lot,plot,burial_date,veteran FROM burials WHERE id = $record');
while ($row = $results->fetchArray()) {
echo "<tr><td><center><h3>" . $row['id'] . "</td><td><center><h3>" . $row['last_name'] . "</td><td><center><h3>" .
$row['first_name'] . "</td><td><center><h3>" . $row['middle_initial'] . "</td><td><center><h3>" .
$row['section'] . "</td><td><center><h3>" . $row['lot'] . "</td><td><center><h3>" . $row['plot'] . "</td><td><center><h3>" . $row['burial_date'] . "</td><td><center><h3>" . $row['veteran'] . "</td></tr>\n";
}
echo "</table>\n";
echo "<p>Record ID is <?php echo $record ?>.</p>";
echo "<label for=\"sql\"><h3>What do you want to update? </label>";
echo "<select id=\"option\">";
echo "<h3><option value=\"last_name\"><h3>Last Name</option>";
echo "<option value=\"fist_name\"><h3>First Name</option>";
echo "<option value=\"middle_initial\"><h3>Middle Name</option>";
echo "<option value=\"section\"><h3>Section</option>";
echo "<option value=\"lot\"><h3>Lot</option>";
echo "<option value=\"plot\"><h3>Plot</option>";
echo "<option value=\"burial_date\"><h3>Burial Date</option>";
echo "<option value=\"veteran\"><h3>Veteran Status</option>";
echo "</select>";
echo "<h2><input style=\"font-size:15px\" type=\"text\" name=\"opt\" size=\"30\">";
echo "</body>\n";
echo "</html>";
}
?>
When I put, say, 1 as the record id in the form, nothing is outputted. I'm new to this and would definitely appreciate some pointers/tips.
To prevent a SQL injection attack, you should consider using the prepare/bind/execute pattern. Use example 1 in the SQLITE3::prepare doc as a guide.
Regarding the problem at hand: From the PHP: Strings doc:
When a string is specified in double quotes or with heredoc, variables
are parsed within it.
Since the SQL query is enclosed in single-quotes ('), the $record variable is not parsed. In other words, what you see is what is being sent to the database, thus no rows are returned.

Stop Adding Duplicate Entries to Database PHP SQLITE

I have created a PHP form which adds to a database that I have created in PHP, however, I am trying to add a function which will stop the user from adding the same fruit into the database how would I try to do this as I have been trying to do it for a while thanks.
As you can see below the PHP script works fine by adding the variable's to the database however when it comes to implementing a check to make sure the fruit name does not match one from the database already I am struggling.
<?php
//SQLite Database test query
$db=sqlite_open("fruitshop.db");
if(isset( $_POST['fruit']) && strcmp($_POST['fruit'],"") != 0 ){ //Adds to Database
$item = sqlite_escape_string($_POST["fruit"]);
$number=$_POST['number'];
sqlite_query($db,"INSERT INTO fruit (fruit) VALUES ('$item')");
sqlite_query($db,"INSERT INTO stock (Number) VALUES ($number)");
$query = "SELECT * from stock, fruit WHERE stock.Item = fruit.id AND fruit.fruit = '$item', 'fruit' = '{$item}'";
$result=sqlite_query($db, $query);
echo "<table border=1>";
echo "<tr><th>Fruit</th><th>Qty</th>";
echo "<h2>". "Newly added Fruit"."</h2>";
while($row=sqlite_fetch_array($result,SQLITE_ASSOC ))
{
echo "<tr>";
echo "<td>" . $row['fruit.fruit'] . "</td><td>" . $row['stock.Number'] . "</td>";
echo "</tr>";
}
echo "</table>";
echo "<h2>". "Show All Fruits"."</h2>";
echo "<table border=1>\n";
//NOte the use of SQLITE_ASSOC
echo "</br>\n";
$result=sqlite_query($db,"SELECT * from stock, fruit WHERE stock.Item = fruit.ID"); //Shows Databse
echo "<th>Fruit</th><th>Qty</th>\n";
while($row=sqlite_fetch_array($result,SQLITE_ASSOC))
{
echo "<tr>\n";
echo "<td>" . $row['fruit.fruit'] . "</td>\n";
echo "<td>" . $row['stock.Number'] . "</td>\n";
echo "</tr>\n";
}
echo "</table>\n";
}
sqlite_close($db);
?>
<html>
<h2> Add Fruits to Database </h2>
<form name="CheckFruit" action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post">
Fruit
<input type="text" name="fruit" />
<br>
Stock
<input type="number" name="number" />
<br>
<input type="submit" value="Submit" />
</form>
</html>
You can use my updated code. Didn't get to try the code though but it should work. Also note how I used empty instead of strcmp. That's a more elegant PHP code.
<?php
//SQLite Database test query
$db=sqlite_open("fruitshop.db");
if(isset( $_POST['fruit']) && !empty($_POST['fruit']) ){ //Adds to Database
$item = sqlite_escape_string($_POST["fruit"]);
$number = $_POST['number'];
$test = sqlite_query($db, "SELECT * FROM fruit WHERE (fruit = '$item')");
if(sqlite_num_rows($test) == 0){
sqlite_query($db,"INSERT INTO fruit (fruit) VALUES ('$item')");
sqlite_query($db,"INSERT INTO stock (Number) VALUES ($number)");
} else {
// Just in case you want this too.
// echo "This database already contains a fruit called {$_POST['fruit]'}";
}
$query = "SELECT * from stock, fruit WHERE stock.Item = fruit.id AND fruit.fruit = '$item', 'fruit' = '{$item}'";
$result=sqlite_query($db, $query);
echo "<table border=1>";
echo "<tr><th>Fruit</th><th>Qty</th>";
echo "<h2>". "Newly added Fruit"."</h2>";
while($row=sqlite_fetch_array($result,SQLITE_ASSOC ))
{
echo "<tr>";
echo "<td>" . $row['fruit.fruit'] . "</td><td>" . $row['stock.Number'] . "</td>";
echo "</tr>";
}
echo "</table>";
echo "<h2>". "Show All Fruits"."</h2>";
echo "<table border=1>\n";
//NOte the use of SQLITE_ASSOC
echo "</br>\n";
$result=sqlite_query($db,"SELECT * from stock, fruit WHERE stock.Item = fruit.ID"); //Shows Databse
echo "<th>Fruit</th><th>Qty</th>\n";
while($row=sqlite_fetch_array($result,SQLITE_ASSOC))
{
echo "<tr>\n";
echo "<td>" . $row['fruit.fruit'] . "</td>\n";
echo "<td>" . $row['stock.Number'] . "</td>\n";
echo "</tr>\n";
}
echo "</table>\n";
}
sqlite_close($db);
?>
<html>
<h2> Add Fruits to Database </h2>
<form name="CheckFruit" action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post">
Fruit
<input type="text" name="fruit" />
<br>
Stock
<input type="number" name="number" />
<br>
<input type="submit" value="Submit" />
</form>
</html>
You could declare the fruit column as UNIQUE in your column schema, so the database will reject a duplicate value without further controls on your side.
If instead you want to check if the value is already present in your PHP code, you can do a query for that value and check if rows are returned. If rows are returned, a value is already present and you can handle that situation before doing your inserts
$query = "SELECT * from fruit WHERE fruit.fruit = '$item', 'fruit' = '{$item}'";
$result=sqlite_query($db, $query);
if (sqlite_num_rows($result) === 0) {
sqlite_query($db,"INSERT INTO fruit (fruit) VALUES ('$item')");
sqlite_query($db,"INSERT INTO stock (Number) VALUES ($number)");
} else {
// Value is already present
}
Note: I've never used SQLITE, so i hope the syntax is correct

Cant seem to EDIT/MODIFY my php table by id

<?php
$con = mysql_connect("localhost","root");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("database", $con);
if(!isset($_POST['submit'])){
$result = mysql_query("SELECT * FROM pleasework ORDER BY ID");
$row = mysql_fetch_array($result);
}
?>
<form action="?php echo $_SERVER['PHP_SELF'];?>" id="form2" method="post" name="form2">
<img id="close1" src="X.png" width="25" height="25" onclick ="div_hide1()">
<h2><font size="6">Please change existing data</font></h2>
<hr>
<br>
<font color="yellow">Change Name to: </font><input type="text" name="New" value="<?php echo $row['Name'];?>"/><br><br>
<font color="yellow"> Change Cause to: </font> <input type="text" name="New1" value="<?php echo $row['Cause'];?>"/><br><br>
<font color="yellow">Change Symptom to: </font><input type="text" name="New2" value="<?php echo $row['Symptom'];?>"/><br><br>
<font color="yellow"> Change Gene_affected to: </font><input type="text" name="New3"value="<?php echo $row['Gene_affected'];?>" /><br><br>
<input type="hidden" name="id" value="<?php echo $_GET['ID'];?>"/>
<input type="submit" onclick="clicked(event)" />
</form>
<?php
if(isset($_POST['submit'])){
mysql_query("UPDATE pleasework SET Name= '$_POST[New]' WHERE ID='$_POST[id]'");
mysql_query("UPDATE pleasework SET Cause= '$_POST[New1]' WHERE ID='$_POST[id]'");
mysql_query("UPDATE pleasework SET Symptom= '$_POST[New2]' WHERE ID='$_POST[id]'");
mysql_query("UPDATE pleasework SET Gene_affected= '$_POST[New3]' WHERE ID='$_POST[id]'");
echo "Change Successful<br>" ;
header("Location: databse.php");
mysql_close($con);
}
else {}
?>
This is my php file.
while($row = mysql_fetch_array($result))
{
echo "<TR>";
echo "<TD>" . $row['ID'] ."</TD>";
echo "<TD>" . $row['Name'] . " </TD>";
echo "<TD>" . $row['Cause'] . " </TD>";
echo "<TD>" . $row['Symptom']. " </TD>";
echo "<TD>" . $row['Gene_affected'] . " </TD>";
echo "<TD><font color='red'>Delete row</font> </TD>";
echo "<TD><font color='red'>modify</font> </TD>";
echo "</TR>";
}
And this is the section which has a modify button that links to the edit.php file. The error here is that is doesnt bring over the values in the table to the editing page and then submitting the form doesnt work too. help please
Your code appears a bit confused.
First of all, why to put the modify routine after output the form? Especially since after modify you send the header function, that fails if previously there are some output.
Note also a typo: you forgot to properly open the php tag in the form declaration. Change-it in this way:
<form action="<?php echo $_SERVER['PHP_SELF'];?>" id="form2" method="post" name="form2">
The main problem is that you check if the $_POST[submit] if set, but this is not set, due to the absence of attribute name.
Change it in this way:
<input type="submit" name="submit" onclick="clicked(event)" />
Now your script should work (I don't have tested the sql).
Please also note that your UPDATE routine is redundant: you can reduce the 4 statement to only one in this way:
$result = mysql_query
(
"UPDATE pleasework SET Name='{$_POST[New]}', Cause='{$_POST[New1]}', Symptom='{$_POST[New2]}', Gene_affected='{$_POST[New3]}' WHERE ID={$_POST[id]}"
);
About PHP Original MySQL API:
This extension is deprecated as of PHP 5.5.0, and has been removed as of PHP 7.0.0
NOTE: mysql_* deprecated, so try to use PDO or mysqli_*.
Simple way:
<?php
if(isset($_POST['submit'])){
$result = mysql_query("UPDATE pleasework
SET Name='".$_POST['New']."',
Cause='".$_POST['New1']."',
Symptom='".$_POST['New2']."',
Gene_affected='".$_POST['New3']."'
WHERE ID=".$_POST['id'].");
if($result ){
echo "Change Successful<br>" ;
header("Location: databse.php");
}
mysql_close($con);
}
YOUR PHP:
while($row = mysql_fetch_array($result))
{ $spaces = " ";
echo "<TR>";
echo "<TD>" . $row['ID'] ."</TD>";
echo "<TD>" . $row['Name'] . $spaces."</TD>";
echo "<TD>" . $row['Cause'] . $spaces."</TD>";
echo "<TD>" . $row['Symptom']. $spaces."</TD>";
echo "<TD>" . $row['Gene_affected'] . $spaces."</TD>";
echo "<TD><a href='delete.php?id=".$row['ID'] ."'>";
echo "<font color='red'>Delete row</font></a>".$spaces."</TD>";
echo "<TD><a href='edit.php?id=" . $row['ID'] ."'>";
echo "<font color='red'>modify</font></a>".$spaces."</TD>";
echo "</TR>";
}

Sending bcc emails only for selected checkbox values

I am trying to send the same email only to selected users. I am printing values from table and want to select specific users to send an email.
<form name="unos" action="mail-proizvodi.php" method="post">
<?
echo "<table border='5'>
<tr>
<th> </th>
<th>ID</th>
<th>NAZIV</th>
<th>ADRESA</th>
<th>DRZAVA</th>
<th>GRAD</th>
<th>EMAIL</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo '<td><input type="checkbox" name="email[]" value="' . $row['ID'] . '"></td>';
echo "<td>" . $row['ID'] . "</td>";
echo "<td>" . $row['NAZIV'] . "</td>";
echo "<td>" . $row['ADRESA'] . "</td>";
echo "<td>" . $row['DRZAVA'] . "</td>";
echo "<td>" . $row['GRAD'] . "</td>";
echo "<td>" . $row['EMAIL'] . "</td>";
echo "</tr>";
}
echo "</table>";
?>
<input type="submit" name="submit" value="submit">
</form>
my mail-proizvodi.php code
$mail=$_POST['email'];
echo "Dzenad catic";
$query= "SELECT `EMAIL` FROM `clanovi` WHERE ID='$mail[0]'";
if(sizeof($mail)>1)
{
for($i=1; $i<sizeof($mail); $i++)
{
$query.=" OR ID = '$mail[$i]' ";
}
}
$result=mysqli_query($con,$query);
while(FALSE!==($row=mysqli_fetch_row($result))) {
$bccfields[] = $row['EMAIL'];
}
echo sprintf("<a href=mailto:test#test.ba?bcc=%s />\n",
urlencode(implode(',',$bccfields)));
echo "Send" ;
Post I am receiving is an array. And when I do var_dump($mail) I get
array
0 => string '20' (length=2)
1 => string '30' (length=2)
Any help or advice is appreciated. Thanks in advance.
I am posting solution for the problem I had in case someone else face similar mistake.
$mail=$_POST['email'];
$query= "SELECT `EMAIL` FROM `clanovi` WHERE ID ='$mail[0]'";
if(sizeof($mail)>1)
{
for($i=1; $i<sizeof($mail); $i++)
{
$query.=" OR ID = '$mail[$i]' ";
}
}
$result=mysql_query($query);
if (!$result) {
echo "Could not successfully run query ($query) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
while(FALSE!==($row=mysql_fetch_assoc($result))) {
$bccfields[] = $row['EMAIL'];
}
echo sprintf("<a href=mailto:prodaja#alternativa.ba?bcc=%s />\n",
urlencode(implode(',',$bccfields)));
echo "Send" ;
mysql_free_result($result);

How to get data from mysql database?

I am having problem in getting values from db. Iam new in php
I am using checkboxes to get values from database. Only checked values should be printed.
<form method="POST" action="gradoviexport.php" id="searchform">
<div id="GRADOVI BIH">
<h3>GRADOVI BOSNE I HERCEGOVINE</h3><hr/>
<input type="checkbox" name="gradovi[]" value="sarajevo"> Sarajevo
<input type="checkbox" name="gradovi[]" value="banovici"> Banovići
<input type="checkbox" name="gradovi[]" value="banjaluka"> Banja Luka
<input type="checkbox" name="gradovi[]" value="bihac"> Bihać
<input type="checkbox" name="gradovi[]" value="bileca"> Bileća
</div>
<div id="snimi">
<input type="submit" name="submit" value="EXPORT">
</div>
</form>
If Sarajevo is checked I want to print values from database. It does not have to be only one value checked If all values are checked it should print all values.
$con=mysqli_connect("$host","$username","$password", "$database");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//connecting to db
$variable=$_POST['grad'];
foreach ($variable as $variablename)
{
$sql_select="SELECT * FROM `clanovi` WHERE `GRAD` = $variablename " ;
$queryRes = mysql_query($sql_select);
print"$sql_select";
}
echo "<table border='5'>
<tr>
<th>IME</th>
<th>PREZIME</th>
<th>FIRMA</th>
<th>ADRESA</th>
<th>TELEFON</th>
<th>FAX</th>
<th>MOBITEL</th>
<th>EMAIL </th>
<th>WEB_STRANICA </th>
<th>GRAD </th>
<th>KATEGORIJA </th>
</tr>";
while($row = mysqli_fetch_array($queryRes))
{
echo "<tr>";
echo "<td>" . $row['IME'] . "</td>";
echo "<td>" . $row['PREZIME'] . "</td>";
echo "<td>" . $row['FIRMA'] . "</td>";
echo "<td>" . $row['ADRESA'] . "</td>";
echo "<td>" . $row['TELEFON'] . "</td>";
echo "<td>" . $row['FAX'] . "</td>";
echo "<td>" . $row['MOBITEL'] . "</td>";
echo "<td>" . $row['EMAIL'] . "</td>";
echo "<td>" . $row['WEB_STRANICA'] . "</td>";
echo "<td>" . $row['GRAD'] . "</td>";
echo "<td>" . $row['KATEGORIJA'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
Assume you posted gradovi[] array values to submitted page.
Submit page:
$grad = array();
$grad = $_POST['gradovi']; //get array value
$grad = implode(',',$grad); //convert it into comma separated string
//Insert it into data base
Getting from database:
//fetch the gradovi field from the db like below
echo $row['gradovi']; // print all values
or
$grad = explode(',',$row['gradovi']);
foreach($grad as $check) {
echo $check; //print one by one
}
There is few errors in your code.
There is no escaping of the string from POST data. Use mysqli_real_escape_string
There is an error in your while loop. You redefining mysql query result.
Fixed code:
//connecting to db
$variable=$_POST['grad'];
foreach($variable as $key => $val) {
$variable[$key] = mysql_escape_string($val);
}
$sql_select="SELECT * FROM `clanovi` WHERE `GRAD` IN ('" . implode("','", $variable) . "')" ;
$queryRes = mysql_query($sql_select);
print"$sql_select";

Categories