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...
Related
I am attempting to get total values from two columns (I have already done this) -- and take these values and create a percent from them. In this case I have a Weighted Value and a Total Value. I need to know what Percent of the Total Value my Weighted Value is.
I have tried:
$result = mysqli_query($mysqli, "SELECT SUM(WEIGHTEDV / VALUE) FROM test.service");
$result = mysqli_query($mysqli, "SELECT WEIGHTEDV, VALUE, (WEIGHTEDV / VALUE) AS percent FROM test.service;
$result = mysqli_query($mysqli,"SELECT (WEIGHTEDV / VALUE)*10 AS Percent
FROM test.service");
There were a few other attempts I do not readily remember.
Here is more complete code:
Login & Working SUM of VALUE
<?php
//LOGIN INFO
$db_host = 'localhost';
$db_user = 'root';
$db_pw = "********";
$database = "test";
//LOGIN VARIABLE
$mysqli = new mysqli($db_host, $db_user, $db_pw);
//VERIFY LOGIN INTEGRITY
if ($mysqli === false) {
die("Cannot connect to Database Server" . $mysqli->connect_error);
}
if (!mysqli_select_db($mysqli, $database)) {
die("Cannot select test Database" . $mysqli->connect_error);
}
$result = mysqli_query($mysqli, "SELECT SUM(VALUE) FROM test.service");
//PRINT ROWS
$fields_num = mysqli_num_fields($result);
while($row = mysqli_fetch_row($result)) {
foreach($row as $cell) {
echo "$$cell";
}
}
?>
Working SUM of WEIGHTEDV
<?php
$result = mysqli_query($mysqli, "SELECT SUM(WEIGHTEDV) FROM test.service");
//PRINT ROWS
$fields_num = mysqli_num_fields($result);
while($row = mysqli_fetch_row($result)) {
foreach($row as $cell) {
echo "$$cell";
}
}
?>
The expected output with the current totals in my Table is
Expected Output: %54.8
Test Variables:
VALUE: 38940.00
WEIGHTEDV:21345.00
Both have a type of (I changed the type to INT -- same result):
DECIMAL(12,2)
Example of actual output (directly out of the HTML table):
65.000000100.0000000.00000050.00000025.000000100.00000050.000000
Current code with above output:
$result = mysqli_query($mysqli,"SELECT (WEIGHTEDV / VALUE)*100 AS Percent
FROM test.service");
This is boggling me pretty good. I am sure it is something simple I am overlooking. Any assistance would be greatly appreciated as to why I cannot get a simple % value output.
seems you need number format and a proper <br />
while($row = mysqli_fetch_row($result)) {
foreach($row as $cell) {
echo umber_format($cell, 2, '.', ',')."<br>";
}
}
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%') ";
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.
I have a view in MySQL called published_people that looks like this:
PersonID Name LastName MarkerID date
-------- ---- -------- -------- ----
1198 Jane Doe Doe 1174 2015-05-20
864 John Doe Doe 863 2015-04-23
1187 Richard Roe Roe 1165 2015-05-21
1190 Sam Spade Spade 1167 2015-01-01
I have a post variable representing the marker ID of the person whose page of data I'm viewing.
I have another post variable that represents the last name of the person whose page of data I'm viewing.
I want to be able to iterate through published_people. If the LastName field matches the variable, I want to get the prior record (the one before this one) in published_people.
Here's my code in php so far:
include_once ('constants_test.php');
$mysqli_prior = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (mysqli_connect_errno()) {
printf("Connect failed: %s", mysqli_connect_error());
exit();
}
//get the year I'm looking for
$this_date = mysqli_real_escape_string($mysqli_prior, $_POST['this_date']);
$pieces = explode("-", $this_date);
$this_year = $pieces[0];
//find the last name of the person I'm looking for
$marker_id = $_POST['marker_id'];
$q_getLastName = "select LastName from published_people where MarkerID =" . $marker_id;
$result = mysqli_query($mysqli_prior,$q_getLastName);
$r = $result->fetch_row();
$thisLastName = $r[0];
//get all records from this year, alphabetized by last name
$q = "select * from published_homicides where year(date) = '" . $this_year . "' order by LastName";
$result = $mysqli_prior->query($q);
$allresults = array();
$num_rows = mysqli_num_rows($result);
if ($num_rows != 0) {
while($row = $result->fetch_array(MYSQLI_ASSOC)) {
// How do I say this?
// if $row["LastName"] == $thisLastName then find the record
// PRIOR TO this one and do the following:
$results = array($row['Name'], $row['date']);
array_push($allresults, $results);
}
echo json_encode($allresults);
} else {
echo "nothing";
}
mysqli_close($mysqli_prior);
I ended up creating a variable to hold the data from the previous record. I iterated through the query. When the MarkerID equaled the marker_id of the record I wanted the previous one of, I stopped:
$priorname = ""; //initialize at nothing
//we'll go through the list of names in alphabetical order by year
while($row = $result->fetch_array(MYSQLI_ASSOC)) {
//compare the row id to the posted id
if ($row['MarkerID'] == $marker_id) {
$results = array($priorname);
array_push($allresults, $results);
} else {
$priorname = $row['Name']; //save this data in $priorname
}
}
echo json_encode($allresults);
mysqli_close($mysqli_prior);
So that was getting the prior record.
I also wanted to get the next record.
I handled this problem in two parts. First I went through my query, counting the row I was on. When my post variable called marker_id matched the MarkerID in the database view, I stopped the query:
$marker_id = $_POST['marker_id'];
$q = "select MarkerID, Name, LastName, date from published_people order by year(date) desc, LastName asc";
$result = $mysqli_next->query($q);
$allresults = array();
$count = 0;
//we'll go through the list of names in alphabetical order by year
while($row = $result->fetch_array(MYSQLI_BOTH)) {
$count++; //keep track of what row you're on
//compare the row id to the posted id
if ($row['MarkerID'] == $marker_id) {
//if they're the same, stop this query - we have counted to the spot that they matched
break;
}
}
Now I know where to set a limit on another query:
//make a new query with a limit of one record starting at the row # indicated by $count
$newq = "select MarkerID, Name, LastName, date from published_homicides order by year(date) desc, LastName asc LIMIT " . $count . ",1";
$result2 = $mysqli_next->query($newq);
while($row2 = $result2->fetch_array(MYSQLI_ASSOC)) {
$results = array($row2["Name"]);
array_push($allresults, $results);
}
echo json_encode($allresults);
mysqli_close($mysqli_next);
I need a rating system which shows the average ratings in php. I done the rating process (saving and update process). I need just to show the average rating in php (using php-Ajax rating system).
While I retrive the data from the database I got errors. The code is this:
<?php
$con = mysql_connect("localhost","root","");
if(!$con){
echo "Connection to the Database Console was Unsuccessful";
}
$select = mysql_select_db("oilandgas13",$con);
if(!$select){
echo "Connection to the Database was Unsuccessful";
}
$add_coun= "SELECT sum(rating) sum, count(id) count from comments WHERE item_id = $itemID AND status=1";
$result = mysql_query($add_coun,$con);
if(!$result)
{
echo "query was not successfully";
}
$result = mysql_fetch_object($result);
$sum = $result->sum;
$count = $result->count;
$rating = $sum / $count;
echo $rating;
?>
I got errors like this:
Warning: mysql_fetch_object(): supplied argument is not a valid MySQL result resource in C:\wamp\www\final work_apr51\final work_apr51\calculation.php on line 19
Warning: Division by zero in C:\wamp\www\final work_apr51\final work_apr51\calculation.php on line 23
Maybe this can help you?
$link = mysqli_connect("localhost","mysqlusername","mysqlpassword","dbname");
$rating = mysql_real_escape_string($_GET['id']);
$q = mysqli_query($link,"SELECT * FROM ratings WHERE id='{$rating}'"); //Get our ratings by the page that has rated
//Die if id dont exist!
if(mysqli_num_rows($q) == 0) die("Wrong page id!");
//Select good & bad ratings
$good = mysqli_query($link,"SELECT * FROM ratings WHERE id='{$rating}' AND value ='yes'");
$bad = mysqli_query($link,"SELECT * FROM ratings WHERE id='{$rating}' AND value ='no'");
//Count good & bad ratings
$gcnt = mysqli_num_rows($good);
$bcnt = mysqli_num_rows($bad);
//Calculate
$totalVotes = $gcnt + $bcnt;
if($totalVotes == 0){
echo $totalVotes." votes";
}
if($totalVotes > 0){
echo "<font color='green'>".$totalVotes." votes</font>";
}
if($totalVotes < 0){
echo "<font color='red'>".$totalVotes." votes</font>";
}