I am changing my database to add an "sex" column and after, I can't log into the my site. So I look into the get_passwd() function, and I see $passwd = $row[5] is causing the problem.
I fixed it, but is there better way to do this function, even if I adding column into the database?
function get_passwd($link, $login) {
$sql = "SELECT * FROM user WHERE email='$login'";
$result = mysql_query($sql, $link);
$row = mysql_fetch_array($result);
$passwd = $row[6];//this is the problem!
//echo $passwd;
return $passwd;
};
You're MYSQL functions are deprecated.
You should be afraid of MYSQL Injections.
... But here is a way to make the world of MYSQL safer ...
PDO - http://php.net/manual/de/book.pdo.php
Example:
$db = new PDO("mysql:host=$db_host;dbname=$db_name;charset=utf8", "$db_user", "$db_pass");
$query = $db->prepare("SELECT username, password FROM user WHERE email = ? LIMIT 1");
// you should know which columns you are selecting
// LIMIT to make sure you don't select 2 rows.
$query->execute(array($login));
$row = $query->fetch();
echo $row["password"];
//return $row["password"];
$db = null;
Use mysql_fetch_assoc instead of mysql_fetch_array. It will return keyed array with column names as keys.
I'm guessing that everyone will tell you that it is no longer recommended to use these functions and you should switch to something like PDO, for example.
But since you might need to maintain some old application with legacy code I'm guessing that we can also stay on point and give an answer. You can use a function like mysql_fetch_assoc and the returned value will be an associative array, so you'll be able to use $row['password'] instead of $row[6]. There's also mysql_fetch_object.
Again, when you look at those manual pages please pay attention to the big notice on the red background at the top.
mysql_fetch_assoc allows you to perform a mysql query and use the response object as a key[value] array.
function get_passwd($link, $login){
$sql="SELECT * FROM user WHERE email='$login'";
$result=mysql_query($sql, $link);
$row=mysql_fetch_assoc($result);
$passwd = $row['password']; <- use the column name here
//echo $passwd;
return $passwd;
};
Find out more at the documentation page below:
http://php.net/manual/en/function.mysql-fetch-assoc.php
Related
I'm fairly new to PDO in PHP and I'm trying to make a simple log-in form. I need to be able to fetch the data and can't seem to make that work with fetchColumn(), which I need to check if the user and password match.
$query = "SELECT * FROM administrator
WHERE user = :user
AND pass = :pass";
$res = $db->prepare($query);
$params = array("user" => $username, "pass" => $password);
$res->execute($params);
$num_rows = $res->fetchColumn(1);
if ($num_rows) {
$_SESSION['user'] = $num_rows['user'];
header('Location: .');
exit();
} else {
echo "Failure";
}
if (isset($_SESSION['user'])): ?>
<p>Hello, <?= $_SESSION['user']; ?>! This is admin content.</p>
Logout
<?php endif; ?>
When using this code, using the username adminuser, the output is:
"Hello, a! This is admin content."
when it should be:
"Hello, adminuser! This is admin content."
So, how does one fetch the data when the fetchColumn() function has already been executed?
I think you are misunderstanding what fetchColumn does. It will simply return a single value.
You have two options:
Change $num_rows['user'] to just $num_rows (strange naming convention there by the way). Here I'm assuming that you are actually targeting the correct column. See note below about using *
or
Use $res->fetch(PDO::FETCH_ASSOC) instead of fetchColumn, which will return an associative array containing all values in the row (which you can then continue to access with $num_rows['user']
If you go for option 1, I strongly recommend that you define which columns should be returned in your SELECT statement. Using fetchColumn with SELECT * FROM is very fragile, because the order of columns may change if new fields are added. To be honest, it's rare that you should use * anyway, so I'd probably specify the columns in any case.
I am new to PHP. I wanted to create a new record in another table but just one new variable gets returned. I've tried following:
$user_id = mysql_real_escape_string($_POST['user_id']);
$user_name = mysql_query("SELECT user_name FROM accept WHERE user_id=".$user_id." ");
$row1 = mysql_fetch_array($user_name);
$server = mysql_query("SELECT server FROM accept WHERE user_id=".$user_id." ");
$row2 = mysql_fetch_array($server);
$url = mysql_query("SELECT link FROM accept WHERE user_id=".$user_id."");
$row3 = mysql_fetch_array($url);
$lpoints = mysql_real_escape_string($_POST['lpoints']);
And my result is this.
First of all, combine your queries into one:
$user_id = mysql_real_escape_string($_POST['user_id']);
$user_info = mysql_query("SELECT user_name, server, link FROM accept WHERE user_id=".$user_id." ");
$row = mysql_fetch_array($user_info);
$lpoints = mysql_real_escape_string($_POST['lpoints']);
In order to create a new record, you will need INSERT INTO, to change existing records use UPDATE.
When you're fetching info from the database, it will be an array so you will need to use it accordingly. So essentially, to use the variables it will be like this:
$row['user_name'] or $row['server'] etc..
Also, look into using mysqli instead. You will need to change your connection script and some other syntax but it needs to be done. mysql is deprecated, insecure, and future support is not there so you will need to change it later anyway.
You should use pdo or mysqli and here is your code;
$user_id = &$_POST["user_id"];
if($user_id){
$result = mysql_query("select user_name,server,link,lpoints from accept where user_id='".mysql_real_escape_string($user_id)."'");
/*You should use single quotes for escaping sql injection*/
if($result){
$vars = mysql_fetch_array($result);
if($vars){
list($username,$server,$link,$lpoints) = $vars;
}
else{
//do something with errors
}
mysql_free_result($result);
}
else{
//do something with errors
}
}
else{
//do something with errors
}
Try This-
$user_id = mysql_real_escape_string($_POST['user_id']);
$result = mysql_query("SELECT user_name, server, link FROM accept WHERE user_id=".$user_id." ");
$row=mysql_fetch_array($result)
$row1=$row['user_name'];
$row2=$row['server'];
$row3=$row['link'];
$lpoints = mysql_real_escape_string($_POST['lpoints']);
Now you got what you wanted based on your requirement use the data to insert or update.
I'm having trouble getting info from my MySQL database.
Here is my code :
/********************
* Database Info
********************/
$host = "localhost";
$user = "admin";
$pass = "admin#";
$database = "db_admin";
/********************
* Database connection
********************/
$con = mysqli_connect( $host, $user, $pass, $database );
if (mysqli_connect_errno ()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error ();
}
$result = array();
if (isset($_POST['ID'])) {
$id = $_POST['ID'];
$query = "SELECT * FROM Servers WHERE PID='" .$id. "'";
$result = mysqli_query($con, $query);
}
print("<pre>".print_r($result,true)."</pre>");
My first question, Did I use "isset" function currectly?
Because it doesnt seem like it is actually going though the if statement.
The Url I am using is : #..com/view.php?ID=1
My second question, Did I use the $query correctly?
Because I echo $id and that echoed out a "MySQL Object()"
Finally, the print printed out "Array()"
I'm just starting on PHP, Thanks for the help :)
A few things:
If you're passing the variable in the query string, use $_GET instead of $_POST to retrieve the values.
$result will return an pointer to the recordset, not the rows themselves. You will have to use mysqli_fetch_array() to fetch the rows.
ADD:
If you are sure that you will only have 1 record returning, you can use:
$row = mysqli_fetch_assoc($query);
echo $row['field_name'];
More then 1 record?
while($row = mysqli_fetch_assoc($query)){
echo $row['field_name'];
}
# your first question: if you have a input field with the name="ID", then its good.
Please also post your HTML :)
$var = 'Hello world';
if(isset($var)){ //If the var $var has been set (in this case it is)
echo $var;
} else {
//If $var is not set, then we get in the else
echo 'The var $var is not set';
}
The best thing is debugging the code with a debugger, you may use XDebug, or at least use var_dump(); to see what happens
var_dump($_REQUEST, $result);
Answer to your first question: It's hard to say if you've used it correctly when you haven't said what you're trying to do. I'm presuming that you only want run the code enclosed in the if-statement if the POST variable 'ID' has been received. If so, yes you've done it correctly.
Answer to your second question: I'm presuming on this line you're trying to build a string with a valid MySQL query. You've done that correctly, assuming $_POST['ID'] is a string (or can be converted to a string, see http://www.php.net/manual/en/language.types.string.php#language.types.string.casting).
If you're echoing $id and it's returning an object, however, you'll have a problem. You can't combine a string and an object like that. You'd need to iterate the object with a foreach, for example, and extract the id from that. The rest of the code won't work until that part is resolved.
The thing to investigate now is why $_POST['ID'] is returning an object. You'll need to provide the form code at the very least.
The problem is, I have a table with some content. The table name is departments. It has 3 columns id,short_name,long_name.
Now i am making a class which will return all the departments in an array but i can't go through that. I used array_push() to make array but can't get enough hint, any other ideas??
Code:
$con= $this->con;
$db_name= $this->db_name;
$sql="SELECT * FROM $db_name.departments";
$result= mysql_query($sql, $con);
$data=array();
while($happen= mysql_fetch_object($result)) {
array_push($data,array([$happen->id],[$happen->short_name],[$happen->long_name]));
}
return $data;
Try this:
$con= $this->con;
$db_name= $this->db_name;
$sql="SELECT * FROM {$db_name}.departments";
$result= mysql_query($sql, $con);
$data=array();
while ($happen= mysql_fetch_object($result))
{
$data[$happen->id]['id'] = $happen->id;
$data[$happen->id]['short_name'] = $happen->short_name;
$data[$happen->id]['long_name'] = $happen->long_name;
}
return $data;
The above adds your data in the array based on the unique ID (using that as a key).
EDIT - restructured response after additional data was provided.
Just use mysqli_fetch_assoc().
http://www.php.net/manual/en/mysqli-result.fetch-assoc.php
It dumps your result set directly into an array like the one you are describing. Also, mysql_query is deprecated and should not be used. You need to look into the mysqli or pdo functions.
Rather than using mysql_fetch_object() just use mysql_fetch_assoc()
Also, I'd try and avoid using mysql_* if you can and just switch to using PDO immediately.
I'm new to PHP and SQL, but I need a way to store the result of an SQL Query into a variable.
The query is like this:
$q = "SELECT type FROM users WHERE username='foo user'";
$result = pg_query($q);
The query will only return one string; the user's account type, and I just need to store that in a variable so I can check to see if the user has permission to view a page.
I know I could probably just do this query:
"SELECT * FROM users WHERE username='foo user' and type='admin'";
if(pg_num_rows($result) == 1) {
//...
}
But it seems like a bad practice to me.
Either way, it would be good to know how to store it as a variable for future reference.
You can pass the result to pg_fetch_assoc() and then store the value, or did you want to get the value without the extra step?
$result = pg_query($q);
$row = pg_fetch_assoc($result);
$account_type = $row['type'];
Is that what you are looking for?
Use pg_fetch_result:
$result = pg_query($q);
$account_type = pg_fetch_result($result, 0, 0);
But on the other hand it's always good idea to check if you got any results so I'll keep the pg_num_rows check.