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();
?>
Related
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();
Ok so I realized this probably looks crazy to good programers but I'm a noob and just trying to figure out the basics. I'm trying to build a simple question/answer site. I can submit a question to the db just fine but when I direct a user to answer I need to put the correct question id (q_id) as it's a foreign key in my answers table. I cant find anything online to solve this problem. I'm sure I'll get "dont use mysqli_query" or something but if anyone can just help me understand how to get the correct value passed into q_id it would be a great help. Seeing my php code below it will probably make sense what I'm attempting to do:
//set up connection credentials
$servername = "127.0.0.1";
$username = "root";
$password = "";
$dbname = "ask";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
//gather the data from the form
$answer = $_POST["answer"];
$q_id = mysqli_query($conn,"select q_id from questions order by q_id
desc limit 1");
$sql = "INSERT INTO answers (answer, q_id) VALUES ('$answer',
'$q_id')";
if (mysqli_query($conn, $sql)) {
echo "answer submitted";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);}
?>
When you open the page that display question, you already use the q_id, just use it again.
Like the stackoverflow URL, question ID is on the URL:
https://stackoverflow.com/questions/44896448/sql-statement-in-php-variable
Because you do not know re-write yet so you can use $_GET method to get q_id.
EDITED:
User insert_id; to get last id after question submitted then you got the id for the question
if (mysqli_query($conn, $sql)) {
$last_id = $conn->insert_id;
echo "answer submitted, id is ".$last_id;
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);}
?>
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
I have a table called "users" which has columns 'username', 'password' and 'permission'. In the permission column is either 'browse' or 'edit'.
Say I have a user logged into my site, I want to select select their permission using their username (which I have stored in a session variable). I want to then set a variable equal to either 'browse' or 'edit' based on their permission, to then use in further logic.
Assuming I have connected to and selected the appropriate database I am pretty sure the php code and query should go something like:
$u = $_SESSION['username'] ;
$sql = "SELECT permission FROM users WHERE username = '$u' " ;
$result = mysqli_query($sql);
But Im unsure how to then set a variable equal to 'browse' or 'edit' accordingly.
Any ideas?
Say you have a connection $con, for using session you have to start your session.
$u = $_SESSION['username'] ;
$sql = "SELECT `permission` FROM `users` WHERE username='$u'";
$result = mysqli_query($con, $sql);
$rows = mysqli_fetch_object($result);
//now its time to set the permission to the variable
echo $permission = $rows->permission;
mysqli_close($con);
you can also set the $permission to a $_SESSION.
$_SESSION['permission'] = $permission;
You have to do it like this:
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$u = $_SESSION['username'] ;
$sql = "SELECT `permission` FROM `users` WHERE username='$u'";
$result = mysqli_query($conn, $sql);
$rows = mysqli_fetch_object($result);
//now its time to set the permission to the variable
echo $permission = $rows->permission;
mysqli_close($conn);
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();
}
This question already has answers here:
php/mysql with multiple queries
(3 answers)
Closed 3 years ago.
I've a doubt with mysqli_query..
this is a part of my code:
$con = db_connect();
$sql= "SET foreign_key_checks = 0; DELETE FROM users WHERE username = 'Hola';";
$result = mysqli_query($con, $sql);
return $result;
I can't do the query...
If I try to do a query like this:
$sql= "INSERT INTO categorias(id_categoria,name) VALUES ('15','ssss');";
It works.
What's the problem?? I can't use SET with mysqli_query?
Thanks
You can not execute multiple queries at once using mysqli_query but you might want to use mysqli_multi_query as you can find out in the official documentation:
http://www.php.net/manual/en/mysqli.multi-query.php
Lets start with creating a working php script.
<?php
// replace for you own.
$host ="";
$user = "";
$password = "";
$database = "";
$con= mysqli_connect($host, $user, $password, $database);
if (!$con)
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else{
// Begin SQL query
$sql = "SELECT * FROM users";
$result = mysqli_query($con,$sql) OR Die('SQL Query not possible!');
var_dump($result);
return $result;
var_dump($result);
// End SQL query
mysqli_close($con);
};
?>
INSERT query:
$sql= "INSERT INTO categorias(name) VALUES ('ssss')";
mysqli_query ($con,$sql) OR Die('SQL Query not possible!');
UPDATE and DELETE query:
$sql= "DELETE FROM users WHERE username = 'Hola';";
$sql.= "UPDATE users SET foreign_key_checks = 0 WHERE username = 'Hola'"; /* I made a guess here*/
mysqli_multi_query ($con,$sql) OR Die('SQL Query not possible!');
Check the SET query. I think something is missing. I have changed it to what I think was your aim.
The connection should be established like this:
$Hostname = "Your host name mostly it is ("localhost")";
$User = "Your Database user name default is (root)"//check this in configuration files
$Password = "Your database password default is ("")"//if you change it put the same other again check in config file
$DBName = "this your dataabse name"//that you use while making database
$con = new mysqli($Hostname, $User , $PasswordP , $DBName);
$sql= "INSERT INTO categorias(id_categoria,name) VALUES ('15','ssss');";
In this query:
put categorias in magic quotes(`) and column names also
For your next query do this:
$sql= "SET foreign_key_checks = 0; DELETE FROM users WHERE username = 'Hola';";
Change to:
$sql= "SET foreign_key_checks = 0; DELETE FROM `users` WHERE `username` = 'Hola'";