Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have this news system but I can't figure out how to do it like this: news.php?id=1 then it will output the news id 1. Please help.
I have this so far:
<?php
include_once('includes/config.php');
if($id != "") {
$id = mysql_real_escape_string($id);
$sql = mysql_query("SELECT * FROM news WHERE id = '$id'");
}
$res = mysql_query($sql);
while($row = mysql_fetch_assoc($res)){
if(isset($_GET['id']));
echo $res['body'];
}
?>
It connects to the database (details are stored in the config).
the parameters after the ? in the URL are GET items. Use this:
<?php
if (isset($_GET['id'])) {
$id = $_GET['id'];
// Rest of your code
}
<?php
include_once('includes/config.php');
// see if the id is set in the URL (news.php?id=)
if(isset($_GET['id'])) {
// get the ID from the URL
// to make it safer: strip any tags (if it's a number we could cast it to an integer)
$id = strip_tags($_GET['id']);
// don't use SELECT *, select only the fields you need
$sql = mysql_query("SELECT body FROM news WHERE id=".mysql_real_escape_string($id));
while($row = mysql_fetch_assoc($sql)) {
echo $res['body'];
}
} else {
echo 'please select an article';
}
I would recommend you get away from using the mysql functions and use mysqli instead, as mysql is depreciated and you'll have to learn mysqli or PDO anyway.
Edit: updated code per comments
Firstly lets dissect your current code, to see where your going wrong.
<?php
include_once('includes/config.php');
/*
$id is not set anywhere before its used so this if statement will not fire,
if you are attempting to get this $id from a url parameter then you need
to set it first from $_GET['id'] global
*/
if($id != "") {
$id = mysql_real_escape_string($id);
$sql = mysql_query("SELECT * FROM news WHERE id = '$id'");
}
/*
This piece of code will fire but where is $sql set?
The mysql_query() function expects a string containing your sql query
so the subsequent lines of code will fail because of this
*/
$res = mysql_query($sql);
while($row = mysql_fetch_assoc($res)){
//this block is in the wrong place
if(isset($_GET['id']));
echo $res['body'];
}
?>
The idea is to get the user input E.G the $_GET['id'] from the url first, check the value is what your looking for, and then build your query.
As the mysql_* functions are deprecated I will show you an example using PDO. Though you can use mysqli, BUT you must always use prepared query's whenever user values come into contact with your database. This is to stop nasty/accidental sql injections.
<?php
// make the connection to the database using PDO
try {
$db = new PDO('mysql:host=127.0.0.1;dbname=the_awsome_db', 'yourusername', 'password');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$db->exec("SET CHARACTER SET utf8");
} catch(PDOException $e) {
exit('Sorry there is a problem with the database connection :' . $e->getMessage());
}
// sanitize user input - expecting an int
$id = filter_input(INPUT_GET, 'id', FILTER_SANITIZE_NUMBER_INT);
if (is_numeric($id)) {
// now lets query the database with the param id from the user
// prepare the query, using a placeholder
$stmt = $db->prepare('SELECT body,
some_other_column
FROM news
WHERE id = :placeholder_id');
// bind the placeholder with the value from the user
$stmt->bindParam(':placeholder_id', $id);
// execute the prepared query
$stmt->execute();
// fetch the result
$result = $stmt->fetch(PDO::FETCH_ASSOC);
// result not empty - display
if (!empty($result)) {
// display your result, use print_r($result) to view the whole result set if unsure
echo $result['body'];
} else {
// no matching id found in the db, do something
echo 'No results found';
}
} else {
// do something as user input is not a number
exit(header('Location: ./index.php'));
}
?>
Hope it helps, if your unsure of getting parameters from the user you may need to look up some more tutorials and get the hang of that first before dabbling with databases and all that good stuff.
Related
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
So basically I got this code right here:
<?php
include_once 'dbconfig2.php';
$con = new DB_con();
$table = "users";
if(isset($_GET['profile_id']))
{
$sql=mysql_query("SELECT * FROM users WHERE user_id=".$_GET['profile_id']);
$result=mysql_fetch_array($sql);
}
?>
I am clueless as to how I would make it so if the user_id is not existent in the records, they cannot view their profile but it leads them to another messsage or piece of code.
If the user_id doesn't exist, there won't be any rows in the result. When you try to read a row with mysql_fetch_array(), it returns FALSE. So you can simply test $result:
if (!$result) {
die("Invalid profile ID");
}
Try to use prepared statements using mysqli, in order to avoid sql injection.
By way of example:
$mysqli = new mysqli("localhost", "root", "root", "test");
if ($mysqli->connect_errno) {
echo "connect_error". $mysqli->connect_error;
}
$id = $_GET['profile_id'];
$result = $mysqli->prepare('SELECT name FROM users WHERE user_id = ?');
$result->bind_param("i", $id);
$result->execute();
$result->bind_result($col1);
$result->fetch();
$is_valid_profile = (!$col1) ? 'Invalid profile' : 'Valid profile';
echo $is_valid_profile;
$result->close();
http://php.net/manual/en/mysqli.prepare.php
This has probably been asked before, please feel free to link me or whatever, I just couldn't find exactly what I'm after.
It's pretty simple, I need to display the results of a search form. That part is easy and I can get that to work. What I'm having trouble with is when no results match what the user searched.
I'm fairly certain I need to just use an IF statement but I'm not very experienced with PHP and cannot figure out how to correctly display the code.
This is what I have so far:
$query = "SELECT * FROM search WHERE isbn='$isbn' OR bookname='$bookname' OR author='$author' OR category='$category'";
if (!$query)
{
echo "No results found in the database. Please go back and search again.";
}
My question is: How do I get the 'No results found...' message to display when the users search doesn't match anything in the database?
NOTE - I get very confused very quickly when it comes to trying to understand certain terms within PHP and SQL so please try to explain your answer like you would to an absolute beginner.
Many thanks in advance.
You want to show the "No results found"-message when no rows are found in the database table.
To do this, you can use below PHP and SQL code:
$sql = "SELECT * FROM search WHERE isbn='$isbn' OR bookname='$bookname' OR author='$author' OR category='$category'";
$query = $db->prepare($sql);
$query->execute();
$rows = $query->fetch(PDO::FETCH_NUM);
if($rows[0]) {
// Row exists
} else {
echo "No results found in the database. Please go back and search again.";
}
Note that the above answer is vulnerable to SQL injection attacks.
To prevent SQL injection attacks, it is recommended that you prepare and bind all user-submitted data, here is a better example that shows how SQL injection attacks can be prevented: (full example, including database connection)
$db = new PDO($dsn);
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query = $db->prepare("SELECT * FROM search WHERE isbn=:isbn OR bookname=:bookname OR author=:author OR category=:category");
$query->execute([ ':isbn'=>$isbn, ':bookname'=>$bookname, ':author'=>$author, ':category'=>$category ]);
$rows = $query->fetch(PDO::FETCH_NUM);
if($rows[0]) {
// Row exists
} else {
echo "No results found in the database. Please go back and search again.";
}
Assuming you are using Mysqli ,
//connect with mysql
$conn = mysqli_connect("localhost", "user", "password", "db");
//here is the query
if($result = mysqli_query($conn,"SELECT * FROM search WHERE isbn='$isbn' OR bookname='$bookname' OR author='$author' OR category='$category'")){
if(mysqli_num_rows($result) > 0){
//mysqli_num_rows() returns the number of rows in a result .
//when it is greater than zero, it has some results
}
else{
echo "No results found in the database. Please go back and search again.";
//Do something if no results returned
}
}
//finally free the results
mysqli_free_result($result);
mysqli_close($conn);
I am starting to learn php PDO because I've read that it is more efficient and secure.
I could do the following with simple mysqli but am having trouble making it work with PDO.
PID stands for an id number.
fname stands for: first name.
lname stands for: last name.
age stands for ... age.
Basically I have an index.php that contains links from a test table called "persons" inside of the database drinks. When I click on the link which shows the fname of every row, it goes to insertcarbonated.php which is then supposed to $_GET['fname']; of the link and search up that specific row. However, my code in insertcarbonated.php is not working and I am not familiar enough with PDO to know exactly why, I would like some enlightenment on this because I literally begun learning PDO yesterday. :(
Here is my insertcarbonated.php:
<html>
<?php
/*** mysql hostname ***/
$hostname = 'localhost';
/*** mysql username ***/
$username = 'theusername';
/*** mysql ***/
$password = 'thepass';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=drinks", $username, $password);
/*** echo a message saying we have connected ***/
echo 'Connected to database';
/*** The SQL SELECT statement ***/
$fname = $_GET['fname'];
//is _GET even working with PDO?
$STH = $dbh-> prepare( "SELECT * FROM persons WHERE fname LIKE '$fname'" );
/***as Joachim suggested, I had actually two different variables here, however, it
did not solve the issue **EDITED** from ($DBH to $dbh)****/
$STH -> execute();
$result = $STH -> fetch(0);
//$result should print out the first column correct? which is the person's ID.
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
<head>
</head>
<body>
<p><?php print $result; ?></p>
//me trying to print out person's ID number here.
</body>
</html>
As previously mentioned, I'm not sure where my error is, I get fatal error:
Call to a member function prepare() on a non-object?
and If I try to not use that function, my page is simply blank and nothing prints out.
Basically I would just like to print out different bits of information from that row (that is from it's relevant link in index.php). I would like to know how to solve this using PDO.
Here is the previous question I asked, and it was solved but not with PDO.
Previous question
You could do something like this...
try {
$dbh = new PDO("mysql:host=$hostname;dbname=drinks", $username, $password);
$fname = $_GET['fname'];
$sth = $dbh->prepare("SELECT * FROM persons WHERE fname LIKE ?");
$sth->execute( array($fname) );
$result = $sth->fetch(PDO::FETCH_OBJ); // or try PDO::FETCH_ASSOC for an associative array
}
catch(PDOException $e)
{
die( $e->getMessage() );
}
In the HTML part you can do print_r($result) and you will see the exact structure of your results.
Comments: one of the best reasons to use PDO is the automatic escaping of the dynamic user inputs, like $fname here, so you should use it. Also, with $sth->fetch($param) the $param is not the column number but the type of the fetch method PDO will use (see PHP manual). Depending the method, you can get the PID of the result by $result->PID in case of PDO::FETCH_OBJ or by $result['PID'] when using PDO::FETCH_ASSOC. I hope this helps.
So Im trying to delete a record from a table using php and sql and check whether it has been deleted using a rowcount() function in an if statement.
Im having problems on both fronts...
<?php
echo $_GET['id'];
if (isset($_GET['id'])) {
$trainingID = $_GET['id'];
}
else {
die('There was a problem with the ID given.');
}
// include the connection file
require_once('./includes/connection.inc.php');
$conn = dbConnect();
// prepare SQL statement
$sql = 'DELETE FROM `trainingCourses` WHERE `trainingID` = "$trainingID"';
$stmt = $conn->prepare($sql);
try {
$stmt->execute();
echo "deleted";
echo $stmt->rowcount();
//check number of rows affected by previous insert
if ($stmt->rowCount() == 1) {
$success = "$trainingID has been removed from the database.";
}
}
catch(PDOException $e){
echo $e;
echo 'Sorry, there was a problem with the database.';
}
?>
I currently get 3 things outputted from my echo's throughout my code, firstly i get T0001, which is the primary key of the record i want to delete from another page. Secondly i get "deleted" which is from an echo within my 'try' statement but the record doesn't actually delete from the database. This is backed up from the rowcount() function which outputs 0.
I can't seem to get this working and im sure it should be simple and is something i am just overlooking!
Will the try method default to the catch if the "if" statement in it fails? As im also unsure what should be output from a rowcount() when a row has been deleted?
Any help you could offer would be really helpful! Thanks!
echo'ing this line
$sql = 'DELETE FROM `trainingCourses` WHERE `trainingID` = "$trainingID"';
will treat $trainingID as string and not variable.
$sql = "DELETE FROM `trainingCourses` WHERE `trainingID` = '$trainingID'";
will do the work BUT its not safe (sql injections). You should use PDO to bind varaibles like this
$sth = $dbh->prepare("DELETE FROM `trainingCourses` WHERE `trainingID` = :id");
$sth->bindParam(":id",$trainingID);
$sth->execute();
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am new to PDO and am attempting to convert my existing PHP/MYSQL code to meet PDO standards.
The problem i am having is I can connect to the database but no results are being shown and no errors are being displayed.
This is my database:
$db2 = new PDO('mysql:host=localhost;dbname=DATABASENAME;charset=utf8', 'USERNAME', 'PASSWORD');
$db2->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db2->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
I am using
include 'db.php';
to include the above database details in my main PHP script.
My main script using the following as a select statement to display the rows which match the criteria:
<?
foreach($db2->query('SELECT view_invoice FROM user_info where username = "$timeapp_username"') as $inrow) {
$inrow['view_invoice']; //etc...
}
?>
On running this I get no errors but no results displayed. I cannot spot what I am doing wrong. Can anyone advise what I am doing wrong here?
The query function is unsafe and should be used only for queries that will not return data, like UPDATE, DELETE, INSERT...
To make safe and working SELECT queries, prepare your query with the PDOStatement. See:
//Example querystring
$id = $_GET['id'];
try{
//Instantiate PDO
$pdo = new PDO('dsn', 'user', 'password');
//Create the statement
$statement = $pdo->prepare("SELECT * FROM `my_table` WHERE `id`=:id");
//Now you can bind values to the statement. This will automatically escape the values
//Defines the type of the value that you'll bind (optional)
$data_type = (is_numeric($id)) ? PDO::PARAM_INT : PDO::PARAM_STR;
//Replace the :id in the query by the value retrieved from the querystring
$statement->bindValue(':id', $id, $data_type);
//Now, let's execute our statement
$statement->execute();
//If the query has returned any rows, we can iterate over it
if ($statement->rowCount() > 0)
{
foreach ($statement->fetchAll() as $result)
{
//Now you can retrieve the values using the defined fetch method.
//Example with associative fetch mode:
echo 'My name is '.$result['name']."!";
echo '<br />';
}
}
else
{
//No results found
}
} catch (PDOException $pe){
die("An error has occurred: ".$pe->getMessage());
}