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>";
}
}
Related
I've been trying to make my php code to show entries from my mysql database. I wanted to make it automatic in a sense that i wouldn't need to print the tables manually instead they would be printed according to an alogrythm, but it doesn't work like intended.
I've tried different ways of setting up the table but none of them worked, the furthest I got was to print one entry from the table, and spitting errors after it.
$base = $_POST["base"];
$connection = mysqli_connect("localhost","login","pass") or die("Impossible to connect to the database!");
$db = mysqli_select_db($connection, "database")or die("Impossible to download the database!");
$sql = "SELECT * FROM $base";
$mysqli_result = mysqli_query($connection, $sql);
$sql2 = "SHOW COLUMNS FROM $base";
$set1 = mysqli_query($connection, $sql2);
$colu = array();
while($db = mysqli_fetch_row($set1)){
$colu[] = $db[0]; }
$columns=implode("<br/>",$colu);
echo "<TABLE BORDER=1>";
echo "<TR><TH>$colu[0]</TH><TH>$colu[1]</TH><TH>$colu[2]</TH><TH>$colu[3]</TH><TH>$colu[4]</TH><TH>$colu[5]</TH></TR>";
while ($row = mysqli_fetch_array($set1)) {
$colu[0] = $row["echo $colu[0]"];
$colu[1] = $row["echo $colu[1]"];
$colu[2] = $row["echo $colu[2]"];
$colu[3] = $row["echo $colu[3]"];
$colu[4] = $row["echo $colu[4]"];
$colu[5] = $row["echo $colu[5]"];
echo "<TR><TD>$colu[0]</TD><TD>$colu[1]</TD><TD>$colu[2]</TD><TD>$colu[3]</TD><TD>$colu[4]</TD><TD>$colu[5]</TD></TR>";}
echo "</TABLE>";
mysqli_free_result($mysqli_result);
mysqli_close($connection); ?>
the $_POST[$base]; part works, Im guessing the issue is in the while loop as it doesnt complete once, and I'm lost as to why it doesnt want to work.
I see some problems in you script. If you want to fetch columns as heading and the content for the table body you are using the wrong result sets.
// next line make it possible to do sql insertion, and what if $base has no input?
$base = $_POST["base"];
// the die will never be reached
$connection = mysqli_connect("localhost","login","pass") or die("Impossible to connect to the database!");
$db = mysqli_select_db($connection, "database")or die("Impossible to download the database!");
// where is this query for?
$sql = "SELECT * FROM $base";
// where is this result being used
$mysqli_result = mysqli_query($connection, $sql);
$sql2 = "SHOW COLUMNS FROM $base";
$set1 = mysqli_query($connection, $sql2);
$colu = [];
// what if the table order chages? Best to use mysqli_fetch_assoc
while($db = mysqli_fetch_row($set1)){
$colu[] = $db[0];
}
// where do you use $comumns?
$columns = implode("<br/>", $colu);
echo "<TABLE BORDER=1>";
echo "<TR><TH>$colu[0]</TH><TH>$colu[1]</TH><TH>$colu[2]</TH><TH>$colu[3]</TH><TH>$colu[4]</TH><TH>$colu[5]</TH></TR>";
// you already fetched all record from set1
while ($row = mysqli_fetch_array($set1)) {
$colu[0] = $row["echo $colu[0]"];
$colu[1] = $row["echo $colu[1]"];
$colu[2] = $row["echo $colu[2]"];
$colu[3] = $row["echo $colu[3]"];
$colu[4] = $row["echo $colu[4]"];
$colu[5] = $row["echo $colu[5]"];
echo "<TR><TD>$colu[0]</TD><TD>$colu[1]</TD><TD>$colu[2]</TD><TD>$colu[3]</TD><TD>$colu[4]</TD><TD>$colu[5]</TD></TR>";
}
echo "</TABLE>";
mysqli_free_result($mysqli_result);
mysqli_close($connection); ?>
This biggest issue you have right now is this:
$base = $_POST["base"]
$sql = "SELECT * FROM $base";
$sql2 = "SHOW COLUMNS FROM $base";
This is a huge SQL Injection vulnerability, even if they pass just an empty string to this it's all bad. For example that would result in a query error and depending on your settings on the server and for error reporting, you may expose quite a bit of info. Just one example is a stack trace could contain DB passwords etc.
Instead of directly using user input make a whitelist like this:
$tables = ['user', 'user_meta', 'states']; //etc
$base = !empty($_POST["base"]) && false !== ($index = array_search($_POST["base"], $tables)) ? $tables[$index] : false;
if(!$base) die('Unknown table '.$_POST["base"]);
This way you are only using data you know the value of.
Variable reuse
Other then that, your variable names are causing a bunch of "code confusion". This is what happens if you have to generic of a variable name. Some examples:
$db = mysqli_select_db(...)
while($db = mysqli_fetch_row($set1)){ //overwriting db
...
}
//....................
while ($row = mysqli_fetch_array($set1)) {
$colu[0] = $row["echo $colu[0]"]; //overwriting $colu
This last one is also wrong because the row key will be something like:
$colu[0] = $row["echo name"];
Or something with a column name. Because you are re-using this variable ("variable confusion" ) on the next loop it will be the value of $row["echo $colu[0]"]; which will get put back into that. So lets assume this is correct without the echo and will use Name as the value.
//loop 1
$colu[0] = 'name';
$row['name'] = 'Tom';
//result
$colu[0] = 'Tom'
//loop 2
$colu[0] = 'Tom';
$row['Tom'] doesn't exist.
//result
$colu[0] = null; //undefined index warning
Cursor Reuse
You are also reusing the DB cursor $set1 and looping over it 2 times. I'm not sure about MySqli, but PDO won't allow you to do that. This is probably why the second loop is failing. I believe the second one should be $mysqli_result. It's a bit confusing because you do both queries then loop though one then the other. Instead of doing a query, looping through it. Then doing the other, and looping though that.
Instead you can do something like this:
//you can even query the DB for the table names
$tables = ['user', 'user_meta', 'states']; //etc
$base = !empty($_POST["base"]) && false !== ($index = array_search($_POST["base"], $tables)) ? $tables[$index] : false;
if(!$base) die('Unknown table '.$_POST["base"]);
$connection = mysqli_connect("localhost","login","pass") or die("Impossible to connect to the database!");
$db = mysqli_select_db($connection, "database")or die("Impossible to download the database!");
//---------query for the columns
$sql = "SHOW COLUMNS FROM `$base`";
$mysqli_result = mysqli_query($connection, $sql);
$columns = [];
while($row = mysqli_fetch_row($mysqli_result)){
$columns[] = $row[0];
}
//---------query for the data
//use the column result in the select part of query, because the column names
//come from the DB they are safe to use.
$sql = "SELECT `".implode('`,`', $columns)."` FROM `$base`"; //reuse sql (no longer needed)
$mysqli_result = mysqli_query($connection, $sql); //reuse results (no longer needed)
//fetch all data as assoc array. because we tied it to the results
//of the first query, the column names. We no longer need to map it.
$data = mysqli_fetch_all($mysqli_result, MYSQLI_ASSOC);
///output table and headers
echo "<table>";
echo "<thead>";
echo "<tr>";
//we can just loop over the columns and put them in the table head
foreach($columns as $key ){
echo "<th>$key</th>";
}
echo "</tr>";
echo "</thead>";
echo "<tbody>";
//loop over each row of data
foreach($data as $row){
echo "<tr>";
//loop over each "correlated" column
foreach($columns as $key ){
echo "<td>{$row[$key]}</td>";
}
echo "</tr>";
}
echo "</tbody>";
echo "</table>";
BONUS For getting the table names from the DB:
$sql = 'SELECT `TABLE_NAME` FROM `information_schema`.`TABLES` WHERE `TABLE_SCHEMA` LIKE "'.$database.'"';
$mysqli_result = mysqli_query($connection, $sql);
$tables = mysqli_fetch_all($mysqli_result, MYSQLI_NUM);
Hope that makes sense.
I'm having trouble with pulling database information from 'rownum' column and putting it into an array and then using that array information for my next query that randomly selects one line of the array and then displays it.
<?php
// Connect to database
include 'DB.php';
$con = mysqli_connect($host,$user,$pass);
$dbs = mysqli_select_db($databaseName, $con);
// Select Rownum to get numbers and only where there is no value in seen.
$firstquery = "SELECT rownum FROM num_image WHERE seen=''";
// If there are results store them here
$result = mysqli_query($firstquery) or die ("no query");
// Put the results taken from the table into array so it displays as: array(56, 44, 78, ...) etc...
$result_array = array();
while($row = mysqli_fetch_assoc($result))
{
$result_array[] = $row;
}
// Select the data I require
$query = mysqli_query("SELECT number, association, image_file, skeleton, sound, colour, comments FROM num_image WHERE rownum='$row' LIMIT 1;");
$test = mysqli_query("UPDATE num_image SET Seen='yes' WHERE rownum='$row';");
// Fetch Results of Query, Ignore test.
$arrayss = mysqli_fetch_row($query);
// Echo Results as a Json
echo json_encode($arrayss);
?>
I'm not sure what I have done wrong? Does the array have to be echoed and then my $query line calls that instead?
Updated code - Solved my problem
Thanks for tips guys, it helped me wrap my head around it and came up with a working solution.
<?php
// Connect to database
include 'DB.php';
$con = mysqli_connect($host,$user,$pass);
$dbs = mysqli_select_db($databaseName, $con);
// Select Rownum to get numbers and only where there is no value in seen.
$firstquery = "SELECT rownum FROM num_image WHERE seen=''";
// If there are results store them here
$result = mysqli_query($firstquery) or die ("no query");
// Put the results taken from the table into array so it displays as: array(56, 44, 78, ...) etc...
$result_array = array();
while($row = mysqli_fetch_assoc($result))
{
$result_array[] = $row;
}
for ($i = 0; $i < count($result_array); $i++) {
$all_rownums[] = implode(',', $result_array[$i]);
}
//pick a random point in the array
$random = mt_rand(0,count($all_rownums)-1);
//store the random question
$question = $all_rownums[$random];
// Select the data I require
$query = mysqli_query("SELECT number, association, image_file, skeleton, sound, colour, comments FROM num_image WHERE rownum='$question' LIMIT 1;");
$test = mysqli_query("UPDATE num_image SET Seen='yes' WHERE rownum='$question';");
// Fetch Results of Query, Ignore test.
$arrayss = mysqli_fetch_row($query);
// Echo Results as a Json
echo json_encode($arrayss);
?>
This part is what helped me solve it:
for ($i = 0; $i < count($result_array); $i++) {
$all_rownums[] = implode(',', $result_array[$i]);
}
Happy Dance
I am calculating AGE by DATE from DOB field, then I want to push it into AGE with correct age based on DOB . So As I debug The DOB calculating to AGE is works, but it cannot update AGE the code:
<?php
$servername = "localhost";
$username = "usernameexmaple";
$password = "passworking";
$dbname = "dbnameworking";
// Create connection
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id as ID, YEAR(CURRENT_TIMESTAMP) - YEAR(dob) - (RIGHT(CURRENT_TIMESTAMP, 5) < RIGHT(dob, 5)) as age
FROM regio_users";
$sql2 = ("UPDATE regio_users SET age = '$newage' WHERE id ='$newid' ");
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$newage = $row['age'];
$newid = $row['ID'];
$sql2 = ("UPDATE regio_users SET age = '$newage' WHERE id ='$newid' ");
$result2 = $conn->query($sql);
if ($result2){
echo "done"."<br>";
}
}
}
else {
echo "0 results";
}
$conn->close();
?>
It echos DONE for every ID but not updating anything at all.
You have used $result2 = $conn->query($sql); which is incorrect. You have to use $result2 = $conn->query($sql2); as $sql2 is the new query you formed.
This can be done with a single line SQL, rather than using PHP to loop through all the rows to only update the age:
UPDATE `regio_users` SET `age` = YEAR(CURRENT_TIMESTAMP) - YEAR(`dob`) - (RIGHT(CURRENT_TIMESTAMP, 5) < RIGHT(`dob`, 5));
As saty pointed, use correct variable name.
Check if autocommit is on. If not, make sure you commit the data. Check for its syntax in PHP.
I want to display data from all rows only for the column named 'text_notes' from my db.
And I want to loop that data in a p tag so that all data from column text_notes is displayed one by one till the end.
Below is the code I tried but it displays all the columns of the latest row and doesn't display the other rows.
I want the data from column 'text_notes' from all the rows to be displayed from latest at the bottom to the oldest at the top.
<?php
$query = "SELECT * FROM notes";
$conn = new mysqli(DBROOT,DBUSER,DBPASS);
$conn->select_db(DBNAME);
if ($conn == TRUE) {
$runQuery = $conn->query($query);
$resultNum = $runQuery->num_rows;
$result = $runQuery->fetch_array();
$resultRow = mysqli_fetch_row($runQuery);
$notes = $result['text_notes'];
for ($i = 0; $i < $resultNum;) {
echo "<p>".$resultRow[$i]."</p>";
$i++;
}
}
?>
$mysqli = new mysqli(DBROOT, DBUSER, DBPASS, DBNAME);
$query = "SELECT text_notes FROM notes";
$result = $mysqli->query($query, MYSQLI_STORE_RESULT);
// Cycle through the result set
$counter = 0;
while(list($text_notes) = $result->fetch_row())
echo "<p>";
$counter++;
echo $counter . " : ";
echo " $text_notes </p>";
// Free the result set
$result->free();
I think it works :) Thanks
I have a form which allows the user to set what the sort the data by in the table and if it increase or decreasing order
http://damiensplace.co.uk/test/requestTableDisplay.htm
However I want the user to choose to exclude a field (Age Grade) form set the variable but been racking my brain on how to do this but only way I come up with is not neat as I basically need to write two lots of code am I missing a trick?
<html><head><title>MySQL Table Viewer</title></head><body>
<?php
$db_host = '****';
$db_user = '***';
$db_pwd = '***';
$sortOn = $_POST['SortOn'];
$sortIn = $_POST['SortIn'];
$database = '****';
$table = '***';
if (!mysql_connect($db_host, $db_user, $db_pwd))
die("Can't connect to database");
if (!mysql_select_db($database))
die("Can't select database");
// sending query
$result = mysql_query("SELECT * FROM {$table} order by {$sortOn} {$sortIn}");
if (!$result) {
die("Query to show fields from table failed");
}
$fields_num = mysql_num_fields($result);
echo "<h1>Table: {$table}</h1>";
echo "<table border='1'><tr>";
// printing table headers
for($i=0; $i<$fields_num; $i++)
{
$field = mysql_fetch_field($result);
echo "<td>{$field->name}</td>";
}
echo "</tr>\n";
// printing table rows
while($row = mysql_fetch_row($result))
{
echo "<tr>";
// $row is array... foreach( .. ) puts every element
// of $row to $cell variable
foreach($row as $cell)
echo "<td>$cell</td>";
echo "</tr>\n";
}
mysql_free_result($result);
?>
</body></html>
If someone can point me in the right direction I would be most grateful
Pretty simple. Instead of running this query:
SELECT * FROM {$table} order by {$sortOn} {$sortIn}
run this one:
"SELECT hats, cats, margarine FROM {$table} order by {$sortOn} {$sortIn}
...where hats, cats and margarine are to be replaced by fields in your table. You can specify any number of fields in this way, even down to grabbing only a single field.
You should have your query as follows:
SELECT (columns) FROM (table)
Do not SELECT all, it appears you only want specific columns.