Cannot fetching data with php in Linux - php

I want to connect to a database and fetch data , But I can't do that . Would you mind helping me what is the problem ? By the way I use Linux Ubuntu. Here is the code and info :
<?php
// DB name : db
// Table name : users
// Columns : username , password
mysql_connect("localhost" "root" "root") or die(mysql_error());
mysql_select_db("db") or die(mysql_error());
$query = mysql_query("SELECT * FROM users") or die(mysql_error());
$fetch = mysql_fetch_array($query);
echo "Username :".$fetch['username'];
echo "Password :".$fetch['password'];
mysql_close();
?>

You forgot to separate the variables on your mysql_connect statement. Do like this
mysql_connect("localhost", "root", "root") or die(mysql_error());
------^ -----^ // Added commas here
Do it like this:
while ($fetch = mysql_fetch_array($query, MYSQL_ASSOC)) {
echo "Username :".$fetch['username'];
echo "Password :".$fetch['password'];
}
Migrating to MySQLi from mysql_*, read here
Most importantly, stop using mysql_* functions as they are deprecated. Switch to MySQLi or PDO.

Related

PHP get data from DB not working [duplicate]

This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 6 years ago.
Can you figure out my code? All the code does is: No database selected It won't get the data from the db. The server os is Ubuntu or OS X. I been pulling my hair out for hours.
<?php
mysqli_connect("localhost", "root", "");
mysql_select_db("hit-counter");
$sql_get_count = mysql_query("SELECT id FROM hit_info ORDER BY id DESC LIMIT 1");
if($sql_get_count === FALSE) {
die(mysql_error());
}
while($row = mysql_fetch_assoc($sql_get_count)) {
print_r($row);
}
?>
I try this, it does the same
<?php
mysql_connect("localhost", "root", "");
mysql_select_db("hit-counter");
$sql_get_count = mysql_query("SELECT id FROM hit_info ORDER BY id DESC LIMIT 1");
if($sql_get_count === FALSE) {
die(mysql_error());
}
while($row = mysql_fetch_assoc($sql_get_count)) {
print_r($row);
}
?>
you have an error in your code. You use mysqli_ function to connect the server but you use a deprecated function mysql_ to select the database.
Try this code:
mysqli_connect("localhost", "root", "");
mysqli_select_db("hit-counter");
Another option when using mysqli_ is to select the database you want during connecting to the server:
$link = mysqli_connect("127.0.0.1", "my_user", "my_password", "my_db");
You didn't mention database name:try this
<?php
$con = mysqli_connect("127.0.0.1","root","654321","testV2") or die("Some error occurred during connection " . mysqli_error($con));
// Write query
$strSQL = "SELECT id FROM did ORDER BY id DESC LIMIT 1";
// Execute the query.
$query = mysqli_query($con, $strSQL);
while($result = mysqli_fetch_array($query))
{
echo $result["id"]."
";
}
// Close the connection
mysqli_close($con);
?>
You cannot interchange the mysql and mysqli functions, please modify your mysql_select_db to mysqli_select_db.
I will not go over the errors everyone else has pointed out. But, I will mention one that no one has. I think the - character in your database name will also cause problems. You should enclose the database name in back ticks. The back tick is this ` character, most likely the far left key above the TAB key. If you had error reporting turned on, or looked at your php error log, you would have seen the error.

(PHP) LogIn script Doesn't work

<?php
//CONNECT TO DATABASE
$db_host="localhost";
$db_username="root";
$db_pass="";
$db_name="admin";
#mysql_connect("$db_host","$db_username","$db_pass","$db_name")
or die ("not connect");
#mysql_select_db("$db_name") or die ("no database");
echo "succesful connection";
//THEN I CHECK THE VALUES FROM MY FORM
if($_SERVER ['REQUEST_METHOD']=='POST'){
$username=$_POST['username'];
$password=$_POST['password'];
$username=htmlspecialchars($username);
$password=htmlspecialchars($password);
//SEARCH INTO MY DATABASE TABLE
$SQL="SELECT * FROM members WHERE`` username=$username AND password=$password ";
$result=mysql_query($SQL);
//BASED ON MY RESULTS I GIVE TO SESSION VARIABLE A VALUE 1 OR "" AND REDIRECT TO INDEX.PHP
if($result){
$num_rows=mysql_num_rows($result);
if($num_rows>0){
session_start();
$_SESSION['check']="1";
header ("Location:index.php");
}
else{
session_start();
$_SESSION['check']="";
header ("Location:index.php");
}
}
}
?>
#mysql_connect and #mysql_select_db: Please don't do that,
Use mysqli instead of the deprecated mysql extension, see Why shouldn't I use mysql_* functions in PHP?
There is a reason why functions maybe throws errors, you should handle it, instead of using # so they don't show up.
To your problem:
Look at your sql statement:
$SQL="SELECT * FROM members WHERE`` username=$username AND password=$password ";
That doesn't work, you pass $password as plain text for the password, not the value of this var, try:
$SQL='SELECT * FROM members WHERE username="' . $username . '" AND password="' . $password . '";
I think you have issue in your sql query. So try this
$SQL="SELECT * FROM members WHERE `username`='".$username."' AND `password`='".$password."' ";
Issue :
1) You are using direct $username without single quote so if username is string it will not work
2) check that special character you are using after WHERE

mysql_select_db("db_name") doesn`t work with freshly created DB

My PHP code
$handle = mysql_connect();
echo ($handle) ? "Connected to mysql" : "Could not connect";
$db = mysql_select_db("users");
if ($db ==false) {
die(' Could Not select database so Exiting;');
} else {
echo " Database selected;";
}
mysql_close($handle);
This code works with default mysql databases like "test" or "mysql".
My Data Base creation code sequence:
mariadb[none]> create database users;
mariadb[none]> use users;
mariadb[users]> create table registered_users ( user_name varchar(18), user_pass varchar(18) );
You should use mysqli_ functions instead:
$localhost=''; //SQL Host
$dbuser=''; //Database Username
$dbpass=''; //Database Password
$dbname=''; //Database Name
$connect=mysqli_connect($localhost,$dbuser,$dbpass,$dbname);
mysql_ functions are deprecated.
What's basically happening is you are connected to test by default please supply parameters mysql_connect("localhost", "username", "password") ;
Should work with no doubt.

How to retrieve multiple rows from database in PHP

I am trying to retrieve multiple rows from the database and process it for response as service using php code, but I wouldn't retreive all values, only first row from the table is displaying, how can I make dis to work?
Here is my code:
$servername="localhost";
$username="root";
$conn= mysql_connect($servername,$username)or die(mysql_error());
mysql_select_db("testing",$conn);
$sql="insert into login (src,dest)values('$from','$tona')";
$result=mysql_query($sql,$conn) or die(mysql_error());
$res = mysql_query("SELECT * FROM login");
$numrows = mysql_num_rows($res);
setcookie('a',$numrows);
Note the use of _mysql is discouraged for new development ... please read this on selecting a new API
This is pretty basic but you need to loop the returned result like so :
$res = mysql_query("SELECT * FROM login");
while ($row = mysql_fetch_array($res, MYSQL_BOTH)) {
// your columns are accessible using
$row['columnname'];
// or
$row[columnnumber];
}
Docs for mysql_fetch_array are here
mysql_query returns a resource on success or false on failure
do like this
<?php
$servername="localhost";
$username="root";
$conn= mysql_connect($servername,$username)or die(mysql_error());
mysql_select_db("testing",$conn);
$sql="insert into login (src,dest)values('$from','$tona')";
$result=mysql_query($sql,$conn) or die(mysql_error());
$res = mysql_query("SELECT * FROM login");
$numrows = mysql_num_rows($res);
while ($result=mysql_fetch_array($res)){
echo $result['src']."<br/>";
}
setcookie('a',$numrows);
mysql_* is deprecated
use
$res = mysql_query("SELECT * FROM login");
$numrows = mysql_num_rows($res);
while($row = mysql_fetch_assoc($res))
{
print_r($row);
}
I see that you using mysql instead of mysqli. Try changing to mysqli instead, because this will become the new standard. As of version PHP 5.5.0 mysql will become deprecated.

PHP login script SQL error

I'm fairly new to SQL and PHP.
I'm trying to write a simple login script. I have a form in a HTML document that I have proved posts the correct data into the 2 variables required but my script fails when it executes the SQL...
I've also tested the SQL in mysqlWorkbench and I get the result I want ???
Please help.
Here is my script:
<?PHP
$odbc = mysql_connect('localhost', 'root', '') or die ("could not connect to database");
mysql_select_db('examresults', $odbc) or die("Could not find database");
// username and password sent from form
$username=$_POST['username'];
$password=$_POST['password'];
$sql='SELECT * FROM tuser where username = '.$username.' and password = '.$password.'';
$result = mysql_query($sql, $odbc) or die ("Error in SQL");
// Mysql_num_row is counting table row
$count=mysql_num_rows($result);
//If result matched username and password, table row must only equal 1 row
if($count==1)
{
header("location:exammenu.php");
}
else
{
echo 'username and password do not match';
}
?>
Note: mysql_* functions are deprecated, you should not use them anymore. Your code is also vulnerable to SQL Injections.
Using mysql_error instead of just printing out "Error in SQL" would give us (and you) a more detailed sql error message. But most likely it is failing because you forgot to put " " around your strings in the query.
$sql='SELECT * FROM tuser where username = "'.$username.'" and password = "'.$password.'"';
If you're really going to need to use mysql, at least sanitize your input. Also note the quotes in the $sql variable. This should work (though not tested):
<?PHP
$odbc = mysql_connect('localhost', 'root', '') or die ("could not connect to database");
mysql_select_db('examresults', $odbc) or die("Could not find database");
// username and password sent from form
$username=mysql_real_escape_string($_POST['username'], $odbc);
$password=mysql_real_escape_string($_POST['password'], $odbc);
$sql=sprintf('SELECT * FROM tuser where username = "%s" and password = "%s"', $username, $password);
$result = mysql_query($sql, $odbc) or die ("Error in SQL");
// Mysql_num_row is counting table row
$count=mysql_num_rows($result);
//If result matched username and password, table row must only equal 1 row
if($count==1)
{
header("location:exammenu.php");
}
else
{
echo 'username and password do not match';
}
I suggest using sprintf to format your sql statement to make it easier to spot such errors.
The query should be as below:
$sql='SELECT * FROM tuser where username = "'.$username.'" and password = "'.$password.'"';
you can try this code. i think it will work correctly.
<?PHP
$odbc = mysql_connect('localhost', 'root', '') or die ("could not connect to database");
mysql_select_db('examresults', $odbc) or die("Could not find database");
// username and password sent from form
$username=$_POST['username'];
$password=$_POST['password'];
$sql="SELECT * FROM tuser where username = '".$username."' and password = '".$password."'";
$result = mysql_query($sql, $odbc) or die ("Error in SQL");
// Mysql_num_row is counting table row
$count=mysql_num_rows($result);
//If result matched username and password, table row must only equal 1 row
if($count==1)
{
header("location:exammenu.php");
}
else
{
echo 'username and password do not match';
}
?>

Categories