How to display count of submitted radio button values using PHP [duplicate] - php

This question already has answers here:
Combine group by and count mysql
(2 answers)
Closed 5 years ago.
I am trying to display the total number of submitted radio button value, in my previous form, there is a choice between "Male", "Female" for user to choose and submit, and I have a database to store the values (radiob).
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT radiob FROM playertest";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo $row["radiob"] . "<br>";
}
} else {
echo "0 results";
}
$conn->close();
I have my code above only display all the items in the database under radiob,
Male
Male
Female
Is there anyway that I can display it with the total count?
Would want it to look like:
Male: 2
Female: 1

Use an Aggragage query with count
"SELECT count(id) as total, radiob FROM playertest GROUP BY radiob ";
I suggest adding an Auto Increment ID field as the primary key if you don't already have it.
This is known as a surrogate key in the Database world, and as your table grows you will really want to have one so you can properly refer to a row in other queries.
if you don't like that you can do
if ($result->num_rows > 0) {
$rows = [];
while($row = $result->fetch_assoc()) {
$rows[] = $row["radiob"];
}
}
$totals = array_count_values($rows);
array_count_values() returns an array using the values of array as keys and their frequency in array as values.
http://php.net/manual/en/function.array-count-values.php
SO $rows should be like this
['male','male', 'female']
And array_count_values will give you this
['male' => 2, 'female' => 1]
Now if you want rows to contain more data such as
while($row = $result->fetch_assoc()) {
$rows[] = $row; //assume row is ['name'=>'foo', 'radiob' => 'male']
}
You can first do array_column such as ( to unwrap it )
$totals = array_count_values(array_column($rows, 'radiob'));
array_column() returns the values from a single column of the input, identified by the column_key. Optionally, an index_key may be provided to index the values in the returned array by the values from the index_key column of the input array.
http://php.net/manual/en/function.array-column.php
In summery the best way is to Aggregate it using the query, but you may have other data besides this you need ( such as name ), in that case do the second method.
Cheers!

Here is a possible solution. There are various ways to do it and I am not 100% certain of the output you want. But this might get you started. I added variables to hold the integer values of the male/female counts. I put them in an array with a key value that matches the values in your database. Then in each loop, the value is incremented on the total of the array element matching the DB row value. At the end I echo the two totals.
$sql = "SELECT radiob FROM playertest";
$result = $conn->query($sql);
$array[ 'Male' => 0, 'Female' => 0 ];
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$array[$row["radiob"]]++;
echo $row["radiob"] . "<br>";
}
} else {
echo "0 results";
}
$conn->close();
echo "Male {$array['Male']}\n";
echo "Female {$array['Female']}\n";

You should modify the code using a group by sentence to look like this
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT radiob,COUNT(*) as total FROM `playertest` group by radiob";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo $row["radiob"] . ": ".$row["total"]."<br>";
}
} else {
echo "0 results";}
$conn->close();
?>

Related

Mysql query don't get first row in PHP [duplicate]

This question already has answers here:
mysqli ignoring the first row in a table
(4 answers)
Closed 1 year ago.
I trying to get the latest orders in my database and show in php frontend.
The problem is when i print the data, the first element in the array is not appear.
Example code
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myDatabase";
$db = new mysqli($servername, $username, $password, $dbname);
$counter = 0;
$query = "SELECT * FROM `orders` WHERE `supplier` = '".session('email')."' ORDER BY `id_order` DESC";
if ($result = $db->query($query)){
if($result->num_rows > 0) {
$row = $result->fetch_assoc();
$ordersArray = array();
// Set orders data to ordersArray
while($row = $result->fetch_assoc()){
$name = $row["name"];
$orderID = $row["id_order"];
$ordersArray[] = array('id_order'=> $orderID,
'name'=> $name, );
}
foreach($ordersArray as $row){
if( $counter <= 4 ){
echo ($row["name"]);
echo ($row["id_order"]);
$counter = $counter + 1;
}
}
} else {
echo ('<tr><td>No tienes ordenes recientes</td></tr>');
}
}
$db->close();
Example output
4
3
2
1
I have a fifth value in the database that should be displayed first, but it does not appear
You fetch the first row already before the while loop starts...
$row = $result->fetch_assoc(); // << first row feteched here
$ordersArray = array();
// Set orders data to ordersArray
while($row = $result->fetch_assoc()){
Remove the random fetch:
$row = $result->fetch_assoc();
Making this call moves the result pointer up but you're not adding this row to $ordersArray.
Alternatively, if for some reason you do need to access the first row outside your while loop, either add the data to the new array or use $result->data_seek(0) to reset the pointer.

Is it possible to loop through each row of a table in a database

I'm trying to loop through each row of a table in a database, then once I'm on a particular row get the value of a certain column. Is this possible? I've done a couple Google searches but nothing really concrete. I try using the mysqli_fetch_array() function but when I do I get the results of a column. I want to target each row. The code I have so far gets me the "nid" column. That's not what I want. I want to iterate through each row.
<?php
$serverName = "localhost";
$username = "user1";
$password = "sp#99#1";
$databaseName = "developer_site";
// Connection
$connection = new mysqli($serverName, $username, $password, $databaseName);
// Check Connection
if ($connection->connect_error) {
die("Connection failed:" . $connection->connect_error);
} // line ends if statement
$queryNodeRevision = "SELECT nid FROM node_revision";
// line above creates variable $queryNodeRevision > selects column "nid" from table "node_revision"
$results = mysqli_query($connection, $queryNodeRevision) or die("Bad Query: $results");
while ($row = mysqli_fetch_array($results)) {
echo "NID: ";
echo $row['nid'];
echo "<br/>";
}
?>
You can select rows by a certain condition with an SQL query alone and also select all columns.
SELECT * FROM node_revision where condition;
condition could be anything. For example another_row = 'something'.
But if, for some reason, you need to process the nid inside your php script to know if that row is the "particular" one you're searching, then you just select all the columns, or the ones you need.
$queryNodeRevision = "SELECT nid, col1, col2 FROM node_revision";
$results = mysqli_query($connection, $queryNodeRevision) or die("Bad Query: $results");
while ($row = mysqli_fetch_array($results)) {
if (condiiton) {
echo "Particular: ".$row['nid']
." ".$row['col1']
." ".$row['col2'];
}
}
condition could be something like $row['nid'] == 123 for example.
Hope it helps.

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();

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.

MySQL with php, displaying 50 most recent

I have a database which simply records words in a table in a single column (with RID beside). All I want to do is display the words in order with a space in between (which I have a working code for below)
<?php
$mysql_host = "mysql1.000webhost.com";
$mysql_database = "db name";
$mysql_user = "user";
$mysql_password = "pass";
// Create connection
$conn = new mysqli( "mysql1.000webhost.com","databaseuser","password","databasename");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = 'SELECT Words FROM Poetry ';
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row["Words"]. " ";
}
} else {
echo "0 results";
}
?>
HOWEVER. I want to only display a set amount (say 50) of the MOST RECENT db entries (i.e) the 50 with the highest RID. Can somebody quickly tell me what code I need (in php) which will display the 50 most recent on a web page?
Thanks!
Don't do it with PHP, just add it to your query.
$sql = 'SELECT Words FROM Poetry order by RID desc limit 50';
This query will order the result set by RID descending, most recent first I'm assuming, and limit the result set to 50 records.
You can use
SELECT Words FROM Poetry order by RID desc limit 0,50
0 is the offset and 50 is limit.u can dynamically change those value if needed.
For the better security purpose You can use mysqli prepared statements.
You can see dynamically-bind_param-array-mysqli for Dynamically Bind Params
Try saving it in a variable and echoing it after your while statement.
Something like this
$all_words = '';
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$all_words = "$all_words, $row['Words']";
}
echo"$all_words";
} else {
echo "0 results";
}

Categories