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);
Related
I am a beginner programmer and I am trying to find the average user rating of vendor 2.
My steps are as follows:
1. User 'Jimmy' gives a rating of 3 to vendor 2 (ratings are out of 5)
2.TABLE vendoratings is updated
3. ratingstot.php then calculates the total sum of ratings and the number of responses for ALL vendors before updating TABLE vendortotalratings shown below
4.User 'Jimmy' clicks on 'View average user rating'
5. The values totalratings and totalno are retrieved and divided in Javascript
var average= totalratings/totalno
6. totalno is displayed to user Jimmy. END
Question
1. I need help forming the for or while loop in ratingstot.php to calculate both ratings and no. of responses belonging to vendor X before inserting them in vendortotalratings table for every vendor.
ratingstot.php
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
error_reporting(E_ERROR);
try{
//Database connection
$conn = new mysqli("localhost", "XXXXXXXX_XXX", "XXXXXXXX", "XXXXXXXX");
//Unsure how to loop this to make vendor new value every loop
for($i=0; $i<=6; $i++){
$vendor = ??
//Calculate sum of ratings from table ratings
$result = $conn->query("SELECT SUM(ratings) FROM ratings WHERE vendorid = '".$vendorid."' ");
$row = mysqli_fetch_array($result);
$totalratings = $row[0];
//Calculate no. of responses (by counting no. of rows)
$result1 = $conn->query("SELECT * FROM ratings WHERE vendorid = '" . $vendorid."' ");
$totalno = mysqli_num_rows($result);
//inserting the results into the table
$query = " UPDATE vendortotalratings SET ";
$query .= " totalratings = '". $totalratings ."', totalno='".$totalno."' ";
$query .= " WHERE vendorid = '". $vendorid ."'";
$result2 = $conn->query($query);
}
echo($outp);
}
catch(Exception $e) {
$json_out = "[".json_encode(array("result"=>0))."]";
echo $json_out;
}
?>
I have no idea how to loop this, are there any easier steps to calculate average of ratings for each vendors?
Instead of all these complicated things, you can simplify the required solution like this:
(Assumption: I'm assuming that vendorid, ratings, totalratings and totalno columns are of type INT)
Use the below statement/query to get the totalratings and totalno corresponding to each vendorid.
$result = $conn->query("SELECT vendorid, SUM(ratings) as totalratings, COUNT(userid) as totalno FROM vendorratings GROUP BY vendorid");
Now loop through the $result result set using while() loop.
while($row = $result->fetch_array()){
...
}
In each iteration of above while() loop, check if the vendorid value already exists or not. If it exists, then UPDATE the row with new totalratings and totalno, otherwise INSERT a new row comprising of vendorid, totalratings and totalno.
while($row = $result->fetch_array()){
$res = $conn->query("SELECT vendorid FROM vendortotalratings WHERE vendorid = " . $row['vendorid']);
if($res->num_rows){
// Update the existing row
$conn->query("UPDATE vendortotalratings SET totalratings = ".$row['totalratings'].", totalno = ".$row['totalno']." WHERE vendorid = ".$row['vendorid']);
echo "Affected rows: " . $conn->affected_rows . '<br />';
}else{
// Insert a new row
$res = $conn->query("INSERT INTO vendortotalratings VALUES(".$row['vendorid'].", ".$row['totalratings'].",".$row['totalno'].")");
if($res) echo "New row inserted <br />";
}
}
So the complete code of try-catch block would be like this:
// your code
try{
//Database connection
$conn = new mysqli("localhost", "XXXXXXXX_XXX", "XXXXXXXX", "XXXXXXXX");
$result = $conn->query("SELECT vendorid, SUM(ratings) as totalratings, COUNT(userid) as totalno FROM vendorratings GROUP BY vendorid");
while($row = $result->fetch_array()){
$res = $conn->query("SELECT vendorid FROM vendortotalratings WHERE vendorid = " . $row['vendorid']);
if($res->num_rows){
// Update the existing row
$conn->query("UPDATE vendortotalratings SET totalratings = ".$row['totalratings'].", totalno = ".$row['totalno']." WHERE vendorid = ".$row['vendorid']);
echo "Affected rows: " . $conn->affected_rows . '<br />';
}else{
// Insert a new row
$res = $conn->query("INSERT INTO vendortotalratings VALUES(".$row['vendorid'].", ".$row['totalratings'].",".$row['totalno'].")");
if($res) echo "New row inserted <br />";
}
}
}catch(Exception $e) {
$json_out = json_encode(array("result"=>0));
echo $json_out;
}
The question doesn't clarify how the records are first inserted in vendortotalratings table. So, assuming that there is already a record in this table for each vendor, you don't have to write a whole new loop.
Updating vendortotalratings:
SQL can take care of calculating the total ratings and their counts in a single query which can then replace the loop that you have.
UPDATE vendortotalratings vtr
INNER JOIN
(
SELECT vendorid, SUM(ratings) AS sumratings, COUNT(ratings) AS countratings
FROM vendoratings
GROUP BY vendorid
) vr
ON vtr.vendorid = vr.vendorid
SET
vtr.totalratings = vtr.totalratings + vr.sumratings
,vtr.totalno = vtr.totalno + vr.countratings
Computing averages:
As for your second question, to compute the average, you could run the following query which will give you the run-time result:
SELECT vendorid, totalratings, totalno,
CAST((totalratings/totalno) AS DECIMAL(10, 2)) AS avgrating
FROM vendortotalratings;
The variable avgrating can be accessed directly in PHP by using $row['avgrating'] if you're fetching an associative array from the results, or by using the appropriate index number, which in this case should be $row[3]
need to get row content from a mysql select statement. Currently starting at high id and desc. Need to take the highest id and get it, and the next 15 in line, and need to store them as variables. Here is an example:
$servername = "localhost";
$username = "_p";
$password = "1";
$dbname = "w";
mysql_connect("localhost", "p", "s") or die(mysql_error());
mysql_select_db("p") or die(mysql_error());
$highest_id = mysql_result(mysql_query("SELECT MAX(id) FROM NE2"), 0);
$result = mysql_query("SELECT content, id FROM NE2 order by ID desc LIMIT 15 ");
while($row[0] = mysql_fetch_array($result)){
echo $row[0]['content'];
You could do it with one query and access the top 16 ids, (the max id and the 15 next ids)
$servername = "localhost";
$username = "_p";
$password = "1s";
$dbname = "wc";
mysql_connect($servername, $username, $dbname) or die(mysql_error());
mysql_select_db("we_ppp") or die(mysql_error());
// Let's get the 16 first highest id's and their content
// Why 16 ? We want the highest and the 15 next
$result = mysql_query("SELECT content, id FROM SEARCH2 order by ID desc LIMIT 0, 16");
// Now it's easied to handle if we just stack the result in a big array
$data_array = array();
while($row = mysql_fetch_array($result)) {
$data_array[] = $row;
}
// Now we have $data_array[0] to $data_array[15] (the 16th row) each one containing
// an associative array resulting from the mysql_fetch_assoc().
// Now if I want the highest id :
$highest_id = $data_array[0]['id'];
$highest_content = $data_array[0]['content'];
// And the next 15 are
for($i = 1; $i < 16; $i++) { // We start at the second line until the 16th (numer 15)
echo $highest[$i]['id'];
echo $highest[$i]['content'];
}
// Now you do whatever you want with $highest and the next ones
The code will be more readable here :
http://pastebin.com/jGF94WJ2
use it like this
$result = mysql_query("SELECT content, id FROM S_ENGINE2 order by ID desc LIMIT 15");
if (mysql_num_rows($result) > 0)
{
while($row = mysql_fetch_array($result))
{
echo $row['content']."<br>";
}
}
may this will help you
The while loop executes row by row, and at an instance you could have only one row (just like array index), so do like
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo $row["id"];
echo $row["contetnt"]);
}
NOTE: mysql_* is deprecated and is not advised . Use PDO for secure database interations
I am trying to make the link <a href='{$_SERVER['PHP_SELF']}?del=true&orderid={$row['orderid']}' style='color:black;' onclick='return show_confirm();'>Delete</a>
delete the specific row from the MSSQL table using the while function. Currently, the bottom code works fine and deletes the specific row from the table, but I would now like it to unlink a file from the sharedstorage folder. The file that gets unlinked has it's filename stored in the name column for that table row. Each table row has a name column that contains a unique file's name from the file that is located in the sharedstorage folder.
My problem in simple terms is when a table row gets deleted, the file for that row in my website's sharedstorage folder remains and does not get deleted with the row.
Here is the code for when the delete link is hit for that specific row:
// delete from table
if ($_GET['del'] == 'true') {
// cast id as int for security
$id = (int) $_GET['orderid'];
// delete row from table
$sql = "DELETE FROM shareddrive WHERE orderid = '$id'";
$result = mssql_query($sql, $conn) or die(mssql_get_last_message());
// select the info, ordering by usort
$sql = "SELECT orderid, name, type FROM shareddrive ORDER BY orderid";
$result = mssql_query($sql, $conn) or die(mssql_get_last_message());
// initialize a counter for rewriting usort
$job_pos_sortt = 1;
// while there is info to be fetched...
while ($r = mssql_fetch_assoc($result)) {
$job_poss = $r['orderid'];
// update the usort number to the one in the next number
$sql = "update shareddrive SET orderid = '$job_pos_sortt' WHERE name = '$job_poss'";
$update = mssql_query($sql, $conn) or die(mssql_get_last_message());
// inc to next avail number
$job_pos_sortt++;
} // end while // end if del
}
All help is greatly appreciated.
// delete from table
if ($_GET['del'] == 'true') {
// cast id as int for security
$id = (int) $_GET['orderid'];
// delete row from table
$file = mssql_fetch_array(mssql_query("select name from shareddrive where orderid = $id"));
unlink($file[0]);
$sql = "DELETE FROM shareddrive WHERE orderid = '$id'";
$result = mssql_query($sql, $conn) or die(mssql_get_last_message());
// select the info, ordering by usort
$sql = "SELECT orderid, name, type FROM shareddrive ORDER BY orderid";
$result = mssql_query($sql, $conn) or die(mssql_get_last_message());
// initialize a counter for rewriting usort
$job_pos_sortt = 1;
// while there is info to be fetched...
while ($r = mssql_fetch_assoc($result)) {
$job_poss = $r['orderid'];
// update the usort number to the one in the next number
$sql = "update shareddrive SET orderid = '$job_pos_sortt' WHERE name = '$job_poss'";
$update = mssql_query($sql, $conn) or die(mssql_get_last_message());
// inc to next avail number
$job_pos_sortt++;
} // end while // end if del
}
Hi I'm new in PHP need some help, i want to generate auto registration code like this (e.g: 0001, 0002, ..) form data base if available in database auto plus one in last number if not start from 0000 it go at 9999 and stop
my sql table as
id | regisCode | title
query is
$query = mysql_query("Select * from accounts");
$result = mysql_num_rows($query);
if ($result > 0){
$row = mysql_fetch_array ($result);
} else{
$new = 0000;
}
$account = substr('0000', 1);
$faccount = 1+$account;
echo "<h1>". $faccount ."</h1>";
sorry for poor english
$query = "SELECT MAX(cast(registration_code as decimal)) id FROM accounts ";
if($result = mysql_query($query))
{
$row = mysql_fetch_assoc($result);
$count = $row['id'];
$count = $count+1;
$code_no = str_pad($count, 4, "0", STR_PAD_LEFT);
}
This will generate 0000,0001,0002...wen it will reach to 0099 it will generate 0100..
I am using the following MySQL query to generate a table for users in a database. The query is designed to just return one row for each user, even though there are multiple rows for each user. This works fine, however I also need to calculate the number of unique entries for each user, to enter into the table where it states HERE. Do I need to use another query to return the count for all entries, and if so how do I integrate this with the code I already have?
$query="SELECT from_user, COUNT(*) AS num FROM tracks GROUP BY from_user ORDER BY COUNT(*) DESC";
$result=mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
$user = $row['from_user'];
echo "<tr>";
echo "<td>".$user."</td>";
echo "<td>uploads (**HERE**)</td>";
echo "<td>favourites (count)</td>";
echo "</tr>";
}
?>
</table>
Because you've already created the custom field 'num', you can use that to get the count!
Add the following line after user = ...
$count = $row['num'];
Then you can
echo "<td>uploads ($count)</td>";
It miss your table stucture to know your field name, but, if i well understand your question you can use count + distinct in mysql.
You can check this answer too.
SELECT DISTINCT(from_user) AS user,
COUNT(from_user) AS num
FROM tracks
GROUP BY from_user
ORDER BY num DESC";
For the second problem you can doing a second query, or do a join tracks .
I think, in your case it's easier to you to do se second query inside the loop to get all detail from 'user' result.
$query1="SELECT DISTINCT(from_user), COUNT(*) AS num
FROM tracks
GROUP BY from_user
ORDER BY COUNT(*) DESC";
$query2="SELECT * FROM tracks";
$result1=mysql_query($query1) or die(mysql_error());
$result2=mysql_query($query2) or die(mysql_error());
$user_array = array();
while ($row = mysql_fetch_array($result1)) {
$user = $row['from_user'];
$num = $row['num'];
$uploads_array = array();
while ($sub_row = mysql_fetch_array($result2)) {
if( $sub_row['from_user'] == $user ) {
//for example only due to the unknown structure of your table
$uploads_array[] = array(
"file_name" => $sub_row['file_name'],
"file_url" => $sub_row['file_url']
);
}
}
$user_array[] = array(
"name" => $user,
"num_entry" => $num,
"actions" => $uploads_array
);
}
// now the table with all data is stuctured and you can parse it
foreach($user_array as $result) {
$upload_html_link_arr = array();
$user = $result['name'];
$num_entry = $result['num_entry'];
$all_actions_from_user_array = $result['actions'];
foreach($all_actions_from_user_array as $upload) {
$upload_html_link_arr[] = sprintf('%s', $upload["file_url"],$upload["file_name"]);
}
$upload_html_link = implode(', ',$upload_html_link_arr);
$full_row = sprintf("<tr><td>%s</td><td>uploads : %s</td><td>favourites (%d)</td></tr>", $user, $upload_html_link, $num_entry);
// now just echo the full row or store it to a table for the final echo.
echo $full_row;
}
I hope this help, mike