PHP: Trouble using mysqli - php

I used this php code in order to make a select on my database:
$check = 'true';
$request = trim(strtolower($_REQUEST['username']));
$query_username=sprintf("SELECT * FROM users WHERE username = '$request'");
$database= mysql_pconnect($hostname, $username, $password) or die(mysql_error());
mysql_select_db($mydatabase, $database);
$resultUsers = mysql_query($query_username, $mydb) or die(mysql_error());
$usernameFound= mysql_num_rows($resultUsers);
if ($usernameFound> 0) {
$check = 'false';
}
The above code works good.
But now I'm trying to convert it using mysqli. So I rewrited the code in this way:
$connectiondb = new mysqli($hostname, $username, $password, $database);
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$request = trim(strtolower($_REQUEST['username']));
$query=sprintf("SELECT * FROM utente WHERE username = '$request'");
if(!$result = $connectiondb->query($query)){
die('Error in query execution [' . $connectiondb->error . ']');
}
$rows = $result->num_rows();
$result->free();
$connectiondb->close();
if($rows>0){
$check = 'false';
}
But this does not work! No error is generated, but I can't obtain the right result.
What can be the problem?

It should be $rows = $result->num_rows;
I also recommend you switch to using prepared statements when using mysqli, your current code is vulnerable to injections.

Related

PHP SQL request returning null value

I'm just starting PHP and keep returning null for my SQL query. I am successfully connected to the database and have copied and pasted the query even straight from the database.
<?php
$servername = "localhost";
$username = "username";
$password = "";
$dbname = "customerbasics";
$conn = new mysqli($servername, $username, $password);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM `orders`";
$result = $conn->query($sql);
if ($result == NULL){
echo 'No results';
};
if ($result->num_rows > 0) {
echo 'Rows returned';
}
} else {
echo "0 results";
}
$conn->close();
?>
This is what the browswer prints:
Update: Error checking added:
Fatal error: Uncaught mysqli_sql_exception: No database selected
Add the fourth parameter to your connection function
$conn = new mysqli($servername, $username, $password, $dbname);
You have forgotten the database name in your connection. For more information, you can go here. Plus I recommend you to learn PDO or prepared statements
First, you have to select database before executing a query:
mysqli_select_db($conn, $dbname);
Then execute your query:
$sql = "SELECT * FROM `orders`";
Other way, you can also specify database name directly every executing a query:
$sql = "SELECT * FROM $dbname.`orders`";

convert mySQL to mySQLi - using a class

The previous programmer had used a class called database that has the connection string and a bunch of functions. I now have to convert this to MySQLi and I am at a loss.
class database {
var $sql='';
var $result='';
function database( $host='localhost', $user, $pass, $db) {
// perform a number of fatality checks, then die gracefully
if (!function_exists( 'mysql_connect' )) {
//or die( 'FATAL ERROR: MySQL support not available. Please check your configuration.' );
exit();
}
bla..bla..bla - bunch of code goes here
function get_events_by_user($username) {
$sql = "SELECT event_id FROM user_events WHERE username = '$username'";
$result = mysql_query($sql);
return $result;
}
}
I tried
var $link=mysqli_connect('localhost', $user, $pass);
to use as
$result = mysqli_query($link,$sql);
but I can not use expression as a variable value and I don't know what else to do.
Thanks a bunch! :)
try to use this.
I think it solves your problem.
<?php
$link = mysqli_connect("localhost", $user, $pass, $databaseName);
if (!$link) {
die('Connect Error (' . mysqli_connect_errno() . ') ' . mysqli_connect_error());
}
mysqli_set_charset($link, "utf8");
?>
just bring the $link in every query.
$link = mysqli_connect("localhost", $user, $pass, $db);
function get_events_by_user($username) {
$sql = "SELECT event_id FROM user_events WHERE username = '$username'";
$result = mysqli_query($link,$sql);
return $result;
}

I can't run my PHP program and I received several errors

This is the image of the warning I got
I am new and I really want to learn PHP.
<?php
include 'mysql.conf.php';
if(isset($_POST['submit']))
{
if(!empty($_POST['user']) && !empty($_POST['password']))
{
$user = $_POST['user'];
$password = $_POST['password'];
$select = "SELECT * FROM admin where user=$user && password=$password";
$sql=mysql_query($select) or die(mysql_error());
if($sql)
{
echo "Login";
}
else
{
echo "Cannot Login";
}
}
}
?>
Below is my code for the mysql.conf.php
<?php
$name = "localhost";
$user = "root";
$pass = "gasamul";
$connect = mysql_connect($name, $user, $pass) or die(mysql_error());
$db = "portfolio";
if($connect)
{
$db = mysql_select_db($db) or die(mysql_error());
if($db)
{
//echo 'Database Connect';
}
}
else
{
echo 'Database can\'t connect';
}
?>
The name of my database is portfolio. I also named my table admin.
Since the error is stating clear that mysql_* extension is already deprecated and it is suggesting that you use mysqli_* or PDO extension.
Lets try the first option - mysqli_*. We establish first the connection to your database in mysql.conf.php:
$connect = new mysqli("localhost", "root", "gasamul", "portfolio");
/* CHECK CONNECTION */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
Then, we can proceed with logintest.php:
include 'mysql.conf.php';
if(isset($_POST['submit']) && !empty($_POST['user']) && !empty($_POST['password']))
{
if($stmt = $con->prepare("SELECT * FROM admin WHERE user = ? AND password = ?")){ /* PREPARE YOUR QUERY */
$stmt->bind_param("ss", $_POST['user'], $_POST['password']); /* BIND THESE TWO VARIABLES TO THE QUERY ABOVE RESPECTIVELY; s STANDS FOR strings */
$stmt->execute(); /* EXECUTE THE QUERY */
$stmt->store_result(); /* STORE THE RESULT */
$noofrows = $stmt->num_rows; /* GET THE NUMBER OF RESULT */
if($noofrows > 0){ /* CHECK IF RESULT IS MORE THAN 0 */
echo "Login";
} else {
echo "Cannot Login";
}
$stmt->close(); /* CLOSE THE PREPARED STATEMENT */
}
}
You can also check out password_hash() for securing your password in your database.

How do I get one row of data from mySQL table using php?

Here is an example of the current PHP code I have. I simply want to grab one row from the table, but it returns this error:
Call to a member function fetch_assoc() on a non-object
Any insight would be appreciated.
$pathname = "C:\Users\BL\Documents\GitHub\Moozik\music";
$files = scandir($pathname);
$server = "localhost";
$user = "root";
$pass = "";
while ($files[0] == "." || $files[0] == "..") {
array_shift($files);
}
print_r($files);
$song = $pathname . '\\' . $files[0];
$conn = new mysqli($server, $user, $pass);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT song_path FROM song_data";
$result = mysqli_query($conn, $sql);
while($row = $result->fetch_assoc()) {
$its = $row["song_path"];
printf($its);
}
mysqli_close($conn);
Point 1 :
You have mixed mysqli Object-oriented and Procedural methods...Use any one
Point 2:
$conn = new mysqli($server, $user, $pass);
// Here You missed database to be selected
Point 3:
$result = mysqli_query($conn, $sql); // Used procedural method But Connection is by Object Oriented method
here is a full object oriented method
$conn = new mysqli($server, $user, $pass, $database);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT song_path FROM song_data";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
$its = $row["song_path"];
echo $its;
}
$conn->close();
You can use
$row=mysqli_fetch_array($result)
You don't even have to use while since you wanna fetch only one row. IF you wanna fetch more than one row, then you can use the while.
You can use this.
$row=mysqli_fetch_row($result)
It will fetches the one row from result set..
Hope this will help.!

Error occurred ... no database selected

I'm trying to connect to a database, check a column for whether a value exists or not, then execute a function based on whether or not that value exists.
Here's my code.
$con = mysql_connect('localhost','root','','users');
$sql = "SELECT * FROM allUsers WHERE username = '".mysql_real_escape_string($_POST["username"]) . "'";
$result = mysql_query($sql,$con) or die("Error occurred in [$sql]: " . mysql_error());
$count = mysql_num_rows($result);
if ($count != 0){
echo "Username is already taken";
echo "$count";
mysql_close($con);
}
else{
createUser($_POST["name"],$_POST["username"],$_POST["password"],$_POST["email"]);
}
The thrown error is:
Error occurred in [SELECT * FROM allUsers WHERE username = 'Admin']: No database selected.
I'm almost entirely sure that it comes from the $result line, but haven't a clue as to why.
I feel like this is a simple solution, and I'm just missing something minor.
I'm very new to MySQL (today is my first day, actually), so please keep solutions as simple as possible.
You forgot to call mysql_select_db after connecting:
$con = mysql_connect('localhost','root','');
mysql_select_db('users', $con);
Unlike MySQLi or PDO, mysql_* libraries does not take database as argument on the connection string, however if you were to migrate to either MySQLi or PDO.
MySQLi:
$con = new mysqli('localhost', 'root', '', 'users');
PDO:
$con = new PDO('mysql:host=localhost;dbname=users', 'root', '');
In MySQLi your code would look like this:
<?php
$host = "localhost";
$user = "root";
$pass = "";
$database = "users";
$con = mysqli_connect($host,$user,$pass,$database);
if($con->connect_error)
die('Connect Error (' . mysqli_connect_errno() . ') '. mysqli_connect_error());
$stmt = $con->prepare("SELECT * FROM allUsers WHERE username = ? LIMIT 1");
$stmt->bind_param('s',$_POST["username"]);
if (!$stmt->execute())
die('Failed to excute with error ' . $con->error);
$stmt->store_result();
$count = $stmt->num_rows;
$stmt->close();
if ($count > 0)
{
echo "Username is already taken.";
}
else
{
createUser($_POST["name"],$_POST["username"],$_POST["password"],$_POST["email"]);
}
I think your error is quite obvious, you need to specify the database you want.
mysql_select_db("databaseName", $con);
With that taken care of, please, please don't use mysql_ libraries the are vulnerable to SQL injection and will soon be removed.

Categories