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;
}
Related
I started writing code for a basic voting system. But I got this error message.
Warning: mysqli_query() expects parameter 1 to be mysqli, bool given
in E:\My-WORLD\xampp\htdocs\php-tut\voting\vote.des.php on line 6
<?php
$con = mysqli_connect("localhost","root","","voting") || die("not
connected");
echo "connected";
if(isset($_POST['ele'])){
global $con;
$vote_ele = "update votes set ele = ele + 1";
$run = mysqli_query($con,$vote_ele);
if($run){
echo "voted to electronics";
}
else{
echo mysqli_error($run);
}
}
?>
Neither || or or should be ever written in connection to any mysqli function.
How to properly connect with mysqli:
$host = '127.0.0.1';
$db = 'voting';
$user = 'root';
$pass = '';
$charset = 'utf8mb4';
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
try {
$con = mysqli_connect($host, $user, $pass, $db);
mysqli_set_charset($con, $charset);
} catch (\mysqli_sql_exception $e) {
throw new \mysqli_sql_exception($e->getMessage(), $e->getCode());
}
Given this script is not the only one uses a mysql connection, store this code in a separate file named mysqli.php and then include it in other files. Therefore your current code will become
<?php
include 'mysqli.php';
if(isset($_POST['ele']))
{
$vote_ele = "update votes set ele = ele + 1";
$run = mysqli_query($con,$vote_ele);
echo "voted to electronics";
}
See - it is concise, tidy and reusable.
When you use $con = mysqli_connect("localhost","root","","voting") || die("not
connected"); you are assigning a bool to $con variable. So it is not mysqli anymore.
Also, When you use global $con you are overriding $con value, So it is not mysqli which you assigned in the pervious line anymore.
try this:
$con = mysqli_connect("localhost", "root", "", "voting");
if (mysqli_connect_errno())
die("Failed to connect to MySQL: " . mysqli_connect_error());
echo "connected";
if (isset($_POST['ele'])) {
// This will override $con value!!
// global $con;
$vote_ele = "update votes set ele = ele + 1";
$run = mysqli_query($con, $vote_ele);
if ($run) {
echo "voted to electronics";
}
else {
echo mysqli_error($run);
}
}
I have some code which works:
$user = 'xxx';
$pass = 'xxx';
$db='vive';
$host ='localhost';
$name = 'chris';
function test($user, $pass, $db, $host){
$mysqli = new mysqli($host, $user, $pass, $db);
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') '
. $mysqli->connect_error);
}
else{
echo 'Checkpoint 1.0 <br>';
return $mysqli;
}
}
$mysqli2 = test($user, $pass, $db, $host);
$sql = "SELECT * FROM `vive_user` WHERE `username` LIKE"."'$name'";
$result = $mysqli2->query($sql);
$num_results = $result->num_rows;
if ($result->num_rows>0) ...
I am able to connect to the database and pull the information that I want out of the database everytime. I wanted to clean up my code a little (all the details are not shown), so i made a new function register() out of the last part of the code. In this new function, i want to call on function test() to return me a database connection object which I can then use to perform queries:
<?php
$user = 'root';
$pass = 'root';
$db='vive';
$host ='localhost';
$name = 'chris';
function test($user, $pass, $db, $host){
$mysqli = new mysqli($host, $user, $pass, $db);
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') '
. $mysqli->connect_error);
}
else{
echo 'Checkpoint 1.0 <br>';
return $mysqli;
}
}
function register($name){
echo'test';
global $user;
global $pass;
global $db;
global $host;
$mysqli2 = test($user, $pass, $db, $host);
$sql = "SELECT * FROM `vive_user` WHERE `username` LIKE"."'$name'";
$result = $mysqli2->query($sql);
$num_results = $result->num_rows;
if ($result->num_rows>0)...
}
For some reason the function register() will never give me any values from the database. I am unable to get anything for $result. Any help is appreciated, I have been dancing around the problem for a few days now. Note that in my actual code I have these two functions in different php files.
The LIKE statement there in the query is missing %...% wrapper.
change the register to :
function register($name){
global $user;
global $pass;
global $db;
global $host;
$name = "%".$name."%"; // see here..
echo'test';
$mysqli2 = test($user, $pass, $db, $host);
$sql = "SELECT * FROM `vive_user` WHERE `username` LIKE"."'$name'";
$result = $mysqli2->query($sql);
$num_results = $result->num_rows;
if ($result->num_rows>0)...
}
and make sure the method is called
Why the where username like?
shouldn't it be where username = ?
also the quotes you used are redundant.
$sql = "SELECT * FROM vive_user WHERE username LIKE"."'$name'";
could just be
$sql = "SELECT * FROM vive_user WHERE username = '$name'";
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.!
This is one of my functions in my function.php file. Right now I'm just trying to get it to output 1 or 0 depending if the username is in the MYSQL DB.
function retrieve_single($col, $table, $item, $con) {
require_once('include/global.php');
$sql = "SELECT * FROM users WHERE username = Username1";
$conn = new mysqli($DBServer, $DBUser, $DBPass, $DBName);
if ($conn->connect_error) {
trigger_error('Database connection failed: '.$conn->connect_error, E_USER_ERROR );
}
$rs=$conn->query($sql);
if($rs === false) {
trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $conn->error, E_USER_ERROR);
} else {
$rows_returned = $rs->num_rows;
echo $rows_returned;
}
}
I keep changing stuff around trying to figure out what's wrong with it, all I know it is a sql error I keep getting. As of right now I have it written without the variables because of trying to figure out the problem.
The global.php:
$DBServer = 'localhost'; $DBUser = 'root'; $DBPass = ''; $DBName = 'social';
Can anyone help me out! I know the problem is simple, as this is my first time having this problem
The error you say that you're getting and you haven't shown us, is caused by this:
WHERE username = Username1 ";
^ ^ // missing quotes
It needs to have single quotes placed around Username1
I.e.:
WHERE username = 'Username1'";
If you're not already doing so, add error reporting to the top of your file(s) which will help during production testing.
error_reporting(E_ALL);
ini_set('display_errors', 1);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
Your function is very confusing. How are you calling it in the rest of your code?
function retrieve_single($col, $table, $item, $con) {
require_once('include/global.php');
$sql = "SELECT * FROM users WHERE username = Username1";
$conn = new mysqli($DBServer, $DBUser, $DBPass, $DBName);
if ($conn->connect_error) {
trigger_error('Database connection failed: '.$conn->connect_error, E_USER_ERROR );
}
$rs=$conn->query($sql);
if($rs === false) {
trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $conn->error, E_USER_ERROR);
} else {
$rows_returned = $rs->num_rows;
echo $rows_returned;
}
}
So your interface to retrieve_single() has the following $col, $table, $item and $con. But where are they used in the function? They seem 100% not used at all. So you are just calling it like retrieve_single() and hope it works? Seems odd.
Then within your function your query is this:
$sql = "SELECT * FROM users WHERE username = Username1";
Which makes little sense. It should at least have single quotes around it like this:
$sql = "SELECT * FROM users WHERE username = 'Username1'";
But it seems like it should be a variable like this:
$sql = "SELECT * FROM users WHERE username = '$Username1'";
But that said, where would $Username1 come from? Perhaps—looking at your interface variables—that should be $item like this:
$sql = "SELECT * FROM users WHERE username = '$item'";
Perhaps the whole function needs to be refactored to accommodate all the oddities I noticed like this:
function retrieve_single($col, $table, $item, $con) {
require_once('include/global.php');
$sql = "SELECT $col FROM $table WHERE username = '$item'";
if ($con->connect_error) {
trigger_error('Database connection failed: '.$con->connect_error, E_USER_ERROR );
}
$rs=$conn->query($sql);
if($rs === false) {
trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $con->error, E_USER_ERROR);
} else {
$rows_returned = $rs->num_rows;
echo $rows_returned;
}
}
Using this refactored function you would access it like this outside of the function:
$con = new mysqli($DBServer, $DBUser, $DBPass, $DBName);
retrieve_single('*', 'users', 'Username1', $con);
Then again, no idea how you are actually using your function in your larger code so this is me just winging it based on what you have presented. As it stands, the function itself—as you have presented it—is just problematic.
guys!I got a littile trouble.
There is connection.inc.php in "includes" folder:
<?php
function dbConnect($usertype, $connectionType = 'mysqli') {
$host = 'localhost';
$db = 'testdb';
if ($usertype == 'read') {
$user = 'readuser';
$pwd = 'testpass';
} elseif ($usertype == 'write') {
$user = 'writeuser';
$pwd = 'testpass';
} else {
exit('Unrecognized connection type');
}
if ($connectionType == 'mysqli') {
return new mysqli($host, $user, $pwd, $db) or die('Cannot open database');
} else {
try {
return new PDO("mysql:host=$host;dbname=$db", $user, $pwd);
} catch(PDOException $e) {
echo 'Cannot connect to database';
exit;
} // end of try block
} // end of $connectionType if
} // end of function
I use Linux for this test,and the lastest xampp 1.7.4
But things become worse when I use the following code:(I already have created my DB, and two users 'readuser' and 'writeuser')
<?php
// I use mysqli extension to connect my DB
require_once(includes/connection.inc.php);
// connect to DB
$conn = dbConnect('read');
// I need to get some picture infomations from images table
$sql = 'SELECT * FROM images';
$result = $conn->query($sql) or die(mysqli_error());
// find out how many records were retrieved
$numRows = $result->num_rows;
echo "We have $numRows pictures in DB";
?>
And when I load it in my browser:
Fatal error:Call to a member function query() on a non-object in /opt/lampp/htdocs/mysqli.php on line 9
So I guess $conn is not a object now,but It works when I write this code:
<?php
$host = 'localhost';
$user = 'readuser';
$pass = 'testpass';
$db = 'testdb';
$sql = 'SELECT * FROM images';
$conn = new mysqli($host, $user, $pass, $db);
$result = $conn->query($sql) or die(mysqli_error());
$numRows = $result->num_rows;
echo "We have $numRows pictures in DB";
?>
And it outputs:We have 8 pictures in DB
That's really a strange thing,I can't figure it out...Thanks guys!
Try saving the new mysqli() result as a variable, then return that variable instead. That logic makes no sense, I know, but I've had problems like that before.
$a = new mysqli($host, $user, $pwd, $db) or die ('Cannot open database');
return $a;