Get the sum of all the hours [closed] - php

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I am doing a project with PHP and MySQL. I have this problem.
This is my code
<?php
$proyecto = $_POST['id'];
$servername = "localhost";
$username = "dbuser";
$password = "dbpass";
$dbname = "proyectos";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT `horas`, `trabajador` FROM `horas` WHERE `proyecto` LIKE '$proyecto' ";
$result = $conn->query($sql);
$conn->close();
?>
It takes a parameter from a post request and do a search in the database database looks like this:
So I want to get as result the sum of all the hours (horas column) that are made by the same worker (trabajador column). Example of result:
Prueba1: 8 hours in total, Prueba2: 9 hours in total
I am stuck trying to dinf they way to sum when 1 or more fields must be the same, I hope someone can help me with this. Thanks!

You must use sum function to add the number of hours for each worker along with GROUP BY clause to group workers.Formatted Query is like:
SELECT SUM(horas) AS Hours,`trabajador`
FROM `horas`
WHERE `proyecto`
LIKE '%".$proyecto."%'
GROUP BY `trabajador`
In your code,
$select = "
SELECT SUM(horas) AS Hours, `trabajador`
FROM `horas`
WHERE `proyecto` LIKE ?
GROUP BY `trabajador`
";
$sth = $conn->prepare($select);
$sth->execute(['%'.$proyecto.'%']);
/* Fetch all of the remaining rows in the result set */
print("Fetch all rows in the result set:\n");
$result = $sth->fetchAll(\PDO::FETCH_ASSOC);
print_r($result);
Note: You better switch to MYSQL prepared statements to keep your data secure and for better database connectivity practices.

Note answer by maniksidana explains how to use SUM() and GROUP BY and is in general valid. However, it mixes mysqli and PDO approches. Here you have sample how to use it with mysqli (as your question uses it) and why it's important to use prepared statements at all. Just add some dummy data to your table end execute it. Personally I'd suggest to go with PDO only instead, but it's matter of taste.
INSERT INTO `horas` (`fecha`, `horas`, `proyecto`, `trabajador`) VALUES
('2020-08-08', 3, 'foo bar baz', 'Joker1'),
('2020-08-09', 4, 'ello pomello', 'Joker2');
<?php
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$proyecto = "ProyectpDePrueba'; DELETE FROM horas WHERE 1; -- bye bye data";
$proyecto = "ProyectpDePrueba";
$proyecto = "ProyectpDePrueba' OR 1=1 -- no more execution";
// Wrong
$sql = "
SELECT SUM(horas) AS Hours, `trabajador`
FROM `horas`
WHERE `proyecto` LIKE '$proyecto'
GROUP BY `trabajador`
";
$result = $conn->query($sql);
echo '<pre>Wrong' . PHP_EOL;
while ($row = mysqli_fetch_assoc($result)) {
print_r($row);
}
// Correct
$sql = "
SELECT SUM(horas) AS Hours, `trabajador`
FROM `horas`
WHERE `proyecto` LIKE ?
GROUP BY `trabajador`
";
$stmt = $conn->prepare($sql);
$stmt->bind_param('s', $proyecto);
$stmt->execute();
$result = $stmt->get_result();
echo PHP_EOL . 'Corrcet' . PHP_EOL;
while ($row = $result->fetch_assoc()) {
print_r($row);
}
$conn->close();

Related

How to fetch a single row from a MySQL DB using MySQLi with PHP? [duplicate]

This question already has answers here:
Single result from database using mysqli
(6 answers)
Closed 2 years ago.
I am using PHP with MySQli and I want to fetch a single row from the whole SQL DB, which fits in my condition. Just for a note, this is what my current database looks like :
I want to get that single row where, eg. txnid column's value == $txnid (a variable). I tried to build the SQL Query which would fit my requirements, and here's how it looks like : $sql = "SELECT * FROM 'table1' WHERE 'txnid' = " . $txnid;. When I raw-run this Query in phpMyAdmin, it works as expected. I just want to know, after I run the Query in PHP, how to fetch that row's data which came in as response from the Query using MySQLi?
This is the code which I am using to run the Query :
$servername = "localhost";
$username = "XXXXXXXXXXXXXX";
$password = "XXXXXXXXXXXXXX";
$dbname = "XXXXXXXXXXXXXXXX";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$txnid = $_GET['id'];
$sql = "SELECT * FROM `testtable1` WHERE `txnid` = " . $txnid;
if ($conn->query($sql) === TRUE) {
echo ""; //what should I do here, if I want to echo the 'date' param of the fetched row?
} else {
echo "Error: " . $sql . "<br>" . $conn->error . "<br>";
}
Add LIMIT 1 to the end of your query to produce a single row of data.
Your method is vulnerable to SQL injection. Use prepared statements to avoid this. Here are some links you can review:
What is SQL injection?
https://en.wikipedia.org/wiki/SQL_injection
https://phpdelusions.net/mysqli_examples/prepared_select
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = new mysqli($servername, $username, $password, $dbname);
$conn->set_charset("utf8mb4");
$txnid= $_GET['name_of_txnid_input_field'];
// prepare and bind
$stmt = $conn->prepare("SELECT * FROM `testtable1` WHERE `txnid` = ? LIMIT 1");
$stmt->bind_param("i", $txnid);
// set parameters and execute
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
echo $row['date_field_you_want_to_display'];
$txnid = $_POST['txnid'];
$sql = "SELECT * FROM tableName WHERE txnid = $txnid";
$result = $conn->query($sql);

PHP I have a database connect file, should i put my database querie functions in the same file [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
to explain my question better, i have two files: dbh.inc.php
$dbServername = "localhost";
$dbUsername = "xxxxx";
$dbPassword = "secret";
$dbName = "databasename";
$conn = mysqli_connect($dbServername, $dbUsername, $dbPassword, $dbName);
mysqli_set_charset($conn,"utf8");
if (!$conn) {
die("Connection failed: ".mysqli_connect_error());
}
$table1 = "users";//1
$table2 = "userprofile";//2
$table3 = "twofactorauth";//3
And: database-query.func.php
function selectdb($data, $values, $url) {
include ('dbh.inc.php');
extract($data);
extract($values);
switch ($data['table']) {
case '1':
$table = $table1;
break;
case '2':
$table = $table2;
break;
case '3':
$table = $table3;
break;
}
$sql = "SELECT $rows FROM $table WHERE $where;";
print_r($sql);
die();
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
mysqli_stmt_close($stmt);
mysqli_close($conn);
header("Location: ".$url."?error=sqlerror");
die();
} else {
$amount = str_repeat('s', count($values));
$values = array_values($values);
mysqli_stmt_bind_param($stmt, $amount, ...$values);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$getResult = mysqli_fetch_assoc($result);
mysqli_stmt_close($stmt);
mysqli_close($conn);
$new = array_push($getResult, 'true');
return $getResult;
}
}
So the first holds database connection, and the latter has dynamic querys for insert, update and select for the moment. And i am wondering should i combine the two files, to one. Since every time i need my connect i always use one of my querys and same on the other way around?
Also 2 bonus questions: as you see in my connect file i have my table names and i use numbers in my other files and in the functions connect numbers to names.
Lastly should i use PDO, why?
To answer your question in general - yes, you can put a helper function in the same file where sql connection is made.
However, the code of your actual function is questionable at the very least. Or, to tell you truth, your function selectdb() is a torture for a programmer and shouldn't be stored anywhere. Stick to natural SQL queries written as is. You don't need numbers to represent tables. You don't need $rows variable. Everything could be written right in the SQL string. All you will need is a simple helper function that would reduce the amount of code required to run a query.
Here is an example of such mysqli include file
Once it's included in in your script, you can use it to run any mysql query, to any table, with any list of variables. Check out the following example (you can copy and paste the following code block to your file and run it as is):
<?php
require 'mysqli.php';
#Create a temporary table
$conn->query("CREATE temporary TABLE tmp_mysqli_helper_test
(id int auto_increment primary key, name varchar(9))");
# populate it with sample data
$sql = "INSERT INTO tmp_mysqli_helper_test (name) VALUES (?),(?),(?)";
$stmt = prepared_query($conn, $sql, ['Sam','Bob','Joe']);
echo "Affected rows: $stmt->affected_rows\n";
echo "Last insert id: $conn->insert_id\n";
# Getting rows in a loop
$sql = "SELECT * FROM tmp_mysqli_helper_test WHERE id > ?";
$res = prepared_query($conn, $sql, [1])->get_result();
while ($row = $res->fetch_assoc())
{
echo "{$row['id']}: {$row['name']}\n";
}
# Getting one row
$id = 1;
$sql = "SELECT * FROM tmp_mysqli_helper_test WHERE id=?";
$row = prepared_query($conn, $sql, [$id])->get_result()->fetch_assoc();
echo "{$row['id']}: {$row['name']}\n";
# Update
$id = 1;
$new = 'Sue';
$sql = "UPDATE tmp_mysqli_helper_test SET name=? WHERE id=?";
$affected_rows = prepared_query($conn, $sql, [$new, $id])->affected_rows;
echo "Affected rows: $affected_rows\n";
# Getting an array of rows
$start = 0;
$limit = 10;
$sql = "SELECT * FROM tmp_mysqli_helper_test LIMIT ?,?";
$all = prepared_query($conn, $sql, [$start, $limit])->get_result()->fetch_all(MYSQLI_ASSOC);
foreach ($all as $row)
{
echo "{$row['id']}: {$row['name']}\n";
}
As you can see, a proper helper function can keep all the flexibility and readability of SQL and reduce the amount of code at the same time.

Update points of a user in mysql database using php [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am trying to take a string username from my android app and use that username to add 5 points to that specific users account.
Example:
My database now: user_id name username password points
1 test test test 0
What I want: user_id name username password points
1 test test test 5
Here is the php code I'm using right now, something must be wrong with it:
<?php
$con = mysqli_connect("localhost", "id177667_root", "***", "id177667_loginb");
$username = $_POST["username"];
$sql = "UPDATE user ". "SET points = points + 5 ". "WHERE username = $username" ;
$response = mysqli_query($sql, $con);
?>
You confused the parameters for mysqli_query. It should be mysqli_query($con, $sql); instead. Also there are a couple of other problems - this should work:
<?php
$con = mysqli_connect("localhost", "id177667_root", "***", "id177667_loginb");
$username = mysqli_real_escape_string($con, $_POST["username"]);
$sql = "UPDATE user SET points = points + 5 WHERE username = '$username'" ;
$response = mysqli_query($con, $sql);
?>
As it was suggested, prepared statements are the preferred way to go. So you could do this... tested it now, and it works for me:
<?php
$points = 5;
// Connect to database (credentials should not be stored in code...)
$con = new mysqli("localhost", "id177667_root", "***", "id177667_loginb");
// Check if connection succeeded
if ($con->connect_error)
die("Connection error: " . $con->connect_error);
// Prepare statement
if ($st = $con->prepare("UPDATE user SET points = points + ? WHERE username = ?")) {
// Bind parameters (i for integer value, s for string)
$st->bind_param("is", $points, $_POST["username"]);
// Execute statement
$st->execute();
// Close statement
$st->close();
} else {
// Prepare failed: report error
die("Prepare failed: " . $con->error);
}
// Close DB connection
$con->close();
?>

Issue with JOIN in PHP MySQL

Having a bit of a struggle here with adding JOINs to a query. I am connecting to two separate databases (on the same server). For this reason, I am writing this mysqli simply and will convert to a prepared statement once it's working.
// REMOVED: DB VARIABLES
$conn = new mysqli($servername, $username, $password, $db_connective_data);
if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); }
$conn2 = new mysqli($servername, $username, $password, $db_resources);
if ($conn2->connect_error) { die("Connection failed: " . $conn2->connect_error); }
$sql = "SELECT * FROM downloads LEFT JOIN resource_data ON downloads.resource_id_REF=resource_data.resource_id WHERE downloads.user_basics_id_REF='$user_id'";
$result = $conn->query($sql);
$number_of_download_rows_returned = mysqli_num_rows($result) -1;
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$resource_id_REF[] = $row['resource_id_REF'];
$download_date[] = date('Y-m-d', strtotime($row['download_date']));
$resource_title[] = $row['resource_title'];
$resource_title_link[] = str_replace(" ", "-", $row['resource_title']);
}
}
$conn->close();
A query without a JOIN works fine (albeit without returning the resource_title):
$sql = "SELECT * FROM downloads WHERE downloads.user_basics_id_REF='$user_id' ORDER BY downloads.download_date DESC";
What am I missing here? The first code sample will return no results. The second one will return three.
Any assistance is greatly appreciated.
Here is a list of the different database names that I reference. As I stated, some data is in the "connective_data" db and some is in the "resources" db.
$db_connective_data = "connective_data";
$db_lists = "lists";
$db_messaging = "messaging";
$db_resources = "resources";
$db_users = "users";
I can't seem to get two of them connected. Am I missing something strikingly obvious here?
There is no need to create 2 connections if the databases are located on the same mysql server. You can simply reference tables from another database as databasename.tablename.
As a result, you can join 2 tables from 2 different databases as:
$sql = "SELECT * FROM yourdatabase1.downloads LEFT JOIN yourdatabase2.resource_data ON yourdatabase1.downloads.resource_id_REF=yourdatabase2.resource_data.resource_id WHERE yourdatabase1.downloads.user_basics_id_REF='$user_id'";
Obviously, you need to substitute your real database names for yourdatabase1 and yourdatabase2 in the above query.
Update: Are you sure you need so many databases? These seem to be tables to me, not databases.

Printing last 10 entries in database [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
So I'm working on a website that has a list of novels in a database with some basic info about them. I'd like to make a table of the most recent additions to the database. I'm using PHP and SQL and this is what I've got so far.
<?php
$servername = "localhost";
$username = "root";
$password = "password";
$database = "novels";
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Select ten most recent entries
SELECT `N_ID`, `NAME`, `DATE_RELEASED`, `GENRES` FROM basic_info ORDER BY N_ID DESC LIMIT 10
?>
I"m new to PHP And SQL so what I can gather is that I've made a connection to the database and have pulled the information from the latest 10 entries. Now I'm just not sure how to print them.
Any help is appreciated!
Try to use PDO if you can. Also you could use lower case for your columns to avoid case sensitivity issues.
You have to "wrap" your SELECT query in a variable (e.g. $sql) to be able to pass it in your php code.
error_reporting(E_ALL);
ini_set("display_errors", 1);
$servername = "localhost";
$username = "root";
$password = "password";
$database = "novels";
try {
//Make your connection handler to your database
$conn = new PDO("mysql:host=".$servername.";dbname=".$database, $username, $password, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING));
$sql = "SELECT `N_ID`, `NAME`, `DATE_RELEASED`, `GENRES` FROM basic_info ORDER BY N_ID DESC LIMIT 10";
$stmt = $conn->prepare($sql);
//Execute the query
$stmt->execute();
$result = $stmt->fetchAll();
//Fetch the results
foreach ($result as $row) {
echo '<p>'.$row['NAME'].'</p>';
}
} catch(PDOException $e) {
echo $e->getMessage();
die();
}

Categories