where condition doesn't work - php

I've made an html design that have many checkbox and I want to take values of this checkbox and search for data similar for it in the database
the problem is in the query ...where condition isn't work although I've tested it in phpmyadmin and it was work.
<?php
$conn = mysqli_connect("localhost","root","","bella_vista");
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
if (isset($_POST['submit'])) {
foreach ($_POST['Ingredient'] as $selected)
{
//sql query to search db
$query ="select name,image
from reciepe
where R_ID =any(select I_ID FROM ingredient where item like '%$selected%') ";
$result =mysqli_query ($conn,$query);
print_r ($result);
while($row = mysqli_fetch_assoc($result)) {
$name = $row['name'];
$image = $row['image'];
echo '<div>'.$name. ''.$image.'</div>';
}
}
}
?>

Change
$query ="select name,image
from reciepe
where R_ID =any(select I_ID FROM ingredient where item like '%$selected%') ";
To
$query ="SELCT name,image
FROM reciepe
WHERE R_ID IN (SELCT I_ID FROM ingredient WHERE item LIKE '%$selected%') ";

Related

How to update data using one select in other database table

I have two databases and i have one table "TabelaX" in database "Servidor1" with out data and other database "Servidor2" with one table "TabelaY". And i want do one select in table "TabelaY" and with her data do one Update in table "TabelaX" which is in another database. I already made some code but it is not working correctly.
<?php
$conn= mysqli_connect('localhost','root',null,'Servidor2') or die
(mysqli_connect_error());
if (!$conn) {
die("Falha de conexao: ". mysqli_connect_error());
}
$ID = $_POST['ID'];
$sql = "SELECT * FROM TabelaY WHERE ID = $ID";
$result = mysqli_query($conn, $sql);
mysqli_select_db($conn,"Servidor1");
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$row1 = $row["ID"];
$row2 = $row["Data"];
}
} else {
echo "0 results";
}
$sql = "INSERT INTO Servidor1.TabelaX (ID, Data)
SELECT ID, Data
FROM Servidor3.TabelaW
WHERE ID = $ID;";
$sql = "UPDATE Servidor1.TabelaX SELECT ID, Data FROM
Servidor3.TabelaW SET Data = $row2 WHERE $row1 = $ID;";
if (mysqli_multi_query($conn, $sql)) {
echo "Dados Inseridos";
} if (mysqli_multi_query($conn, $sql)) {
echo "Dados Atualizados";
}
mysqli_close($conn);
I have no idea what your query is trying to do, because you assign to $sql twice without ever executing the first query, but if you're asking how to update a row in tableX based on data from tableY, then:
UPDATE Servidor1.TabelaX as x, Servidor2.TabelaY as y
SET x.Data = y.Data
WHERE x.id = y.id
AND x.id = $someIdForWhichYouWantToUpdate
Also, do not do this:
$ID = $_POST['ID'];
$sql = "SELECT * FROM TabelaY WHERE ID = $ID";
Imagine what happens when the user posts 1; DROP DATABASE Servidor1 into the form. This is called SQL injection and your code is full of vulnerabilities to it.

Looping mulitple SQL queries in multiple arrays

I'm a PHP beginner. I've dabbled before, but when I've begun to get the knack a new project takes me elsewhere. If anyone can assist; I'd appreciate it.
I am using multiple queries and arrays to retrieve data between two mySQL tables starting from 1 initial known variant.
I'd like each query to process all results from the previous query. This is not occurring.
Current results: The first query echos all results. The second query echos one result. The third query echos 1 result. The final echo displays all the final results (desired, but missing the first 148 rows).
Desired results: Echo all 149 results from all three queries then echo a table/array of all 3 queries (to confirm correlation).
<?php
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//Select all POST_IDs for variation 2.1M
$sql = "SELECT post_id FROM wp_postmeta WHERE meta_value = '2-1m'";
$result = $conn->query($sql);
//Array and display POST_IDs
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["post_id"]. "<br>";
}
} else {
echo "0 results";
}
//Prepare POST_IDs for next query
foreach ($result as $row){
$postids = $row["post_id"];
}
//Use POST_IDs to select all PARENT_IDs
$sql2 = "SELECT post_parent FROM wp_posts WHERE ID = ($postids)";
$result2 = $conn->query($sql2);
//Array and display PARENT_IDs
if ($result2->num_rows > 0) {
// output data of each row
while($row2 = $result2->fetch_assoc()) {
echo "parentid: " . $row2["post_parent"]. "<br>";
}
} else {
echo "0 results";
}
//Prepare PARENT_IDs for next query
foreach ($result2 as $row2){
$parentids = $row2["post_parent"];
}
//Select PRICES using PARENT_IDs and META_KEY for Price
$sql3 = "SELECT meta_value FROM wp_postmeta WHERE meta_key = '_price' AND post_id = ($parentids)";
$result3 = $conn->query($sql3);
if ($result3->num_rows > 0) {
// output data of each row
while($row3 = $result3->fetch_assoc()) {
echo "price: " . $row3["meta_value"]. "<br>";
}
} else {
echo "0 results";
}
//Array and display PRICES
foreach ($result3 as $row3){
$prices = $row3["meta_value"];
}
//Display all retrieved data
echo "<div><p>" . $postids . " " . $parentids . " " . $prices . "</p></div>";
$conn->close();
?>
You're overriding your variables instead of cumulate them into an array:
foreach ($result as $row){
$postids = $row["post_id"];
}
Should be :
$postids = [];
foreach ($result as $row){
$postids[] = $row["post_id"];
}
Then :
"WHERE ID = ($postids)"
Should be :
if (!empty($postids)) {
... "...WHERE ID IN (".implode(',', $postids).")..." ...
}
NB: you should have a look to parameterized queries : Parameterized Queries PHP/MySQL
The same thing happend for $parentids.

php sql How to display only the last value in the row?

I need only to display the last values in the row. Now its displaying
Message for: Rocha : gff
Message for: Rocha :
Message for: Rocha : hi my name is kenny
I only need it to display Message for: Rocha : hi my name is kenny.
Thank you
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "company";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, className, lastname, messages FROM Mymesages";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
if("CPS210-CompSci-I (4)"==$row["className"] && $lastname== $row["lastname"]){
echo "Message for: " . $row["lastname"]. " : " . $row["messages"]. "<br>";
}
}
}
$conn->close();
?>
If you're looking for only one record, that too the last one, you just need to modify your query a little. Also, there's no need for the loop in that case.
$sql = "SELECT id, className, lastname, messages FROM Mymesages ORDER BY id DESC LIMIT 1";
Replace this line:
while($row = $result->fetch_assoc()) {
With simply:
$row = $result->fetch_assoc();
If you want to display the last row, then your query should be like this:
$sql = "SELECT id, className, lastname, messages FROM Mymesages ORDER BY id DESC LIMIT 1";
And later, instead of while loop simply fetch the row like this:
$row = $result->fetch_assoc();

Rating system: Pulling in average rating

the following is my code to do a database search and return the results in this format:
- Institute name 1
Rating: x/5
- Institute name 2
Rating: x/5
code:
search_results.php
<?php
//mysql_
$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
if(mysqli_connect_errno())
{
die("Database connection failed: " .
mysqli_connect_error() .
" (" . mysqli_connect_errno() . ")");
}
$result = "";
//collect info from database
if(isset($_POST['search'])) {
$searchq = $_POST['search'];
$searchq = preg_replace("#[^0-9a-z]#i", "", $searchq);
//echo $searchq;
//SQL query
$query = "SELECT institute_id, name FROM institutes WHERE
category1 LIKE '%$searchq%' OR
category2 LIKE '%$searchq%' OR
category3 LIKE '%$searchq%' OR
category4 LIKE '%$searchq%'";
$result = mysqli_query($connection, $query);
// Test if there was a query failure
if(!$result){
die("Database query failed.");
}
$count = mysqli_num_rows($result);
if($count == 0)
{
$output = "There's no search result";
}
else {
while($row = mysqli_fetch_assoc($result))
{
$id = $row["institute_id"];
?>
<li>
<h3>
<a href="institute_profile_test.php?id=<?php echo $id; ?>"><?php echo $row["name"];?>
</a>
</h3>
</li>
<div class = "rating">Rating: x/5</div>
<?php
}
}
}
?>
I have a ratings and institutes table in my database whose table structures are as follows:
ratings
institutes
As you can see, the ratings database already stores some rating information.(I will share the code i wrote to register ratings if required)
What i need to do next is pull in the average rating for each institute and substitute the x with each individual average. What additional code do i write in search_results.php to achieve this goal?
I would also like to sort the institute names as per their average ratings.
Calculating/Saving the average
If I understand correctly, all you need to do is create a simple while loop that runs through all the instances of the institute_id being fetched for each successful "search" query.
while($row = mysqli_fetch_assoc($result)){
$id = $row["institute_id"];
$query2 = "SELECT rating FROM ratings WHERE institute_id ='$id'";
$result2 = mysqli_query($connection, $query2);
//average rating vars
$count = 0;
$sum = 0;
while($row2 = mysqli_fetch_assoc($result2)){
$count++;
$sum += $row2['rating'];
}
$average = $sum / $count;
//display average
.....
}
That should allow you to display the average for each institute, then if you want to display them according to DESCENDING or ASCENDING just save each average in an array. The rest is up to you, try saving the average results in a JSON array and pairing each result with its institute id counter part.
example:
$average = array('institute_x' => 'average')
*Ensure to replace 'institute_x' with id and 'average' with average...

php-mysql How to select the particular number of the row in mysql?

I am new at this and learning the code.
I want to create the php code which select the particular row.
say 5th row or 6th row any row.
I create the code like this
<?php
$servername = "localhost";
$username = "test1";
$password = "pass";
$dbname = "test1";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT FIELD1, FIELD2 FROM mytable ";
$result = $conn->query($sql);
if ($result->num_rows > 0)
{
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["FIELD1"]. " - Name: " . $row["FIELD2"]. " <br>";
}
} else
{
echo "0 results";
}
$conn->close();
?>
THis code works fine but it give the all data of the table.I want to just select particular row number data.how to do this??
You can do it with the LIMIT statement, say LIMIT 3,1 to select the 4th row. First number is the starting row, second number is the count of rows to select.
$sql = "SELECT FIELD1, FIELD2 FROM mytable LIMIT $row_index, 1";
will give you row $row_index + 1
You can do it using WHERE condition in query as SELECT FIELD1, FIELD2 FROM mytable WHERE id = 1.

Categories