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();
}
Related
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);
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();
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 5 years ago.
Improve this question
I have a string called $searchquery. $searchquery contains this SQL command:
SELECT * FROM `videos` WHERE (`Title` LIKE "%query%" OR `Tags` LIKE "%query%")
How can I make MySQL execute this command from a PHP page then display the results on PHP page??
I have tried
$sql = ($searchquery)
But dosent seem to work?
Firstly you need to create database connection
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// then execute your query
$sql = "SELECT * FROM `videos` WHERE (`Title` LIKE '%query%' OR `Tags` LIKE '%query%')";
$result = mysqli_query($conn, $sql);
// and fetch result set
while($row = mysqli_fetch_assoc($result)) {
print_r($row);
}
?>
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);
This question already has answers here:
Selecting random rows with MySQL
(3 answers)
Closed 8 years ago.
bellow you can see my table. In this table we have 300 quotes that I'm trying to fetch my at random and display it on the page but I have not succeeded. The column containing the texts has the name "fortune_text". here is my attempt code:
<?php
$username = "fortunes";
$password = "xxxx";
$hostname = "localhost";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
// connect to database
mysql_select_db("fortunes");
// query the databse
$query = mysql_query("SELECT 'fortune_text' FROM 'fortunes' ORDER BY RAND()");
echo "$query";
?>
try using shuffle() function of php to randomize array that comes from database and then echo the first index of that variable.
Hi here is the modified version of your sample, which fetch text by rand order.
I suggest you to use limit when you print result to page if you have later many rows, checking for error if any. Important line is echo mysql_result($result);
<?php
$username = "fortunes";
$password = "xxxx";
$hostname = "localhost";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
// connect to database
mysql_select_db("fortunes");
// query the databse
$result = mysql_query("SELECT 'fortune_text' FROM 'fortunes' ORDER BY RAND()");
if (!$result) {
die('Could not query:' . mysql_error());
}
echo mysql_result($result);
mysql_close($dbhandle);
?>