Here's my code:
$query = "SELECT Username, EmailVerified, Blocked FROM user";
$result = mysql_query($query, $link);
$row = mysql_fetch_assoc($result);
print_r($row);
Field Username is string and EmailVerified and Blocked are of type bit. The line print_r($row) displays the value of Username field but not the other two. I tried mysql_fetch_object(), mysql_fetch_row(), mysql_fetch_array() also, but same result.
Can't we fetch bit fields with mysql_query()?
I think you need to cast the BIT field to an integer ->
SELECT Username, CAST(EmailVerified AS unsigned integer) AS EmailV, CAST(Blocked AS unsigned integer) AS Block FROM User
Yes you can but they are retrieved as strings, and most likely end up being unprintable characters. You can get the values as numbers like so:
$query = "SELECT Username, EmailVerified, Blocked FROM user";
$result = mysql_query($query, $link);
$row = mysql_fetch_assoc($result);
$row['EmailVerified'] = ord( $row['EmailVerified'] );
$row['Blocked'] = ord( $row['Blocked'] );
print_r($row);
Instead of using BIT and converting it each time you need to use, you can use BOOL (which is already a TINYINT) and store TRUE (1) or FALSE (0) values.
Related
All I need is to produce a row. I've looked at all the samples and I cannot for the life of me get the right information. Hence help is required please.
Connection to DB in the usual way. Here is my code for the query.
$sql = "SELECT * FROM table WHERE `u_password` = $pword AND `user` = $uname LIMIT 1";
$result = mysqli_query($mdb, $sql);
$row = mysqli_fetch_assoc($result);
//Then I try to retrieve say the user name....
echo $row['seeking'];
I've got a count in there and it produces a result of 1.
The error I get is
'Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result'
Help would be appreciated.
The error
Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result
Almost always means that the query failed for some reason, thus $result = mysqli_query returns FALSE rather than a mysql_result object so anything that then tries to use $result as an object will not work for obvious reasons.
The issue with your query is that text column data must be wrapped in quotes like this
$sql = "SELECT *
FROM table
WHERE `u_password` = '$pword' AND `user` = '$uname' LIMIT 1";
Your script is at risk of SQL Injection Attack
Have a look at what happened to Little Bobby Tables Even
if you are escaping inputs, its not safe!
You should use parameterized queries to avoid this.
$sql = "SELECT *
FROM table
WHERE `u_password` = ? AND `user` = ? LIMIT 1";
$stmt = mysqli_prepare($mdb, $sql);
// its also a good idea to check the staus of a prepare
// and show the error if it failed, at least while testing
if ( $stmt === FALSE ) {
echo mysqli_error($mdb);
exit;
}
$stmt->bind_param('ss', $pword, $uname );
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
echo $row['seeking'];
You need to use prepared statements (in actuality you could get it to work by quoting your strings but prepared statements are much better). Like so:
$sql = "SELECT * FROM table WHERE `u_password` = ? AND `user` = ? LIMIT 1";
$stmt = mysqli_prepare($mdb, $sql);
$stmt->bind_param("ss",$pword,$uname);
if ($stmt->execute()) {
$result = $stmt->get_result();
$row = mysqli_fetch_assoc($result);
//Then I try to retrieve say the user name....
echo $row['seeking'];
} else { /* something went wrong */ }
I am trying to receive an Id from my user table.
I have:
$retrieve_id = "SELECT userid FROM tb_users WHERE username = '$username'";
$user_id = intval(mysql_query($retrieve_id));
The statement should return 1 since that is the value in the table. However, it returns 6 which is the length of the column name (userid). This happens when I'm querying other tables too.
How can I retrieve the value from the table ONLY?
You need to fetch the actual result from the query, either using mysql_result or mysql_fetch_*.
$result = mysql_query("SELECT userid FROM tb_users WHERE username = '$username'");
if (!$result) {
die('Could not query:' . mysql_error());
}
$user_id = mysql_result($result, 0); // outputs first row
Note that all mysql_ functions are deprecated and you should use mysqli_ or PDO. Your query is also open to SQL injection.
http://php.net/manual/en/function.mysql-query.php
mysql_query returns a resource not the value.
$retrieve_id = "SELECT userid FROM tb_users WHERE username = '$username'";
$result = mysql_fetch_assoc(mysql_query($retrieve_id));
$user = $result['userid'];
A) mysql_* is deprecated
B) make sure you're parameterizing your inputs
C) try this:
$result = mysql_query($retrieve_id);
$user_id=$result["userid"];
function mysql_query returns resource type for a select query. For results you have to use mysql_fetch_array or mysql_fetch_assoc functions.
$retrieve_id = "SELECT userid FROM tb_users WHERE username = '$username'";
$result = mysql_query($retrieve_id));
$row = mysql_fetch_assoc($result)) {
echo $row['userid'];
Check the php docs on mysql_query(). It actually returns a resource, not simply the value you are querying for.
But you shouldn't even be using mysql_query() as it's deprecated in PHP 5.5, and you don't want to have to redo your code when you upgrade, do you?
Instead, use mysqli_query(), which will return a mysqli_result object. Then from that object, you can retrieve the values you're looking for with fetch_field()
Basically im doing a login script where the username must be checked in the database before user gets logged in. So I need a mysql query that will return ONLY the number of records matched from the target table with the specified username, AND NOT an array with the records. I tried this:
$result = mysql_query( "SELECT COUNT(*) from usersecurity WHERE Email ='$username'" );
but apparrently it returns a result resource and not a int or number value.
You're almost there:
$result = mysql_query( "SELECT COUNT(*) from usersecurity WHERE Email ='$username'" );
$row = mysql_fetch_row($result);
print($row[0]) //0 or 1, etc
use mysql_num_rows on the returned resource
$result = mysql_query( "SELECT * from usersecurity WHERE Email ='$username'" );
$count = mysql_num_rows( $result );
from http://php.net/manual/en/function.mysql-query.php
"For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query() returns a resource on success, or FALSE on error."
In other words mysql_query will ALWAYS return a resource.
what you can use for quick validation is
mysql_num_of_rows($result) > 0
http://php.net/manual/en/function.mysql-num-rows.php
or if(!empty(mysql_fetch_row($result))
Don't forget you still need this to retrieve your results
$row = mysql_fetch_row($result)
$row[0] will be your integer.
How can I put and read data from PHP and MySQL? I tried the following:
$pwdcrypt = SHA1($pwd);
echo "Now we put some data to the database!";
$userregisterquery="INSERT INTO user (email, password) VALUES ('$email', '$pwdcrypt')";
echo $userregisterquery;
mysqli_query($link, $userregisterquery);
$usergetdataquery="SELECT email, password FROM user WHERE email='$email'";
echo $usergetdataquery.'</br>';
$result = mysqli_query($link, $usergetdataquery);
$row = mysqli_fetch_row($result);
print_r($row);
// get the user_id
$useridquery="SELECT user.id FROM user WHERE email = '$email'";
echo $useridquery.'</br>';
$result = mysqli_query($link, $useridquery);
$row = mysqli_fetch_array($result);
echo "the result is:".print_r($row);
mysqli_close($link);
It outputs, for example:
Now we put some data to the database!INSERT INTO user (email, password) VALUES ('fdjisadds#as.com', 'cf860129c95e6afcdb9f9a390354915cde81c40c')We put email: fdjisadds#as.com and password: cf860129c95e6afcdb9f9a390354915cde81c40c to the database.SELECT email, password FROM user WHERE email='fdjisadds#as.com'We get: 1
As I checked that id=1, I found that it is some other user I put there via SQL-terminal and no email fdjisadds#as.com.
Well, obviously $row = mysqli_fetch_array($link, $useridquery) fetches an array of results. print_r($row) is then printing that array to the output stream and returns true which is concatenated to the string as 1.
From the PHP manual
If given a string, integer or float, the value itself will be printed. If given an array, values will be presented in a format that shows keys and elements. Similar notation is used for objects.
When the return parameter is TRUE, this function will return a string. Otherwise, the return value is TRUE.
So try this instead:
// This would concatenate the print_r's result to the string
echo "the result is:".print_r($row, true);
// Or better yet, use the following
echo "the result is:".$row[0]
EDIT
Regarding the questionaire's last comment:
ALTER TABLE `user`
CHANGE COLUMN `id` `id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT;
Be aware, though, that based on the limited insight you provided, this could break some other logic of yours.
Can I get from PHP a value back like the new id from the row I've just added to the database or should I make a SELECT to retrieve it?
<?php
$sql = "INSERT INTO my_table (column_1, column_2) VALUES ('hello', 'ciao')";
$res = mysql_query ($sql) or die (mysql_error ());
$sql = "SELECT column_id FROM my_table WHERE column_1 = 'hello'";
$res = mysql_query ($sql) or die (mysql_error ());
$row = mysql_fetch_assoc ($res);
$id = $row["column_id"];
print "my id is = $id";
?>
Use this: http://php.net/manual/en/function.mysql-insert-id.php
Selecting can be dangerous because an auto-increment often means that records may not otherwise be unique, and therefore not uniquely selectable without the id.
The proper way of getting the id is via mysql_insert_id(), as others have stated. The reason for this is that you may have other inserts taking place immediately following yours, and simply requesting the last id is not guaranteed to return the id that you expected.
$result = mysql_query("INSERT INTO tableName (col1) VALUES ('foo')");
print mysql_insert_id();
There is builtin support for it, mysql_insert_id() or something.