Use variable as ID and get table from mysql (edited) - php

I'm using a multiple select option form to get a table of venues. Each venue has an ID and this is what I used:
<?php
require("db_access.php");
if(isset($_POST['select3']))
{
$aVenues = $_POST['select3'];
if(!isset($aVenues))
{
echo("<p>You didn't select any venues!</p>\n");
}
else
{
$nVenues = count($aVenues);
echo("<p>You selected $nVenues venues: ");
for($i=0; $i < $nVenues; $i++)
{
echo($aVenues[$i] . " ");
}
echo("</p>");
$sql = "SELECT * FROM venues WHERE id IN (" . implode(",",$aVenues) . ")";
$comma_separated = implode(",", $aVenues);
echo $comma_separated;
}
}
?>
It results in this:
However I thought that the code would use those two numbers below and draw out a table with those id's I used :/ ? Am I missing something?

$array is used in implode(",", $array); but is not defined anywhere else that we can see. It is perhaps intended to be:
implode(",", $aVenues);
UPDATE
Per comments, it does not draw a table because you never actually query your database.
You build your SQL statement, but you need to execute it and fetch the result set.
// Make sure you actually have a database connection
$conn = mysql_connect('localhost', $username, $password);
mysql_select_db($database);
$sql = "SELECT * FROM venues WHERE id IN (" . implode(",",$aVenues) . ")";
$comma_separated = implode(",", $array);
echo $comma_separated;
// Execute query and fetch result rowset
$result = mysql_query($sql);
if ($result) {
$rowset = array();
while ($row = mysql_fetch_array($result)) {
$rowset[] = $row;
}
var_dump($rowset);
}
else echo mysql_error();

Related

Dynamic value in sql query using php

I want to search a certain string in all the columns of different tables, so I am looping the query through every column name. but if i give it as dynamic value it does not seem to work.
what is wrong?
<?php
$search = $_POST['search'];
$columns = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'feedback'";
$columns_result = $conn->query($columns);
$columns_array = array();
if (!$columns_result) {
echo $conn->error;
} else {
while ($row = $columns_result->fetch_assoc()) {
//var_dump($row);
//echo $row['COLUMN_NAME']."</br>";
array_push($columns_array, $row['COLUMN_NAME']);
}
}
var_dump($columns_array);
$row_result = array();
for ($i = 0; $i < count($columns_array); $i++) {
echo $columns_array[$i] . "</br>";
$name = "name";
// $sql = 'SELECT * FROM feedback WHERE "'.$search.'" in ("'.$columns_array[$i].'")';
$sql = 'SELECT * FROM feedback WHERE ' . $name . ' like "' . $search . '"';
$result = $conn->query($sql);
if (!$result) {
echo "hi";
echo $conn->error;
} else {
foreach ($result as $row) {
array_push($row_result, $row);
echo "hey";
}
}
}
var_dump($row_result);
I am getting the column names of the table and looping through them because I have so many other tables which I need to search that given string. I don't know if it is optimal I did not have any other solution in my mind. If someone can tell a good way I will try that.
It looks to me that you want to generate a where clause that looks at any available nvarchar column of your table for a possible match. Maybe something like the following is helpful to you?
I wrote the following with SQL-Server in mind since at the beginning the question wasn't clearly tagged as MySql. However, it turns out that with a few minor changes the query work for MySql too (nvarchar needs to become varchar):
$search='%';$tbl='feedback';
if (isset($_POST['search'])) $search = $_POST['search'];
$columns = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = '$tbl' AND DATA_TYPE ='nvarchar'";
$columns_result = $conn->query($columns);
$columns_array = array();
if(!$columns_result) print_r($conn->errorInfo());
else while ($row = $columns_result->fetch(PDO::FETCH_ASSOC))
array_push($columns_array, "$row[COLUMN_NAME] LIKE ?");
$where = join("\n OR ",$columns_array);
$sth = $conn->prepare("SELECT * FROM $tbl WHERE $where");
for ($i=count($columns_array); $i;$i--) $sth->bindParam($i, $search);
$sth->execute();
$result = $sth->fetchAll(PDO::FETCH_ASSOC);
print_r($result);
The above is a revised version using prepared statements. I have now tested this latest version using PHP 7.2.12 and SQL-Server. It turned out that I had to rewrite my parameter binding part. Matching so many columns is not a very elegant way of doing queries anyway. But it has been a nice exercise.
It looks like you are using mysqli, so I wanted to give another way of doing it via mysqli.
It does more or less the same as cars10m solution.
$search = $_POST['search'];
$columns = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'feedback'";
$columns_result = $conn->query($columns)->fetch_all(MYSQLI_ASSOC);
// Here dynamically prepare WHERE with all the columns joined with OR
$sql = 'SELECT * FROM feedback WHERE ';
$arrayOfWHERE = [];
foreach($columns_result as $col){
$arrayOfWHERE[] = '`'.$col['COLUMN_NAME'].'` LIKE ?';
}
$sql .= implode(' OR ', $arrayOfWHERE);
// prepare/bind/execute
$stmt = $conn->prepare($sql);
$stmt->bind_param(str_repeat("s", count($arrayOfWHERE)), ...array_fill(0, count($arrayOfWHERE), $search));
$stmt->execute();
$result = $stmt->get_result();
$row_result = $result->fetch_all(MYSQLI_ASSOC);
var_dump($row_result);
Of course this will search for this value in every column of the table. It doesn't consider data type. And as always I have to point out the using PDO is better than mysqli. If you can switch to PDO.

SQL in php, make partial search using LIKE

I am trying to make SQL in php to return all the entries that matches a keyword that is entered by the user (from search bar).
I want to return all the entries that their name "partial" matches with the keyword.
I want at least to match the keyword, if an entry name in database before has space and after maybe another letter/space.
For example I have three entries with names "Milk", "Semi skimmed Milk" and "Full Milk 2". If the keyword is "Milk" or "milk" or "MiLK", I want to get all these three entries.
The only case I am thinking it might be the problem is case sensitive.
I tried with a keyword that exists exactly in database, but my app (on android) stops .
Based on user3783243 answer.
PHP FILE
<?php
$servername = "";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT name FROM items WHERE name LIKE CONCAT ('%', ?, '%')";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $keyword);
$res = $stmt->get_result();
while($row = $res->fetch_assoc()) {
echo $row["name"] . ",";
}
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row["name"] . ",";
}
} else {
echo "0";
}
$conn->close();
?>
Your query should be:
$sql = "SELECT * FROM items WHERE name LIKE CONCAT ('%', ?, '%')";
and then $keyword should be bound with whatever syntax the driver you are using supports.
As is your query would have been:
SELECT * FROM items WHERE name LIKE CONCAT ('%', Milk, '%')
and you wanted Milk to be a string so it needed to be quoted. As is mysql would have thought that was a column.
Alternatively you could do:
$keyword = '%' . $_POST['keyword'] . '%';
$sql = "SELECT * FROM items WHERE name LIKE CONCAT ?";
that is the same and still requires the binding though.
The binding also takes away the SQL injection. See How can I prevent SQL injection in PHP? and/or https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet#Defense_Option_1:_Prepared_Statements_.28with_Parameterized_Queries.29
Per update.. replace:
$keyword =$_POST['keyword'];
$sql = "SELECT * FROM items WHERE name LIKE '%$keyword%)";
$result = $conn->query($sql);
with:
$sql = "SELECT name FROM items WHERE name LIKE CONCAT ('%', ?, '%')";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $keyword);
$stmt->execute();
$res = $stmt->get_result();
if(empty($conn->errno) && !empty($res)) {
while($row = $res->fetch_assoc()) {
echo $row["name"] . ",";
}
} else {
echo '0';
//print_r($conn->errno);
}
$conn->close();
...
also remove
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row["name"] . ",";
}
} else {
echo "0";
}
$conn->close();
In this case you can convert the input in search bar to either upper or lower case by default then apply query in db like
For Upper case:
$keyword =strtoupper($_POST['keyword']);
$sql = "SELECT * FROM items WHERE upper(name) LIKE '%$keyword%)";
Or for lower case:
$keyword =strtolower($_POST['keyword']);
$sql = "SELECT * FROM items WHERE lower(name) LIKE '%$keyword%)";

mysqli_fetch_array only displays the first result

I struggled all day to display the results of an SQL query using PHP.
I have a table in the database named coins with the following columns:
- nr_unic (which is the index);
- rank;
- name;
- symbol;
- price_usd;
- price_btc;
What I need to do is to fetch the values of each coin (from the name field) and display the symbol, price_usd, price_btc, and rank. The piece of code which contains the query I am running and trying to display the values is:
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// SQL QUERY
$sql= "SELECT rank, name, symbol, price_usd, price_btc, 24h_volume_usd FROM coins WHERE rank BETWEEN 1 AND 10 ORDER BY nr_unic DESC LIMIT 10";
$result = $conn->query($sql);
$rows = array();
if ($result) {
while($row = mysqli_fetch_array($result, MYSQLI_BOTH)) {
$rows[] = $row['name'] . " " . $row['price_usd'] . " " . $row['symbol'] . " " . $row['rank'];
foreach ($rows as $key => $value) {
echo $value;
}
}
mysqli_free_result ($result);
}
Thank you!
LATER EDIT
Following #Máté Solymosi indications I managed updated the code and to display the results. The problem now is they are getting duplicated: I get the first coin, then the first and the second, then the first, second and third... and so on.
The code I use was updated
The return statement in your while loop causes the function to terminate immediately, returning just the first row. Instead, you should collect the results in an array and return the array at the end:
$rows = array();
while($row = mysqli_fetch_array($result, MYSQLI_BOTH)) {
$rows[] = $row['name'] . " " . // ...
}
mysqli_free_result($result);
return $rows;

Using mysql_fetch_assoc and updating each record

Some of my rows have a "," comma as the initial character in the field. So I need to loop through, check if each row has the initial commma, remove it if it does, and update the row.
I am running the following code, which seems to go on an endless loop when the update is called.
When I am just echoing out the result at the end, everything looks fine in the browser. But on execution of the update line below the echo, it seems as if a single datum from the column "Tags" is being populated for every record, instead of just the rows that have the initial commma that I am removing.
Would love help :)
$query = mysql_query("SELECT Tags FROM products")
or die (mysql_error());
while ($row = mysql_fetch_assoc($query))
{
$str = $row['Tags'];
$initial = substr($str,0,1);
if ($initial = ",") {
$str = (ltrim($str, ','));
}
echo "result: " .$str . "<br/>";
$result = "UPDATE products SET Tags = '" .$str ."'";
mysql_query($result);
}
Thank you.
You should pass the particular row id to the one you're making changes to, by using a WHERE clause:
$query = mysql_query("SELECT Tags FROM products")
or die (mysql_error());
while ($row = mysql_fetch_assoc($query)) {
$str = $row['Tags'];
$initial = substr($str,0,1);
if ($initial == ",") {
// == not =
$str = (ltrim($str, ','));
}
$id = $row['id'];
echo "result: " .$str . "<br/>";
$result = "UPDATE products SET Tags = '$str' WHERE id = $id";
mysql_query($result);
}
By the way, if possible kindly change to the better extension which is mysqli or PDO instead.
You're if() statement has an error in it.
You're using one equal:
if($initial = ",") {
}
Instead of two for actual comparison:
if($initial == ",") {
}
Here is the complete code. Thank you everyone.
$query = mysql_query("SELECT ProductID, Tags FROM products")
or die (mysql_error());
while ($row = mysql_fetch_assoc($query)) {
$str = $row['Tags'];
$initial = substr($str,0,1);
if ($initial == ",") {
$str = (ltrim($str, ','));
$id = $row['ProductID'];
//echo $id . " ";
//echo $str . "<br/>";
$result = "UPDATE products SET Tags = '$str' WHERE ProductID = $id";
echo $result ."<br>";
mysql_query($result);
}
}
So grateful for the help. I will update to mysqlli also.

why doesn't this code return all rows?

I have an access database, and one of the tables is called Products, which contains 9 rows.
I want to echo all of the rows, but when I use this code, it will echo only 4 rows.
Where is my fault ?
$conn = odbc_connect('MoeinODBCTest1', '', '');
$sql = "select * from Products";
$rs = odbc_exec($conn, $sql);
while(odbc_fetch_row($rs))
{
$arr = odbc_fetch_array($rs);
print_r($arr);
echo '<br>';
}
Both odbc_fetch_array and odbc_fetch_row are pulling rows out of the results.
Try instead:
$conn = odbc_connect('MoeinODBCTest1', '', '');
$sql = "select * from Products";
$rs = odbc_exec($conn, $sql);
while($arr = odbc_fetch_array($rs)) {
print_r($arr);
echo '
';
}
You are fetching rows both when calling odbc_fetch_row and odbc_fetch_array, so every second row gets discarded.
Since odbc_fetch_array returns FALSE when there are no more rows, you can use it to fetch the next row and check if there are any more rows, at the same time:
while ($arr = odbc_fetch_array($rs)) {
print_r($arr);
echo "\n";
}

Categories