I have a PHP script that queries the database and returns a list of all the usernames in my database. Problem is, it is not printing anything and I think I am doing the while statement incorrectly, this is my code below:
<?php
include "init.php";
$stmt = "SELECT username FROM tbl_users ";
$result = $dbcon -> prepare($stmt);
$result->execute();
$result->store_result();
$count = 0;
while($row = mysqli_fetch_assoc($result)){
if($row['username']=="Ben"{
echo "Here";
}
//$count++;
}
?>
Even something as basic as this doesn't work:
<?php
include "init.php";
$stmt = "SELECT username FROM tbl_users ";
$result = $dbcon -> prepare($stmt);
$result->execute();
$result->store_result();
$count = 0;
while($row = mysqli_fetch_assoc($result)){
echo "Here";
//$count++;
}
?>
I can't also seem to increment the count too and it is not even printing the basic "Here"
The main problem is that you are not reading manual/examples properly.
mysqli_stmt_get_result() doesn't change the state of a statement. It returns a mysqli result. So you have to assign this returned value to a variable and than use this one.
Besides, you are using a database completely wrong way. Instead of selecting all rows from database you should always select the only data you need.
For your case the code would be like this.
include "init.php";
$name = "Ben";
$stmt = $dbcon->prepare("SELECT 1 FROM tbl_users WHERE username = ?");
$stmt->bind_param("s", $name);
$stmt->bind_result($found);
$stmt->execute();
$stmt->fetch();
if ($found) ... // here you go
For other cases you have to read the manual or a book carefully. and reproduce the code exactly.
Since there are multiple error in your code i managed to write a code am not sure following is best but it works
<?php
include "init.php";
$stmt = "SELECT username FROM tbl_users ";
$result = mysqli_query($sqlconnection, $stmt) or die($mysqli_load->error);
$count = 0;
while($row = mysqli_fetch_assoc($result)){
if($row['username']=="ben"){
echo "Here";
}
//$count++;
}
?>
few errors i found in your code are ) is missing here if($row['username']=="Ben"{ next to "ben"){
and use this type of connection
$link = new mysqli("localhost","user","pass","database");
Related
I am trying to create a guestbook that shows comments people have posted through an SQL query. I have successfully connected to the SQL database, but the query isn't showing anything. What is wrong here?
</form>
<h2>Current Posts</h2>
";
$sql = "SELECT * FROM 'guest_booklet' LIMIT 0, 30 ";
if ($numrows > 0) {
echo "$rows ['email']";
while ( $row = mysql_fetch_row($result) ){
$id = $row ['id'];
$name = $row['name'];
$email = $row['email'];
$message = $row['message'];
$message = n12br($message);
echo "<div>
$name - and email is $email <hr/>
$message
<div>";
}
}
mysql_close();
?>
</body>
</html>
1) Change
$sql = "SELECT * FROM 'guest_booklet' LIMIT 0, 30 ";
To
$sql = "SELECT * FROM `guest_booklet` LIMIT 0, 30 ";
=> Use Backtick instead of single quotes for enclosing table name.
2) You missed $result = mysql_query($sql);
3) You Missed $numrows = mysql_num_rows($result);.
4) Remove echo "$rows ['email']"; line. It's suspense from where it comes.
Mysql (Updated Code)
<?php
$sql = "SELECT * FROM `guest_booklet` LIMIT 0, 30 ";
$result = mysql_query($sql);
$numrows = mysql_num_rows($result);
if ($numrows > 0) {
while ( $row = mysql_fetch_row($result) ){
$id = $row ['id'];
$name = $row['name'];
$email = $row['email'];
$message = n12br($row['message']);
echo "<div>".$name." - and email is ".$email." <hr/>.".$message."<div>";
}
}
mysql_close();
?>
[Note: The mysql_* functions are deprecated, they have been removed from PHP 7, your code will stop working when you upgrade to that version. You should not write new code using them, use mysqli_* or PDO instead.]
Click To Know How can I prevent SQL-injection in PHP?
Mysqli (Updated Code)
<?php
//Connection
$servername = "YOUR-VALUES";
$dbname = "YOUR-VALUES";
$user = "YOUR-VALUES";
$password = "YOUR-VALUES";
$connection = mysqli_connect($servername,$user,$password,$dbname);
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT * FROM `guest_booklet` LIMIT 0, 30 ";
$result = mysqli_query($connection,$sql);
$numrows = mysqli_num_rows($result);
if ($numrows > 0) {
while ( $row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
$id = $row ['id'];
$name = $row['name'];
$email = $row['email'];
$message = n12br($row['message']);
echo "<div>".$name." - and email is ".$email." <hr/>.".$message."<div>";
}
}
mysqli_close($connection);
?>
You are missing a lot of stuff here.
You are closing the PHP tag but not opening it: <?php
You are never actually executing the query, you are missing a call to $result = mysql_query($sql);
You are using $numRows but never actually setting its value: `$numRows = mysql_num_rows($result);
You are using $row = mysql_fetch_row(...) but latter you are reading the resulting row as an associative array instead of a numeric index. You have to use mysql_fetch_assoc instead.
You are never actually connecting to the DB and selecting a schema, I assume you do that somewhere else, but you close the connection at the end. So make sure you are actually connecting.
It seems like you copied this from somewhere else but didn't do it right.
Things that are wrong
The syntax is not within PHP tags so won't do anything
Using single quote marks around a table name is invalid, you need backticks
(or nothing at all)
The $sql statement is never actually run
I assume $numrows is never set, so it will never be over 0
$rows['email'] is not set so it wont echo
$result is never set, so
you won't be able to iterate through it's rows
Original (incorrect) answer
Because you have LIMIT 0, 30. You are telling MySql to give you 0 results starting at index 30.
Also you are using mysql_fetch_row on a query string not a result set, you need to first actually run the query.
-- And indeed i am wrong with my assumption, here is the right thing you need to do:
"; //What is this?
$sql = "SELECT * FROM 'guest_booklet' LIMIT 0, 30 ";
$result = mysql_query($sql); //you need to add this
first I have a login form in c# that asks the user to input his email and password then these are data are sent to the domain then I retrieve it in php so I wrote a sql query to get the logged in user id and this works fine till the
if(isset($_POST['y']))
inside of it there is an insert query this query works but doesn't insert the user id ! I tried to figure it out but I dont know whats the problem .
here's the code :
<?php
session_start();
$con = mysqli_connect("mysql7.000webhost.com","a1945567_host","12345678ab","a1945567_db");
$sql = "SELECT ID FROM user WHERE Email = '".$_GET["txt_UserName"]."'AND Password = '".sha1($_GET["txt_Password"])."'";
$result = $con->query($sql);
$
$row = mysqli_fetch_array($result,MYSQLI_NUM);
$_SESSION['ID'] = $row[0] ;
echo "SUCCESS";
echo $usrID = $row[0];
if(isset($_POST['y'])){
$sql = "INSERT INTO `question13_interaction` (uid,no_0,no_1) VALUES ('".$usrID."','".$_POST['y']."',0)";
$con->query($sql);
// mysqli_query($con,$sql);
}
else if(isset($_POST["z"])){
//$sumcount = "INSERT INTO question13_interaction (sumcount)";
//$result = mysqli_query($con,$sumcount);
$sql1 = "INSERT INTO question13_interaction(uid,no_1,no_0) VALUES('".$row[0]."','".$_POST["z"]."',0)";
mysqli_query($con,$sql1);
}
//}
/*else
{
echo "FAILED";
}*/
?>
you have an extra"$" in the code:
$result = $con->query($sql);
$
probably should just be :
$result = $con->query($sql);
also I don;t think you want the echo in this statement - it will probably not set it to the correct value for your query:
echo $usrID = $row[0];
should be
$usrID = $row[0];
Except for the redundant "$", there is another question. There should be a white space between single quote and "AND", or mysql cann't parse the query correctly
Okay, I know there are a number of posts on this one, but I am still posting this questions because none of them are working yet.
I am trying to fetch result data with mysqli where the row count is fetching fine,but the row data is not.
Here is my code:
$query = $db->prepare("SELECT * from users where email = ?");
$query->bind_param("s",$loginEmail);
$query->execute();
$query->store_result();
$row_count = $query->num_rows;
echo $row_count;
if($row_count==1){
$row = $query->get_result;
$email = $row['email'];
echo $email;
}
So echoing out $rowcount gives the correct result, but I am not able to fetch the subsequent data for this row using fetch_array(). It displays nothing. I know I am going wrong somewhere. Any suggestions would be of great help.
You cannot use get_result() and store_result() at the same time.Besides, it's just superfluous.
$query = $db->prepare("SELECT * from users where email = ?");
$query->bind_param("s",$loginEmail);
$query->execute();
$res = $query->get_result();
$row = $res->fetch_assoc();
if ($row) {
$email = $row['email'];
echo $email;
}
This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
How do i “echo” a “Resource id #6” from a MySql response in PHP?
I am looking for the result out of a query, but it keeps giving me resource id #3.
The following is my code.
$type = "SELECT `sellingid` FROM `ticket` WHERE `ticketid` = $_GET[ticketid]";
$typeResult = mysql_query($type);
print_r($typeResult);
What step am I missing here?
You need to fetch the result. All you're doing is sending the query.
Be aware that if you are writing new code, you should use mysqli_ or PDO functions as your query is vulnerable to SQL injection and mysql_ functions are being deprecated. Hesitantly, below is a sample for mysql_fetch_assoc.
<?php
$sql = "SELECT `sellingid` FROM `ticket` WHERE `ticketid` = $_GET[ticketid]";
$result = mysql_query($sql);
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
// While a row of data exists, put that row in $row as an associative array
// Note: If you're expecting just one row, no need to use a loop
// Note: If you put extract($row); inside the following loop, you'll
// then create $userid, $fullname, and $userstatus
while ($row = mysql_fetch_assoc($result)) {
echo $row[sellingid];
}
mysql_free_result($result);
?>
Reference
$type = "SELECT `sellingid` FROM `ticket` WHERE `ticketid` = $_GET[ticketid]";
$typeResult = mysql_query($type);
$row = mysql_fetch_array($typeResult);
print_r($row);
More clear hint - use MySQLi class/functions, read this:
http://lt1.php.net/manual/en/mysqli-result.fetch-assoc.php
or if you like OOP approach more then
http://lt1.php.net/manual/en/mysqli-result.fetch-object.php
You are not actually fetching the results of your query. Below are two examples that use WHILE loops to fetch the results as rows. You can then grab the column values and work with them.
Incorrect and depreciated method, but working:
$type = "SELECT `sellingid` FROM `ticket` WHERE `ticketid` = $_GET[ticketid]";
$typeResult = mysql_query($type);
// for each row
while ($row = mysql_fetch_array($typeResult)) {
// grab the columns
$value = $row['column_name'];
}
I would recommend using MySQLi or PDO like to following (MySQLi):
$mysqli_connection = new mysqli("hostname", "username", "password", "database");
$type = "SELECT `sellingid` FROM `ticket` WHERE `ticketid` = $_GET[ticketid]";
$res = $mysqli_connection->query($type);
while($row = $res->fetch_array(MYSQLI_ASSOC)) {
$value = $row['column_name'];
}
$res->free();
$mysqli_connection->close();
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.