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
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 5 years ago.
Improve this question
I need get Data form mySql and echo it . but show to me error ! please help me . I am amator . please check my code. (get Data form mySql and echo it - PHP)
my error in $result1=mysqli_query($link,$query1);
my PHP file :
<?php
$post_data=#$_POST['myjson'];
$post_data=json_decode($post_data,true);
$command=$post_data['command'];
$server="localhost";
$user="user";
$pass="pass";
$db="db";
$link=mysqli_connect($server,$user,$pass,$db);
mysqli_set_charset($link,"utf8");
if ($command=="get_contact") {
$id=$post_data['id'];
$query="select * from ad where id=$id";
$result=mysqli_query($link,$query);
$row=mysqli_fetch_assoc($result);
$num=mysqli_num_rows($result);
if ($num == 1) {
$query1="select * from user where id=$row['user_id']";
$result1=mysqli_query($link,$query1);
$row1=mysqli_fetch_assoc($result1);
$num1=mysqli_num_rows($result1);
if ($num1 == 1) {
$specifications=array("mobile"=>$row1["mobile"], "email"=>$row1["email"]);
echo "<b>".json_encode($specifications)."</b>";
} else {
echo "<b>Not Found</b>";
}
} else {
echo "<b>Not Found</b>";
}
exit();
}
?>
If you expect just one result of each query, you can get the same results with just one query instead of the two you have:
$query = "select user.* from user, ad where ad.id=$id and user.id = ad.user_id";
Also, you should use prepared statements to avoid sql injection instead of writing vars inside the sql queries.
Besides that, give more info in the error messages because now you don't know which error is returning.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 7 years ago.
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.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Improve this question
I looked at some other questions online and on here related to this, but none seem to really encounter my error exactly.
I wrote my PHP code and implemented it into my HTML, I get the dropdown box appearing, but it doesn't actually want to display any values. Is there any implementations or fixes I should include in my code? How do I get it to work?
My database is called: Treatments
My column in the database that I want displayed is called: Treatment
treatment_dropdown.php
<?php
$hostname = 'host_name';
$dbname = 'database_name';
$username = 'username';
$password = 'password';
$con=mysql_connect($hostname,$username,$password,$dbname) or die("Failed to connect to MySQL: " . mysql_error());
$db=mysql_select_db($dbname,$con) or die("Failed to connect to MySQL: " . mysql_error());
$query = "SELECT * FROM `Treatments`";
$result = mysql_query($con, $query);
$options = "";
while ($row = mysql_fetch_array($result)){
$options = $options . "<option>$row[1]</option>";
}
?>
HTML:
<body>
<select>
<?php
echo $options;
?>
</select>
</body>
Consider changing this line:
$query = "SELECT * FROM 'Treatments'";
to use backticks instead of single quotes like so:
$query = "SELECT * FROM `Treatments`";
In my test query I got an error because of this, let me know if that helps.
Add <?php include 'treatment_dropdown.php'; ?> to the top of your HTML file. This should give you access to the the $options string so it can be used in that file. Note that in order for this to work, treatment_dropdown.php needs to be in the same directory as your HTML file. If it is not, the include statement will need to be changed to reflect the appropriate file path.
Do not use mysql_*() functions, they are deprecated. Use mysqli or PDO instead.
No matter which library use use to access mysql, always check for errors within the sql code separately. Errors in the sql code do not result in errors in the php code.
In this particular case the problem is that you included the table in single quotes instead of backticks.
The correct code:
$query = "SELECT * FROM `Treatments`";
Here's what your PHP file should look like:
<?php
$hostname = 'localhost';
$dbname = 'Treatments';
$username = 'root';
$password = '';
$con = mysql_connect( $hostname, $username, $password, $dbname) or die("Failed to connect to MySQL: " . mysql_error());
$db = mysql_select_db($dbname,$con) or die("Failed to connect to MySQL: " . mysql_error());
/* No single quotes needed for the table name. */
$query = "SELECT * FROM Treatments";
/* First parameter should be $query not $con */
$result = mysql_query($query, $con);
$options = "";
/* Check if no results exist. */
if ( !$result ) {
die( "NO results found." );
}
while ( $row = mysql_fetch_array($result) ) {
$options .= "<option>$row[treatment]</option>";
}
?>
Notes:
dont use mysql_* functions, they're not secure, use PDO instead.
your table name does not need to be wrapped in single quotes.
mysql_query expects parameter 1 to be the query not the DB connection.
you should probably check if no results are found.
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 7 years ago.
Improve this question
$query = sqlsrv_query("select * from sessions where password='$password' AND username='$username'");
$rows = sqlsrv_num_rows($query);
if ($rows == 1) {
$_SESSION['login_user']=$username;
header("location: profile.php");
} else {
$error = "Username or Password is invalid";
}
Hi, I have this code but it's written in mysql and I want it to work in sqlserver so I changed mysql_query into sqlsrv_query and it didn't work properly, and I changed mysql_num_rows into sqlsrv_num_rows and it didn't work either so can anyone help me and tell me how to write them please?
You are missing the connection parameter to sqlsrv_query. While you're at it, you might as well use bind variables instead of string substitution to help guard against SQL-Injection attacks.
$serverName = "serverName\instancename";
$connectionInfo =
array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password" );
$conn = sqlsrv_connect( $serverName, $connectionInfo);
$params = array($username, $password);
$stmt = sqlsrv_query
($conn,
'select * from sessions where password=? AND username=?',
$params);
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 8 years ago.
Improve this question
require("./connect.php");
$getid = $_GET['id'];
$getusername = mysql_query("SELECT username FROM user WHERE id='$getid'");
$getdesc = mysql_query("SELECT description FROM user WHERE id='$getid'");
echo "$getusername $getdesc";
I am having trouble, it is not echoing the data from those variables. I is returning resource id #10 and #11.
You need to fetch the data first before you can use the mysql_query result...
please see the example in the PHP Documentation
https://php.net/manual/en/function.mysql-fetch-row.php
<?php
$result = mysql_query("SELECT id,email FROM people WHERE id = '42'");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$row = mysql_fetch_row($result);
echo $row[0]; // 42
echo $row[1]; // the email value
?>
Warning:
This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used.
pdo : https://php.net/manual/en/book.pdo.php
mysqli : http://www.php.net//manual/en/book.mysqli.php
You are trying to print out the resource ID of the query you just ran.
To get to the actual results you have to specifically request it.
mysql_fetch_assoc($getusername); //should be used!
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.