More than one htmlspecialchars string in PHP MySQL - php

I have a table in MySQL where there is a row with this data.
id = 187
friendly name = i don't like mustard
filetype = exe
This first block of code below works perfectly, and echos text i don't like mustard into an HTML form. Similarly, if I change $row['friendlyname'] to $row['filetype'], text exe is echoed. All good, no issues yet.
<?php
$con = mysqli_connect('domain','user','pass','db');
$sql = "select * from installers where id=187";
$result = mysqli_query($con,$sql);
while($row=mysqli_fetch_array($result))
$friendlyname = htmlspecialchars(" ".$row['friendlyname']." ",ENT_QUOTES);
$con->close();
?>
<input type='text' value='<?php echo $friendlyname; ?>'>
The problem I'm having is if I try to echo both $row['friendlyname'] and $row['filetype'], only the variable that is listed first will be echoed. For example, in the below code, $row['friendlyname'] is listed before $row['filetype']. In this example, only $row['friendlyname'] (i don't like mustard) will be echoed. Similarly, if $row['filetype'] is listed before $row['friendlyname'], then only $row['filetype'] (exe) is echoed, and the second other HTML input form is empty.
<?php
$con = mysqli_connect('domain','user','pass','db');
$sql = "select * from installers where id=187";
$result = mysqli_query($con,$sql);
while($row=mysqli_fetch_array($result))
$friendlyname = htmlspecialchars(" ".$row['friendlyname']." ",ENT_QUOTES);
$filetype= htmlspecialchars(" ".$row['filetype']." ",ENT_QUOTES);
$con->close();
?>
<input type='text' value='<?php echo $friendlyname; ?>'>
<input type='text' value='<?php echo $filetype; ?>'>
Note 1: It doesn't matter the order of the input type forms. I ruled that out as the issue.
Note 2: If I were to replace $row['friendlyname'] and $row['filetype'] with the text I'm trying to echo, then it work (the below code). So, this definitely appears to be something with these $row variables.
<?php
$con = mysqli_connect('domain','user','pass','db');
$sql = "select * from installers where id=187";
$result = mysqli_query($con,$sql);
while($row=mysqli_fetch_array($result))
$friendlyname = i don't like mustard;
$filetype= exe;
$con->close();
?>
<input type='text' value='<?php echo $friendlyname; ?>'>
<input type='text' value='<?php echo $filetype; ?>'>

You have not added brackets into while loop so only first record is populated.
This block:
while($row=mysqli_fetch_array($result))
$friendlyname = htmlspecialchars(" ".$row['friendlyname']." ",ENT_QUOTES);
$filetype= htmlspecialchars(" ".$row['filetype']." ",ENT_QUOTES);
Should be:
while($row=mysqli_fetch_array($result)){
$friendlyname = htmlspecialchars(" ".$row['friendlyname']." ",ENT_QUOTES);
$filetype= htmlspecialchars(" ".$row['filetype']." ",ENT_QUOTES);
}

Related

Displaying multiple mysql row results in single textbox in array format separated in comma

Hi I have tried to select mysqli results from a table row for phone numbers but it produces many textboxes instead of only one. Please I need your help, I'll be grateful. My code is as below:
<form method="post">
<?php
$connect = mysqli_connect("localhost", "root", "", "hrm");
$query = "SELECT * FROM tbl_employee";
$result = mysqli_query($connect, $query);
while($row = mysqli_fetch_array($result))
{
?>
<input type='text' name='phone' class='form-control' placeholder='Enter recipients' value='<?php echo $row['phone']; ?>' />
<?php
}
?>
</form>
try like this in php alone i used while inside value attr.
printing ',' will produce extra one in the last which will help to type new number
<form method="post">
<?php
$connect = mysqli_connect("localhost", "root", "", "hrm");
$query = "SELECT * FROM tbl_employee";
$result = mysqli_query($connect, $query); ?>
<input type='text' name='phone' class='form-control' placeholder='Enter recipients'
value='<?php
while($row = mysqli_fetch_array($result)){
echo $row['phone'].",";
}
?>'
/>
</form>

Retrieve more than 3 data's from mysql into checkbox

I need to retrieve the hobbies name from mysql and display it in check boxes. I done the below given code. But it displays just check box and not any hobby names. Please help.
$query = "SELECT * FROM hobbies";
$result = mysqli_query($con, "$query");
while ($r=mysqli_fetch_array($result))
{
$hobby=$r["hobby_name"];?>
<input type='checkbox' name='check[]' value='$hobby'>
}
You need to add simple text $hobby next to every checkbox.
Corrected code:
$query = "SELECT * FROM hobbies";
$result = mysqli_query($con, "$query");
while ($r=mysqli_fetch_array($result)) {
$hobby=$r["hobby_name"];
?>
<input type='checkbox' name='check[]' value='<?php echo $hobby;?>'> <?php echo $hobby;?>
<?php
}
Checkbox input itself does not display any text. You need to show both checkbox and text separately like this:
<input type='checkbox' name='check[]' value='$hobby'><label>$hobby</label>
Try this:
<?php
$query = "SELECT * FROM hobbies";
$result = mysqli_query($con, "$query");
while ($r=mysqli_fetch_array($result))
{
$hobby=$r["hobby_name"];
echo "<input type='checkbox' name='check[]' value='".$hobby."'><label>".$hobby."</label>";
}
?>

MySQL search enquiry error

I am trying to create a form which allows the user to search for an event using the Venue and category fields which are scripted as dropdown boxes and the Price and finally by event title, as shown via the code if a keyword is entered which matches the fields on the database it should output all the related information for that event if any matches have been made on either search fields, but it seems to output every single event from the database no matter what I type in the search field.
DATABASE: http://i.imgur.com/d4uoXtE.jpg
HTML FORM
<form name="searchform" action ="PHP/searchfunction.php" method = "post" >
<h2>Event Search:</h2>
Use the Check Boxes to indicate which fields you watch to search with
<br /><br />
<h2>Search by Venue:</h2>
<?php
echo "<select name = 'venueName'>";
$queryresult2 = mysql_query($sql2) or die (mysql_error());
while ($row = mysql_fetch_assoc($queryresult2)) {
echo "\n";
$venueID = $row['venueID'];
$venueName = $row['venueName'];
echo "<option value = '$venueID'";
echo ">$venueName</option>";
}# when the option selected matches the queryresult it will echo this
echo "</select>";
mysql_free_result($queryresult2);
mysql_close($conn);
?>
<input type="checkbox" name="S_venueName">
<br /><br />
<h2>Search by Category:</h2>
<?php
include 'PHP/database_conn.php';
$sql3 ="SELECT catID, catDesc
FROM te_category";
echo "<select name = 'catdesc'>";
$queryresult3 = mysql_query($sql3) or die (mysql_error());
while ($row = mysql_fetch_assoc($queryresult3)) {
echo "\n";
$catID = $row['catID'];
$catDesc = $row['catDesc'];
echo "<option value = '$catID'";
echo ">$catDesc </option>";
}
echo "</select>";
mysql_free_result($queryresult3);
mysql_close($conn);
?>
<input type="checkbox" name="S_catDes">
<br /><br />
<h2>Search By Price</h2>
<input type="text" name="S_price" />
<input type="checkbox" name="S_CheckPrice">
<br /><br />
<h2>Search By Event title</h2>
<input type="text" name="S_EventT" />
<input type="checkbox" name="S_EventTitle">
<br /><br />
<input name="update" type="submit" id="update" value="Search">
searchfunction.php file
<?php
$count = 0;
include 'database_conn.php';
$venuename = $_REQUEST['venueName']; //this is an integer
$catdesc = $_REQUEST['catdesc']; //this is a string
$Price = $_REQUEST['S_price'];
$EventT = $_REQUEST['S_EventT'];
$sql = "select * FROM te_events WHERE venueID LIKE '%$venuename%' OR catID LIKE '%$catdesc%' OR eventPrice LIKE '%Price%' OR eventTitle LIKE '%$EventT%'";
$queryresult = mysql_query($sql) or die (mysql_error());
while ($row = mysql_fetch_assoc($queryresult))
{
echo $row['eventTitle'];
echo $row['eventDescription'];
echo $row['venueID'];
echo $row['catID'];
echo $row['eventStartDate'];
echo $row['eventEndDate'];
echo $row['eventPrice'];
}
mysql_free_result($queryresult);
mysql_close($conn);
?>
The query should be
$sql = "select * FROM te_events
WHERE (venueID LIKE '%$venuename%'
OR catID LIKE '%$catdesc%'
OR eventPrice LIKE '%$Price%'
OR eventTitle LIKE '%$EventT%')
;
To get values from the form submitted with method POST we use $_POST to access form data and not $_REQUEST:
$venuename = $_POST['venueName']; //this is an integer
$catdesc = $_POST['catdesc']; //this is a string
$Price = $_POST['S_price'];
$EventT = $_POST['S_EventT'];
That was about your problem - now some important notes:
Do not use mysql extension as it's deprecated. Read this official documentation.
Use mysqli and prevent SQL injections by using prepared queries and parameters like in official documentation again.
Since you are matching on any fields surrounded by wildcards, if any of the fields are blank, then the MySQL query will match all rows.
Also, you need to prevent MySQL injection. Otherwise, your MySQL table will eventually be hacked.
By the way, the code eventPrice LIKE '%Price%' is invalid and is missing a dollar sign.
Lastly, the mysql extension has been deprecated. I would recommend using mysqli instead as it is fairly similar.

PHP: Query was empty when searching

I need a little help for my problem...
Scene: I was trying to search something in my database but the result is "Query was empty" but the one I'm trying to search is already in my database. I'm trying to search the "Atrium Hotel"
Here's my screenshot of my Database:
Here's my screenshot of my result Page:
And Lastly here's my code:
<input type='submit' name='search' value='Search Building' onClick="this.form.action='search_bldg.php'; this.form.submit()">
<input type="text" id="idSearch"name="searchBldg" size="40" value="<?php echo $_POST['searchBldg']; ?>">
<fieldset width= "50px">
<legend>BUILDING/S</legend>
<?php
$search = $_POST["searchBldg"];
$data = mysql_query("SELECT * FROM tbldata WHERE fldBldgName LIKE '%$search%'");
$result = mysql_query($data) or die(mysql_error());
while($row = mysql_fetch_array( $result ))
{
echo $row['fldBldgName'];
}
?>
</fieldset>
I was wondering what is the problem in my query...
Thanks in advance...
You are executing your query twice (Line #7 and #8). That may be the problem. Try something like this:
<input type='submit' name='search' value='Search Building' onClick="this.form.action='search_bldg.php'; this.form.submit()">
<input type="text" id="idSearch"name="searchBldg" size="40" value="<?php echo $_POST['searchBldg']; ?>">
<fieldset width= "50px">
<legend>BUILDING/S</legend>
<?php
$search = $_POST["searchBldg"];
$query= "SELECT * FROM tbldata WHERE fldBldgName LIKE '%$search%'"; //Your sql
$result = mysql_query($query) or die(mysql_error()); //execute your query
while($row = mysql_fetch_array( $result ))
{
echo $row['fldBldgName'];
}
?>
</fieldset>
P.S. use mysqli_* or PDO instead of mysql_* since it is deprecated as of PHP 5.4
You should use mysqli or PDO since mysql_* is depreciated.
Try the below code: It's using mysqli . It should be working...
<?php
$search = $_POST["searchBldg"];
//connecting to db...mysqli_connect("example.com","peter","abc123","my_db")
$con=mysqli_connect(host,username,password,dbname);
//searching...
$query= "SELECT * FROM tbldata WHERE fldBldgName LIKE '%$search%'";
//execute the query
$result = mysqli_query($query) or die(mysqli_error());
while($row = mysqli_fetch_array( $result ))
{
echo $row['fldBldgName'];
}
mysqli_close($con);
?>
There are some issues in your code that I'll demonstrate by commenting your code:
<input type='submit' name='search' value='Search Building' action='search_bldg.php' onClick="this.form.submit();"> <!-- setting action-attribute directly in form-tag, no need to use js for that -->
<input type="text" id="idSearch" name="searchBldg" size="40" value="<?php echo $_POST['searchBldg']; ?>"> <!-- added a space between id="search" and name-attribute -->
<fieldset width= "50px">
<legend>BUILDING/S</legend>
<?php
$search = $_POST["searchBldg"];
$data = "SELECT * FROM tbldata WHERE fldBldgName LIKE '%$search%'"; //mysql_query is removed, because the actual query is executed below
$result = mysql_query($data) or die(mysql_error());
while($row = mysql_fetch_assoc( $result )) //mysql_fetch_array doesn't return associative arrays, therefore it's replaced with mysql_fetch_assoc
{
echo $row['fldBldgName'];
}
?>
</fieldset>
You should of course sanitize data (so not unwanted data gets inserted into db) and use something else besides mysql_* as stated in previous answers.
Another issue (which is not really a problem) is the name of elements, column-names etc. searchBldg is very similar to searchB1dg and it might be easy to do typing-errors which might be hard to find.

Update echoed data using WHILE loop. Only updates one record

I can't seem to be able to update any records except the first one.
I am not sure how to modify any of the displayed records.
<?php
if(isset($_POST["action"]) == "update")
{
$id = $_POST['m_id'][0];
$type = $_POST['type'][0];
// if I echo $id & $type, it only gives me the first record.**
mysql_query("
UPDATE membership_type
SET mt_type ='$type'
WHERE mt_id = '$id'"
);
}
?>
ALl of this is within the same php page.
<form name=form action='' method='post'>
<?php
$result=mysql_query("SELECT * FROM membership_type;");
while($rows=mysql_fetch_array($result))
{ ?>
<input size=35 class=textField type=text name='type[]' value='<?php echo $rows['mt_type']; ?>'>
<input type=hidden name='m_id[]' value="<?php echo $rows['mt_id']; ?>">
<input type=submit value="Update">
<?php
}
?>
How do I edit any of the displayed records by simply clicking Update button???
First: You should NEVER use the mysql_* functions as they are deprecated.
Second: Try this code:
<?php
// Get a connection to the database
$mysqli = new mysqli('host', 'user', 'password', 'database');
// Check if there's POST request in this file
if($_POST){
foreach($_POST['m_id'] as $id => $type){
$query = "UPDATE membership_type
SET mt_type = '".$type."'
WHERE mt_id = '".$id."'";
// Try to exec the query
$mysqli->query($query) or die($mysqli->error);
}
}else{
// Get all membership_type records and then iterate
$result = $mysqli->query("SELECT * FROM membership_type") or die($mysqli->error); ?>
<form name='form' action='<?php echo $_SERVER['PHP_SELF'] ?>' method='post'>
<?php while($row = $result->fetch_object()){ ?>
<input size='35'
class='textField'
type='text'
name='m_id[<?php echo $row->mt_id ?>]'
value='<?php echo $row->mt_type; ?>'>
<input type='submit' value="Update">
<?php } ?>
</form>
<?php } ?>
Third: In order to add more security (this code is vulnerable), try mysqli_prepare
Only the first record is updated on every form submission because you have set $id = $_POST['m_id'][0], which contains the value of the first type[] textbox. To update all the other records as well, loop through $_POST['m_id'].
Replace it. Hope this works.
<?php
if(isset($_POST["action"]) == "update")
{
$id = $_POST['m_id'];
$type = $_POST['type'];
$i = 0;
foreach($id as $mid) {
mysql_query("UPDATE membership_type
SET mt_type='".mysql_real_escape_string($type[$i])."'
WHERE mt_id = '".intval($mid)."'") OR mysql_error();
$i++;
}
}
?>
Try this :
if(isset($_POST["action"]) == "update")
{
$id = $_POST['m_id'];
$type = $_POST['type'];
$loopcount = count($id);
for($i=0; $i<$loopcount; $i++)
{
mysql_query("
UPDATE membership_type
SET mt_type ='$type[$i]'
WHERE mt_id = '$id[$i]'"
);
}
}
You HTML was malformed and you were passing as an array but then only using the first element. Consider:
<form name="form" action="" method="post">
<?php
$result = mysql_query("SELECT * FROM membership_type;");
while($row = mysql_fetch_array($result))
echo sprintf('<input size="35" class="textField" type="text" name="m_ids[%s]" value="%s" />', $row['mt_id'], $row['mt_type']);
?>
<input type="submit" value="Update">
</form>
Then the server script:
<?php
if(isset($_POST["action"]) && $_POST["action"] == "Update"){
foreach($_POST['m_ids'] as $mt_id => $mt_type)
mysql_query(sprintf("UPDATE membership_type SET mt_type ='%s' WHERE mt_id = %s LIMIT 1", addslashes($mt_type), (int) $mt_id));
}
There are other things you could be doing here, eg. prepared statements, but this should work.

Categories