Get sum of row where username is the current user's name - php

This code just displays a blank webpage. Is there anything wrong with it? It is supposed to show the total points the logged in user has.
<?php
session_start();
$servername = "localhost";
$username = "root";
$password = "randompassword";
$dbname = "transactions";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$query = "SELECT sum(points) AS points FROM transaction WHERE username = '".mysqli_real_escape_string($conn,$_SESSION['username'])."'";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result);
print($row)
?>

You should enable the error_reporting like this
error_reporting(E_ALL);
ini_set("display_errors", 1);
transaction is a keyword in mysql. So use back tick ( ` ).
Instead of using direct substitution values, you could use below methods to avoid sql injection.
Using MySQLi (for MySQL):
$stmt = $dbConnection->prepare('SELECT * FROM employees WHERE name = ?');
$stmt->bind_param('s', $name);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// do something with $row
}
Please refer How can I prevent SQL-injection in PHP?

Related

How to use PHP SQL with where Clause? [duplicate]

This question already has answers here:
How to include a PHP variable inside a MySQL statement
(5 answers)
Closed 2 years ago.
I want to select an email from the DB which needs to return the related Account_ID
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "connected accounts details";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT acc_id FROM users
WHERE
email = $user_email";
$result = $conn->query($sql);
echo "$result";
$conn->close();
This code returns nothing, just blank.
While using the same connection/db data is being inserted in db successfully.
Try this code
// Php Sql Select From DB....
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "connected accounts details";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT `acc_id` FROM `users` WHERE `email` = ?";
$result->$conn->prepare($sql);
$result->bind_param('s',$user_email);
$result->execute();
$data = $result->get_result();
// Fetch all
$data->fetch_all(MYSQLI_ASSOC);
print_r($data);
$mysqli -> close();
// #link http://php.net/manual/en/mysqli-result.fetch-all.php
$sql = "SELECT acc_id FROM users
WHERE
email LIKE '%$user_email%' ";
$result = mysqli_query($conn, $sql);
$row = $result->fetch_assoc();
$id = $row['acc_id'];
echo "$id";
$conn->close();
Got the wanted Record, trying this way.
Thanks everyone answering on this post.

How to use ? in URL?

I am trying to figure out a way to have one PHP page to display all of my blog post but have the URL decide what post is requested from that database. Something kind of like this: localhost/bolg/posts.php?pid=1 In my database I have it set up to where each post has an ID associated with it. So what I want is something that put the pid=1 and put it in the MySQL code. Here is the PHP code of the post.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, title, content, date FROM posts where id =3";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<h1> ". $row["title"]. "</h1>". $row["content"]. "" . $row["date"] . "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
Assuming you enter example.com?pid=10 in the browser address bar, you can capture that variable pid using the $_GET (docs) array which PHP automatically fills for you when a page is called with a querystring.
Using your existing code as a start point you can
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
if (isset($_GET['pid'])) {
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
$sql = "SELECT id, title, content, date FROM posts where id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param('i', $_GET['pid']);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows > 0) {
// output data of each row
// while looop is not necessary, you are only returning one row
$row = $result->fetch_assoc();
echo "<h1> ". $row["title"]. "</h1>". $row["content"]. "" . $row["date"] . "<br>";
}
$conn->close();
} else {
echo "0 results";
}
Notice I took the liberty of amending your database access code to use prepared and parameterised query and binding the values to avoid SQL Injection Attack. You should always use this technique in the future

Query is TRUE when its not

Please be gentle with me i have just recently trying to learn PHP/SQL.
The problem is that the first query is ALWAYS TRUE when it shouldn't (base on what i know).
The query simply state to get the 'username' where betakey=$betakey provided by user. The fact that my datebase columns is still empty except column betakey doesn't make that query statement true at all.
Please help, maybe i am missing some knowledge on this.
<?php
header('Access-Control-Allow-Origin: *');
$firstName = $_GET['rfirstname'];
$lastName = $_GET['rlastname'];
$username = $_GET['rusername'];
$password = $_GET['rpass'];
$betakey = $_GET['rkey'];
$host="localhost"; // Host name
$db_username="**"; // Mysql username
$db_password="**"; // Mysql password
$db_name="**"; // Database name
$conn = mysqli_connect("$host", "$db_username", "$db_password","$db_name");
if (!$conn){
die ("Error: ".mysqli_connect_error());
}
$query1 = "SELECT username='$username' FROM users2 WHERE betakey='$betakey';";
$result_1 = mysqli_query($conn,$query1);
if(mysqli_num_rows($result_1) > 0){
echo 'Beta key is used';
}else{
$query2 = "UPDATE users2 SET firstName='$firstName',lastName='$lastName',username='$username',password='$password' WHERE betakey='$betakey'";
echo 'Registration Successful';
}
mysqli_close($conn);//Close off the MySQL connection to save resources.
?>
You have plenty of problems in your code. Let me help you fix some of them
You should learn how to properly open mysqli connection. You need to enable error reporting and set the correct charset.
You should never concatenate PHP variables into SQL query. Always use parameterized prepared statements instead of manually building your queries.
Your first SQL query has an error. username='$username' is meaningless and wrong. If all you want to do is check existence use COUNT(1) or something similar.
Here is my take on your fixed code:
<?php
header('Access-Control-Allow-Origin: *');
$firstName = $_GET['rfirstname'];
$lastName = $_GET['rlastname'];
$username = $_GET['rusername'];
$password = $_GET['rpass'];
$betakey = $_GET['rkey'];
$host = "localhost"; // Host name
$db_username = "**"; // Mysql username
$db_password = "**"; // Mysql password
$db_name = "**"; // Database name
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = new mysqli($host, $db_username, $db_password, $db_name);
$conn->set_charset('utf8mb4');
$stmt = $conn->prepare("SELECT COUNT(username) FROM users2 WHERE betakey=?");
$stmt->bind_param('s', $_GET['rusername']);
$stmt->execute();
$result_1 = $stmt->get_result();
$used = $result_1->fetch_row()[0];
if ($used) {
echo 'Beta key is used';
} else {
$stmt = $conn->prepare("UPDATE users2 SET firstName=?, lastName=?, username=?, password=? WHERE betakey=?");
$stmt->bind_param('sssss', $firstName, $lastName, $username, $password, $betakey);
$stmt->execute();
echo 'Registration Successful';
}

php delete record using id

This program is meant to delete a record when given the id.
php:
if ($_GET['type']=="file"){
$servername = "localhost";
$username = "****";
$password = "****";
$dbname = "****";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (mysqli_connect_error($conn)) {
die("Connection failed: " . mysqli_connect_error($conn));
}
$sql = "SELECT id,user, FROM CreationsAndFiles WHERE id =".$_GET['id']." LIMIT 1";
$result = mysqli_query($conn,$sql);
$row = mysqli_fetch_assoc($result);
if ($row['user'] == $login_session){
$sql = "DELETE FROM CreationsAndFiles WHERE id=".$_GET['id'];
if(mysqli_query($conn, $sql)){echo "deleted";}
}
mysqli_close($conn);
//header("location: index.php?page=CreationsAndFiles");
}
the header is type=file&id=9
there is a record where id=9
It for no apparent reason will not work.
Your SQL syntax is wrong;
SELECT id,user, FROM CreationsAndFiles...
^ extra comma
should be simply
SELECT id,user FROM CreationsAndFiles...
You may want to sanitize your input though, for example simply entering type=file&id=id will most likely do bad things.

phpMyAdmin: one table in database work, another doesn't

I've created an app were you can register as a user. You can sign up and then you're in the database "myAppDataBase" in "firsttable". A second table contains a list of lets say other important users that I manually created in the PHPmyAdmin-Website/"App". This table is called "secondtable".
My code to get the data is as follows:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "mydatabas";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}else{
//Print ("successfully connected");
}
$query = "SELECT * FROM firsttable";
$result = mysqli_query($conn, $query) or die("Error: " . mysqli_error($query));
$num = mysqli_num_rows($result);
$rows = array();
while ($r = mysqli_fetch_assoc($result))
{
$rows[] = $r;
Print ("sf");
}
Print json_encode($rows);
mysqli_close($conn);
?>
The only thing i changed was this line: THIS WORKS
$query = "SELECT * FROM firsttable";
But when I change it to this it won't work anymore.
$query = "SELECT * FROM secondtable";
Any help?
Change this:
mysqli_error($query)
With this:
mysqli_error($conn) // with your connection
Explanation:
mysqli_error() function needs connection link identifier not your query as param.
Mysqli_error PHP Manual
I SOLVED IT! Somehow, my second wasn't encoded the right way. I simply added this coder and it worked:
mysqli_set_charset($conn, 'utf8mb4');
Thanks for all you help though. ;)

Categories