Is there any way to store mysql result in php variable? thanks
$query = "SELECT username,userid FROM user WHERE username = 'admin' ";
$result=$conn->query($query);
then I want to print selected userid from query.
Of course there is. Check out mysql_query, and mysql_fetch_row if you use MySQL.
Example from PHP manual:
<?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
?>
There are a couple of mysql functions you need to look into.
mysql_query("query string here") : returns a resource
mysql_fetch_array(resource obtained above) : fetches a row and return as an array with numerical and associative(with column name as key) indices. Typically, you need to iterate through the results till expression evaluates to false value. Like the below:
while ($row = mysql_fetch_array($query)){
print_r $row;
}
Consult the manual, the links to which are provided below, they have more options to specify the format in which the array is requested. Like, you could use mysql_fetch_assoc(..) to get the row in an associative array.
Links:
http://php.net/manual/en/function.mysql-query.php
http://php.net/manual/en/function.mysql-fetch-array.php
In your case,
$query = "SELECT username,userid FROM user WHERE username = 'admin' ";
$result=mysql_query($query);
if (!$result){
die("BAD!");
}
if (mysql_num_rows($result)==1){
$row = mysql_fetch_array($result);
echo "user Id: " . $row['userid'];
}
else{
echo "not found!";
}
$query="SELECT * FROM contacts";
$result=mysql_query($query);
I personally use prepared statements.
Why is it important?
Well it's important because of security. It's very easy to do an SQL injection on someone who use variables in the query.
Instead of using this code:
$query = "SELECT username,userid FROM user WHERE username = 'admin' ";
$result=$conn->query($query);
You should use this
$stmt = $this->db->query("SELECT * FROM users WHERE username = ? AND password = ?");
$stmt->bind_param("ss", $username, $password); //You need the variables to do something as well.
$stmt->execute();
Learn more about prepared statements on:
http://php.net/manual/en/mysqli.quickstart.prepared-statements.php MySQLI
http://php.net/manual/en/pdo.prepared-statements.php PDO
$query = "SELECT username, userid FROM user WHERE username = 'admin' ";
$result = $conn->query($query);
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$arrayResult = mysql_fetch_array($result);
//Now you can access $arrayResult like this
$arrayResult['userid']; // output will be userid which will be in database
$arrayResult['username']; // output will be admin
//Note- userid and username will be column name of user table.
Related
I don't understand this because I'm just getting into query's and php.
I'm trying to get the user's ID from the database and set that equal to a different users friendreq column.
Don't worry about me not escaping properly, this is only a test so I can practice! Thank you! (Although I'm not sure what escaping is, I'm going to do my research!)
$usernameID = "SELECT Id FROM Users WHERE Username = '$username'";
$sql = "UPDATE Users SET FriendReq = $usernameID WHERE Username = '$usernamebeingreq'";
$result = mysqli_multi_query($con, $usernameID, $sql);
if(!$result)
{
echo 'Failed';
}
else
{
echo 'Friend added!';
}
According to the PHP reference of mysqli_multi_query your two queries need to be concatenated with a semicolon. You're passing each query as its own parameter.
Use the following instead:
$result = mysqli_multi_query($con, $usernameID . "; " . $sql);
This will concatenate your two queries, so that it's the following:
SELECT Id FROM Users WHERE Username = '$username'; UPDATE Users SET FriendReq = $usernameID WHERE Username = '$usernamebeingreq'
I want to search my database to see if a user that is registering is using a username that is currently in my database. I have registered the same name about 5 times so it SHOULD return false but it returns true.
<?php
function registerUser($userName, $userPassword) {
$db = new dbinterface();
$db->connect();
// check for duplicate data
$checkduplicates = "SELECT * FROM usersexample WHERE $userName = :userName";
$myresult = mysql_query($checkduplicates);
if(mysql_num_rows($myresult) > 0){
echo $myresult;
return false;
}
?>
My table name is usersexample and the field i am searching is userName.
ANY and ALL help is appreciated!
Using mysql_num_rows in examples i get this warning:
Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource.
Use mysql_num_rows() to check the number of rows returned.
Sample:
$myresult = mysql_query($checkduplicates);
$rowcount = mysql_num_rows($myresult);
if($rowcount > 0)
{
// Account name already in use
}
You should try this...
if(mysql_num_rows($myresult) > 0) {
echo $myresult;
return false;
}
It will return false if there is a duplicate username.
$getduplicates = mysql_query("SELECT * FROM table WHERE username = $username");
$duplicates = mysql_num_rows($getduplicates);
if($duplicates){
echo "Uh oh someone already has that username";
}
else {
echo "Everything is allllllll good";
}
Please use prepared statements to avoid sql injection.
As you are using :userName in your SQL it seems you are trying to do this (is your
database class based on PDO by any chance?). The :userName part will be replaced
by your variable $userName when you do the bindValue.
Use count() in the database to count the number of records found,
the database knows best ;-)
$query = $db->prepare("SELECT count(*) AS no_found FROM usersexample WHERE userName = :userName");
$query->bindValue(':userName', $userName, PDO::PARAM_STR);
$query->execute();
$result = $query->fetchObject();
if($result->no_found > 0)
{
return false;
}
Did you try:
$checkduplicates = "SELECT userName FROM usersexample
WHERE LOWER('".$userName."') = LOWER(userName)";
$myresult = mysql_query($checkduplicates)
if (!$myresult) {
die('Invalid query: ' . mysql_error());
} else {
$num_rows = mysql_num_rows($myresult);
if (!$num_rows) {
die('Invalid query: ' . mysql_error());
} else return ($num_rows == 0);
}
Please, sanitize user input to avoid SQL injection.
I don't know if you are doing something fancy I don't understand, but I would build the query like this:
$checkduplicates = "SELECT * FROM `usersexample` WHERE `userName` = '$userName'";
Or this
$checkduplicates = "SELECT * FROM `usersexample` WHERE `userName` = '".$userName."'";
I need to insert an ID into session for later use. Table contains ID, username and password.
To get the ID im using:
$sql = "SELECT id FROM members WHERE username='$myusername' and password='$mypassword'";
$result=mysql_query($sql);
And trying to store it into session:
$_SESSION["id"] = $result;
When im trying to insert $_SESSION[id] into a table I get the value of 0 (which is the default value I made).
Kinda new on PHP, any help would be appriciated :)
you need fetch the value aswell:
$result=mysql_query($sql);
$fetch =mysql_fetch_array($result);
$_SESSION["id"] = $fetch["ID"];
Attempting to print $result won't allow access to information in the resource.
You need to use a function to access the resource returned:
$row = mysql_fetch_assoc($result)
$id = $row['id'];
The proper way to handle result would be to first check it has any value at all, i.e.:
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}
mysql_query() returns a resource on success, or FALSE on error. You need to fetch the rows from that result:
$result = mysql_query("SELECT id, name FROM mytable") or die(mysql_error());
$row = mysql_fetch_array($result);
if($row){ // check that there was really selected at least one row
$_SESSION['id'] = $row['id'];
}
I am using a MySQL table called "login" that includes fields called "username" and "subcheckr."
I would like to run a PHP query to create a new variable equal to "subcheckr" in the table where "username" equals a variable called $u. Let's say I want to call the variable "$variable."
How can I do this? The query below is what I have so far.
Thanks in advance,
John
$sqlStremail = "SELECT subcheckr
FROM login
WHERE username = '$u'";
I don't know if I understood correctly but if:
Just do something like this.
$sqlStremail = "SELECT subcheckr
FROM login
WHERE username = '$u'";
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
$variable = $row["subcheckr"];
In case you don't know, your query is vulnerable for SQL injections. Use something like mysql_real_escape() to filter your $u variable.
Is this what youa re looking for?
$result = mysql_query($sqlStremail);
$row = mysql_fetch_assoc($result);
$subcheckr = $row['subcheckr'];
$sqlStremail = mysql_query("SELECT subcheckr FROM login WHERE username = '$u'");
$result= mysql_fetch_array($sqlStremail);
$some_variable = $result['subcheckr']; // the value you want
You can do:
// make sure you use mysql_real_escape to escape your username.
$sqlStremail = "SELECT subcheckr FROM login WHERE username = '".mysql_real_escape($u)."'";
// run the query.
$result = mysql_query($sqlStremail );
// See if the query ran. If not print the cause of err and exit.
if (!$result) {
die 'Could not run query: ' . mysql_error();
}
// if query ran fine..fetch the result row.
$row = mysql_fetch_row($result);
// extract the field you want.
$subcheckr = $row['subcheckr'];
You can write
$sqlStremail = "SELECT subcheckr FROM login WHERE username = '".mysql_real_escape($u)."'";
$result = mysql_query($sqlStremail );
if (!$result) {
die 'Could not run query: ' . mysql_error();
}
$row = mysql_fetch_row($result);
$subcheckr = $row['subcheckr'];
$variable = array_pop(mysql_fetch_row(mysql_query("SELECT subcheckr FROM login WHERE username = '$u'")));
Only if username is unique
I have the following code and it should return just one value (id) from mysql table. The following code doesnt work. How can I output it without creating arrays and all this stuff, just a simple output of one value.
$query = "SELECT id FROM users_entity WHERE username = 'Admin' ";
$result = map_query($query);
echo $result;
I do something like this:
<?php
$data = mysql_fetch_object($result);
echo $data->foo();
?>
You have to do some form of object creation. There's no real way around that.
You can try:
$query = "SELECT id FROM users_entity WHERE username = 'Admin' ";
//$result = map_query($query);
//echo $result;
$result = mysql_query($query); // run the query and get the result object.
if (!$result) { // check for errors.
echo 'Could not run query: ' . mysql_error();
exit;
}
$row = mysql_fetch_row($result); // get the single row.
echo $row['id']; // display the value.
all you have is a resource, you would still have to make it construct a result array if you want the output.
Check out ADO if you want to write less.
Not sure I exactly understood, what you want, but you could just do
$result = mysql_query('SELECT id FROM table WHERE area = "foo" LIMIT 1');
list($data) = mysql_fetch_assoc($result);
if you wish to execute only one row you can do like this.
$query = "SELECT id FROM users_entity WHERE username = 'Admin' ";
$result = mysql_query($query);
$row = mysql_fetch_row($result);
echo $row[0];
there have been many ways as answered above and this is just my simple example. it will echo the first row that have been executed, you can also use another option like limit clause to do the same result as answered by others above.