How to get data from mysql database? - php

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";

Related

Not able to retrieve results from database in php/mysql

I am using simple code to retrieve data from database table but not getting result it always shows "No Result found".
Table Structure
rollno Varchar(50) Primary Key,
name Varchar(100),
fname Varchar(100),
mname Varchar(100),
course Varchar(100),
duration Varchar(100),
address Varchar(100),
image blob.
HTML FORM CODE
<form name="input" action="q.php" target="display" method="post" >
Roll No: <input type="text" name="name">
<input type="submit" name="submit" value="Submit">
</form>
PHP CODE
<?php
if (isset($_POST['name'])) {
$con=mysqli_connect("mysql.1freehosting.com","u890130056_certi","samsungk2","u890130056_certi");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$name = htmlspecialchars($_POST['rollno']);
{
$result = mysqli_query($con,"SELECT * FROM certificate where rollno ='$name'");
if(mysqli_num_rows($result)>0){
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['rollno'] . "</td>";
echo "<td>" . $row['course'] . "</td>";
echo "<td>" . $row['duration'] . "</td>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['fname'] . "</td>";
echo "<td>" . $row['mname'] . "</td>";
echo "<td>" . $row['address'] . "</td>";
echo "<td>";?><img src="<?php echo $row["image"]; ?> " height="100" width="100"> <?php echo "</td>";
echo "</tr>";
}
}
else
{
echo "<tr><td colspan='4'> No Data Found , Please check your registration no. or contact the institute for clarification. ".$line.'</td></tr>';
}
mysqli_close($con);
}}
?>
name = htmlspecialchars($_POST['rollno']);
where are you getting this 'rollno??
i dont get why are you saving the result by posting['rollno'] because the name of your feild is 'name'.
change this line
$name = htmlspecialchars($_POST['rollno']);
to
$name = htmlspecialchars($_POST['name']);

My delete button is not functioning as expected

I'm stuck in the delete function, I wonder why my delete button is not functioning, and I already edited my code.
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$semester = ($_POST["semester"]);
$level = ($_POST["level"]);
}
?>
Here is the form method:
<form method="post" action="<?php echo($_SERVER["PHP_SELF"]);?>" enctype="multipart/form-data">
Here is to display the data in table form, and SELECT * is functioning
$sql = mysqli_query ($connection, "SELECT * FROM subject");
echo " <table>
<th>Semester</th>
<th>Level</th>
</tr>";
while($record = mysqli_fetch_assoc ($sql)){
echo "<tr>";
echo "<td>" . $record['semester'] . "</td>";
echo "<td>" . $record['level'] . "</td>";
echo "<td>" . "<input type=submit name=delete value=Delete>" . "</td>";
echo "</tr>";
}
This is the delete button code
if (isset($_POST['delete']))
{
$delete = mysqli_query ($connection, "DELETE FROM subject WHERE semester = '($_POST[semester])'");
}
Try this :
while($record = mysqli_fetch_assoc ($sql)){
echo "<tr>";
echo '<form action="mypage.php" method="post">';
echo "<td>" . $record['semester'] . "</td>";
echo "<td>" . $record['level'] . "</td>";
echo "<td>" . $record['course'] . "</td>";
echo "<td>" . $record['subject'] . "</td>";
echo "<td>" . $record['section'] . "</td>";
// And add field form hidden
echo '<input type="hidden" name="semester" value="'.$record['semester'].'">';
echo "<td>" . '<input type="submit" name="delete" value="Delete">' . "</td>";
echo "</form>";
echo "</tr>";
}
if (isset($_POST['delete']) && isset($_POST['semester']))
{
$stmt = $connection->prepare('DELETE FROM subject WHERE semester = ?');
// if $_POST['semester'] is integer else see http://php.net/manual/en/mysqli-stmt.bind-param.php
$stmt->bind_param('i', $_POST['semester']);
$stmt->execute();
}

Utilize user input in SQL query

I'm trying to update a table given user input. Once the user hits submit on the form, I want the WHERE portion of my query to reflect the zip code entered by the user. Here is what I have so far, but it doesn't work. Any help would be greatly appreciated!
<form id="user-location" method="post" action="#">
<input id="addressInput" name="addressInput" type="text">
<input id="submit" onclick="searchLocations()" value="GO" type="button">
</form>
<?php
$con=mysqli_connect("localhost","######","######","######");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM Prospects WHERE zip = 'echo $_POST['addressInput']'");
echo "<table width='540' cellpadding='0' border='0' cellspacing='0'>
<tr>
<th>Under 4</th>
<th>5 - 9</th>
<th>10 - 14</th>
<th>15 - 17</th>
<th>18 - 20</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['cy_pop_04'] . "</td>";
echo "<td>" . $row['cy_pop_59'] . "</td>";
echo "<td>" . $row['cy_pop_1014'] . "</td>";
echo "<td>" . $row['cy_pop_1517'] . "</td>";
echo "<td>" . $row['cy_pop_1820'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
Change <input id="submit" onclick="searchLocations()" value="GO" type="button"> to <input id="submit" value="GO" type="submit" name="submit"> then use a conditional statement.
I.e.: if(isset($_POST['submit']))
Here is a prepared statement method.
The way you're doing it now (or intended to use), will leave you open to SQL injection.
<?php
$con=mysqli_connect("localhost","######","######","######");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if(isset($_POST['submit'])){
$zip = $_POST['addressInput'];
if($query = $con->prepare("SELECT * FROM Prospects WHERE zip=?")){
$query->bind_param("s", $zip);
$query->execute();
}
echo "<table width='540' cellpadding='0' border='0' cellspacing='0'>
<tr>
<th>Under 4</th>
<th>5 - 9</th>
<th>10 - 14</th>
<th>15 - 17</th>
<th>18 - 20</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['cy_pop_04'] . "</td>";
echo "<td>" . $row['cy_pop_59'] . "</td>";
echo "<td>" . $row['cy_pop_1014'] . "</td>";
echo "<td>" . $row['cy_pop_1517'] . "</td>";
echo "<td>" . $row['cy_pop_1820'] . "</td>";
echo "</tr>";
}
echo "</table>";
} // closing brace for if(isset($_POST['submit']))
mysqli_close($con);
?>
Footnotes:
Do not do or use this:
WHERE zip = 'echo $_POST['addressInput']'
^^^^ ^ ^
It's always better using prepared statements when using mysqli_* functions.
Here is a tutorial on using prepared statements.

PHP MSSQL Query Search

I have been batting this around for a while and can not get the variables working for a search. Can connect fine and return results defined as a proper mssql_query and also am fine order by on variables etc but trying to get a text search implemented is not returning results not sure why.
<?php
$link = mssql_connect('SERV13\\RALSQL12', 'RA4joomla', 'Fenestron1');
if (!$link || !mssql_select_db('RALNHV', $link)) {
die('Unable to connect or select database!');
}else{
echo"";
}
if(isset($_REQUEST['submit'])){
$firstname=$_POST['FirstName'];
$surname=$_POST['Surname'];
$query = 'SELECT * FROM lEmployee WHERE FirstName LIKE '%".$firstname."%' OR Surname LIKE '%".$surname."%'';
$q=mssql_query($sql);
}
else{
$query = 'SELECT * FROM lEmployee';
$q = mssql_query($query);
}
?>
<form method="post">
<table width="200" border="1">
<tr>
<td>Name</td>
<td><input type="text" name="firstname" value="<?php echo $firstname;?>" /></td>
<td>Email</td>
<td><input type="text" name="surname" value="<?php echo $surname;?>" /></td>
<td><input type="submit" name="submit" value=" Find " /></td>
</tr>
</table>
</form>
<?php
// Check if there were any records
echo "<table class='table'>";
echo "<tr>";
echo "<th><a href='?orderBy=FirstName'>FirstName</a></th><th><a href='?orderBy=Surname'>Surname</a></th><th><a href='?orderBy=EmployeeNo'>Trigram</a></th><th>Office Phone</th><th>Mobile</th><th><a href='?orderBy=EmployeeJobTitle'>Job Title</a></th><th><a href='?orderBy=Name'>Base</a></th>";
echo "</tr>";
while ($row = mssql_fetch_array($query)) {
echo "<tr>";
echo "<td>" . '' . iconv("CP1252", "UTF-8", $row['FirstName']) . '' . "</td>";
echo "<td>" . '' . iconv("CP1252", "UTF-8", $row['Surname']) . '' . "</td>";
echo "<td>" . '' . $row['EmployeeNo'] . '' . "</td>";
echo "<td>" . '' . $row['Phone'] . '' . "</td>";
echo "<td>" . '' . $row['Mobile'] . '' . "</td>";
echo "<td>" . '' . $row['EmployeeJobTitle'] . '' . "</td>";
echo "<td>" . '' . $row['Name'] . '' . "</td>";
echo "</tr>";
}
echo "</table>";
?>
I am 100% agree with nickL you have some formating issue in your query try to replace your search query by this:
$firstname=$_POST['firstname'];
$surname=$_POST['surname'];
$query = "SELECT * FROM lEmployee WHERE FirstName LIKE '%".$firstname."%' OR Surname LIKE '%".$surname."%'";
$q=mssql_query($sql);
php is a case sensitive language your post variables name are wrong replace the code and try again, if not succeeded try echo $query and run it in query browser in sql server.
hope this will fix the issue.

Get a mySQL line item id with PHP

Right now I have a table that displays menu items and I want an Admin to be able to delete and edit a particular line item. My delete.php code works correctly if I have the id equal to a particular number, but I want the id to be equal to the id of whichever row the delete button is in. So my question is how do I get that id number? Because what I'm doing now is not correct.
Here is my delete.php file:
<?php
$con = mysql_connect("localhost", "root", "");
if(!$con)
{
die('Could not connect: ' .mysql_error());
}
mysql_select_db("bics_place", $con);
echo "mysql connected";
$myid = $_POST['id'];
$sql = "DELETE FROM menu WHERE id='$myid'";
echo "sql = $sql";
if(!mysql_query($sql, $con))
{
die('Error: ' .mysql_Error());
}
echo "1 record deleted";
header("location:admin_menu.php");
mysql_close($con);
?>
This is the table being made in admin_menu.php
$result = mysql_query("SELECT * FROM menu");
echo "<table border='1' id='menu'>
<form method='post' action='delete.php'>
<tr>
<th> Id </th>
<th> Type </th>
<th> Product Name </th>
<th> Price </th>
<th></th>
<th></th>
</tr>";
while($row = mysql_fetch_assoc($result))
{
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['type'] . "</td>";
echo "<td>" . $row['productName'] . "</td>";
echo "<td>" . $row['price'] . "</td>";
echo "<td>" . '<input type="submit" name="delete" value="Delete">' . "</td>";
echo "<td>" . '<input type="submit" name="edit" value="Edit">' . "</td>";
echo "</tr>";
}
echo "</form>";
echo "</table>";
Take on hidden field in your form.Then button onclick event set id into hidden field before submit.
<script>
function setId(idValue){
document.getElementById('myid').value=idValue;
}
</script>
echo "<table border='1' id='menu'>
<form method='post' action='delete.php'>
<input type="hidden" name="id" id="myid" value="" />
<tr>
<th> Id </th>
<th> Type </th>
<th> Product Name </th>
<th> Price </th>
<th></th>
<th></th>
</tr>";
while($row = mysql_fetch_assoc($result))
{
$myID = $row["id"];
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['type'] . "</td>";
echo "<td>" . $row['productName'] . "</td>";
echo "<td>" . $row['price'] . "</td>";
echo "<td>" . '<input type="submit" name="delete" value="Delete" onClick="setId('.$myID.');">' . "</td>";
echo "<td>" . '<input type="submit" name="edit" value="Edit">' . "</td>";
echo "</tr>";
}
echo "</form>";
echo "</table>";
Add a hidden field - id in the form :
while($row = mysql_fetch_assoc($result)) {
//your <td>'s here
echo '<input type="hidden" name="id" value="{$row[id]}">';
// echoes for form submit
}
Note : mysql_* functions are deprecated. You should use mysqli_ functions instead. Read here

Categories