Displaying MySQL query in html select - php

I am still a beginner with php and MySQL. I am having trouble getting rows from my database to display in an html select drop down box. I have researched it and it seems like my code should be good. The campaigns table as a row titled name. This is the row I am wanting to echo into the drop down. The drop down shows, however there is no content in it. Not sure what I am missing here...
Here is the code
<?php
$con=mysqli_connect("localhost","username","password","db_name");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query = mysqli_query($con,"SELECT * FROM campaigns");
echo '<select name="campaignChange">';
while ($row = mysql_fetch_array($query)) {
echo "<option value='" . $row['name'] ."'>" . $row['name'] ."</option>";
}
echo '</select>';
?>

You are mixing mysql and mysqli syntax.
You should change:
$query = mysql_query($con,"SELECT * FROM campaigns");
to:
$query = mysqli_query($con,"SELECT * FROM campaigns");
and:
while ($row = mysql_fetch_array($query)) {
to:
while ($row = mysqli_fetch_array($query)) {
By the way, you should add error handling. If you add this to the top:
mysqli_report(MYSQLI_REPORT_ALL);
mysqli will throw exceptions so you will always know what goes wrong exactly. As long as you use mysqli functions of course...

Related

Use POST method to display data from database PHP

I am using this SQL query in a link to retrieve data from database
<div class="nav-laptop">Laptop
and display it using
$sql = $_REQUEST['upit'];
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<div class='proizvodi'>";
// output data of each row
$result->data_seek(0);
while($row = $result->fetch_assoc()) {
echo "<div class='row'>";
foreach($row as $key => $value){
echo "<div class='" . $key . "'>" . $value . "</div>";
}
echo "</div>";
echo "<hr />";
}
echo "</div>";
}
else {
echo "<div class='search-query-none'><img src='index/no result.png' width='754' height='198' /></div>";
}
I realized this is very vulnerable and that I should use POST method to hide parameters from URL. I tried reading online forums, but I found nothing that would help me to convert this to POST way of retrieving data.
So, how do I use POST method to achieve the same result as I am achieving right now using GET?
This will give you a general idea on how to do this.
HTML form:
<form method="post" action="your_handler.php">
<input type = "text" name = "search_query">
<input type = "submit" name = "submit" value = "Search">
</form>
SQL/PHP and assuming a successful connection using the MySQLi API.
$conn = mysqli_connect("your_host", "user", "password", "db");
if (!$conn) {
echo "Error: Unable to connect to MySQL." . PHP_EOL;
echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
exit;
}
if(isset($_POST['submit'])){
if(!empty($_POST['search_query'])){
$search_query = mysqli_real_escape_string($conn, $_POST['search_query']);
$result = mysqli_query($conn, "SELECT * FROM TABLE WHERE col = '$search_query' ");
if(!$result) { echo "Error: " . mysqli_error($conn); }
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
// perform what you want here
// and check for errors on your query
}
}
}
}
You can substitute SELECT * with the said columns also.
Ideally, a prepared statement is nice to work with.
http://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php
http://php.net/pdo.prepared-statements (if you want to look into PDO).
Sidenote: Do not intermix different MySQL APIs such as mysqli_ with PDO. They just don't mix together.
Check for errors also against your query:
http://php.net/manual/en/mysqli.error.php
Add or die(mysqli_error($conn)) to mysqli_query().
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// Then the rest of your code
Sidenote: Displaying errors should only be done in staging, and never production.
Plus, make sure that no whitespace gets introduced into your input, otherwise your query may fail.
Use trim() against the input.
You don't need to use POST for a SELECT query. You can, but it's really better suited for INSERT / UPDATE / DELETE, things that actually change your data. A possible advantage to using a link like that for search results is that it can be saved, bookmarked, emailed, etc., where a form submission cannot. But you are right that putting your entire query into a link like that definitely is extremely vulnerable.
Instead of passing the entire query through the link, you can just pass the parameters, like this:
Laptop
Then in your display code you can use a prepared statement and safely bind the parameter:
$kategorija = $_GET['kategorija'];
$sql = 'SELECT Slika, Naziv, Opis, Cijena FROM Proizvodi
WHERE Kategorija=? ORDER BY Proizvodac';
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $kategorija);
$stmt->execute();
// etc.

Error when fetching SQL array [duplicate]

This question already has an answer here:
Syntax error due to using a reserved word as a table or column name in MySQL
(1 answer)
Closed 7 years ago.
I am extremely new to PHP and I'm frustrated by the error of this simple task. I want to import a table from an SQL database and show it in a HTML table. But I keep getting errors when trying to fetch the table column names.
The connection with the database is made though, I tested that.
The error is:
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 'Table' at line 1.
I found this example on w3schools which I edited by other examples on php.net
If anybody can help me with this, I'd appreciate it.
<?php
error_reporting(-1);
$con = mysqli_connect('localhost', 'user', 'pass');
mysqli_select_db($con, 'database') or die("Could not found" . mysqli_error($con));
$query = ("select * from Table");
$result = mysqli_query($con, $query) or die ( mysqli_error ($con) );
//Print table
echo "<table>";
echo "<tr>";
if($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
//Print headers
foreach($row as $key => $value ){
echo "<td>" . $key . "</td>";
}
echo "</tr>";
}
$result = mysqli_query($con, $query) or die (mysqli_error());
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
echo "<tr>";
while( list($key, $value) = each($row)){
//Print value
echo "<td>" . $value . "</td>";
}
echo "<td>" . $value . "<i class='fa fa-caret-up'></i><i class='fa fa-caret-down'></i></td>";
echo "</tr>";
}
echo "</table>";
?>
Table is a reserved keyword and you cant use it like this. If you want to fetch some data from a table named users or some like this then the query should be -
select * from users

load options to an drop down list in html from when the page loads from database

I want to load options for a drop downlist when an html form loads.I already know how to do when I select first drop down and load for second.But when page loads how to do that.Your kind consideration given with this regard is highly appreciated.
You can try something like below for loading deopdownlist option from database
<?php
$con=mysqli_connect("localhost","user","password","db_name");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM table_name");
echo '<select id="select_1">';
while($row = mysqli_fetch_array($result)) {
echo '<option value="'.$row['column_name'].'">'.$row['column_name'].'</option>';
}
echo '</select>';
mysqli_close($con);
?>

Echoing options from column in mySQL (option/select)

I've been working with this for almost an 3 hours now. It just seems unfixable. I've tried millions of options but just won't work.
So I want to echo from column title in table news so they apear like options in option select.
THis is how it looks now:
Here is the code:
<?php
global $mysqli;
mysqli_connect($mysqli,'localhost', 'root', '');
mysqli_select_db ($mysqli,"filip12356");
$sql = "SELECT DISTINCT title FROM news";
$result = mysqli_query($mysqli,$sql);
echo "<select name='title_name'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['title'] . "'>" . $row['title'] . "</option>";
}
echo "</select>";
?>
Well you seem to be using mysqli_ everywhere except here...
$row = mysql_fetch_array($result))
Should be..
$row = mysqli_fetch_array($result))
I would ensure that all files are UTF-8 encoded without BOM. It seems that the server is misunderstanding the php as text.

Select one value from database

I have the code bellow, it's ok but I want to be able to use for example the 4th value extracted from the database, use it alone, not put all of them in a list, I want to be able to use the values from database individually. How do I echo them?
Edit: I was thinking to simplify things, to be able to add the values from database into one array and then extract the value I need from the array (for example the 4th - ordered by "order_id"). But how?
Right now I can only create a list with all the values one after the other..
(Sorry, I am new to this). Thank you for all your help..
<?php
include '../../h.inc.php';
$con = mysql_connect($db['host'],$db['user'],$db['passwd']);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("database", $con);
$result = mysql_query("SELECT * FROM options WHERE Name LIKE 'x_swift%' ORDER BY order_id");
echo "<table border='1'>
<tr>
<th>Values</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
// echo "<td>" . $row['Name'] . "</td>";
echo "<td>" . $row['VALUE'] . "</td>";
echo "</tr>";
$array = array(mysql_fetch_array($strict));
}
echo "</table>";
mysql_close($con);
?>
To select the value in the value column of the row where order_id is 4, use this SQL:
$query = 'select value from options where order_id = 4';
Then you can access this result in many ways. One is to get the entire result row (which in this case is just one cell) as an associative array:
if ($result = mysql_query($query)) {
$row = mysql_fetch_assoc($result);
echo 'value = ' . $row['value'];
}
You can also get the value directly:
if ($result = mysql_query($query)) {
echo 'value = ' . mysql_result($result, 'value');
}
It would just be a query like...
$result = mysql_query("SELECT * FROM options WHERE ID = 3");
mysql_fetch_row($result);
Unless Im misunderstanding you....let me know
But you really should use PDO, instead of deprecated mysql_* functions
http://php.net/manual/en/book.pdo.php

Categories