mysqli_query() expects parameter 1 to be mysqli [closed] - php

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have new to PHP programming and looking to create access a database I created. I have been able to get a successful connection going between PHP and my database, but the problem arises when I try to run a simple query.
I get the dreaded message mysqli_query() expects parameter 1 to be mysqli. I have seen numerous issues on this throughout the internet. I still am unable to resolve my situation. Can someone please address my code here:
$mysqli= mysql_connect($hostname,$username,$password,'japanesewords')
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
mysqli_query($mysqli, 'SELECT * FROM japanesedefinition') or die(mysql_error($mysqli));

Why don't you use PDO?
<?php
try {
// config
$dsn = 'mysql:dbname=japanesewords;host=127.0.0.1;charset=utf8';
$username = 'root';
$password = '';
$options = array(
// necessary for rowCount() on SELECT
PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true,
// for catching SQL errors as PDOException
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
// default fetch mode is used for iterating PDOStatement by foreach()
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ,
);
// connect
$pdo = new PDO($dsn, $username, $password, $options);
// execute SQL
$stmt = $pdo->query('SELECT * FROM japanesedefinition');
// check row count
if (!$stmt->rowCount()) {
throw new Exception('no data');
}
// fetch results and display
echo "<p>\n";
foreach ($stmt as $row) {
printf("foo: %s; bar: %s;<br />\n", $row->foo, $row->bar);
}
echo "</p>\n";
} catch (Exception $e) {
printf("<p>%s</p>\n", $e->getMessage());
}
I don't know whether you're japanese or not, remark the summary in Japanese for connectiong to MySQL with PHP.
http://qiita.com/mpyw/items/b00b72c5c95aac573b71

Related

Why is there a fatal error although it has echo out "connect successfully" [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
The following code is part of the main page that connect database with the main page. mainpage.php
<?php
error_reporting(E_ALL);
include_once dirname(__FILE__).'\dbh.php';
session_start()
?>
this part of the code is the connection between database with the website. dhb.php
<?php
$host = "localhost";
$user = "root";
$password = "root";
$dp="ia";
$port=8889;
$link=mysqli_init();
$conn = mysqli_real_connect($link, $host, $user , $password , $dp, $port);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
$sql = "SELECT * FROM table player";
$result = $conn-> query($sql);
?>
This image is how the website tells me:
mysqli_real_connect() returns a boolean. It does not return a valid mysqli object. You create the mysqli object with mysqli_init().
You are overcomplicating the database connection. You only need three lines to connect properly.
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli('localhost', 'user', 'pass', 'db');
$mysqli->set_charset('utf8mb4'); // always set the charset
If you are only starting to learn PHP then you should learn PDO instead of mysqli. PDO is much easier and more suitable for beginners. Start here https://phpdelusions.net/pdo & https://websitebeaver.com/php-pdo-prepared-statements-to-prevent-sql-injection

PHP PDO SQLSTATE[HY000] [1044] Access denied for user ''#'localhost' to database 'events' [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
When I connect to the database using MySQLi, everything works as it should, but with PDO or with CI database methods, I get this error : SQLSTATE[HY000] [1044] Access denied for user ''#'localhost' to database 'events'.
try {
$link = new PDO("mysql:host=localhost;dbname=events;");
$link->setAttribute(PDO::ATTR_MODE, PDO::ERR_MODE_EXCEPTION);
//create statement;
$statement = $link->prepare($sql);
$statement->bindParam(":username", $login_request["username"]);
$statement->bindParam(":password", $login_request["password"]);
$statement->execute();
$rows = $statement->fetchColumn();
return ($rows == 1) ? true : false;
}
catch(PDOEXCEPTION $e){
echo $e->getMessage();
}
Try to connect like this.
Put it in a separate file connection.php and include it in every page you run queries
try{
$connect = new PDO('mysql:host=localhost;dbname=YOUR_DB_NAME;charset=utf8', 'USERNAME', 'PASSWORD',
array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"));
$connect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOException $e){
die('Error connecting to database');
}
then you can run queries in every page like this
$stmt = $connect->prepare("SELECT * FROM table WHERE id=:id");
$stmt->bindParam(':id', $id);
$stmt->execute();

Is this code with PDO good (PHP)? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
I'm new to PHP and I've followed a few tutorials on PDO after learning the basics of the language and I was just wondering if my code here is correct and what you guys'd suggest I can change to make it more secure, faster, more efficient, you name it...
I've followed numerous tutorials to achieve this result and therefore I thought I'd ask you guys as not every tutorial on the web on PHP (there are so many) are reliable sources to learn best practices and writing good code.
Here's the code I have. It only inserts the string 'Bill Gates' to the database, called 'pdotest', table 'tableOne' and row 'rowOne'. I've used persistent db connection because that's supposed to make the web application faster. I'm sure you guys can enlighten me on how to use this persistent connection thing correctly, I may have not fully understood how to use this in my code.
<?php
// DB connect configuration
$user = 'user';
$pass = 'password';
// Database connection
try {
$conn = new PDO('mysql:host=localhost;dbname=pdotest', $user, $pass, array(
PDO::ATTR_PERSISTENT => true
));
}
catch(PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
$conn = null;
die();
}
// Data to insert (Bill Gates = Hero #1)
$data = 'Bill Gates';
try {
// The insert query
$sql = "INSERT INTO tableone (rowOne) VALUES (:rowOne)";
$q = $conn->prepare($sql);
$q->execute(array(':rowOne'=>$data));
// Example INSERT query with multiple VALUES
// $q->execute(array(':rowOne'=>$data, ':rowTwo'=>$dataTwo));
}
catch(PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
$conn = null;
die();
}
?>
this is apparently inefficient as your PHP have to run twice more code than needed.
the below code is enough
<?php
// DB connect configuration
$user = 'user';
$pass = 'password';
// Database connection
$dsn = "mysql:host=localhost;dbname=pdotest;charset=utf8";
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
);
$conn = new PDO($dsn, $user, $pass, $opt);
$data = 'Bill Gates';
$sql = "INSERT INTO tableone (rowOne) VALUES (?)";
$q = $conn->prepare($sql);
$q->execute(array($data));
some highlights
use persistent connection only if you certainly know what are you doing
set exception mode if you are expecting exceptions
DO NOT catch them only to die. PHP can die all right by itself.

myqsli -> fetch TO pdo [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 9 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Improve this question
i need to change this mysqli to to working PDO:
$user = "name";
$pass = "password";
try {
$dbh = new PDO('mysql:host=host;dbname=dbname', $user, $pass);
$dbh = null;
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
$sth = $dbh->prepare("SELECT * FROM table");
$sth->execute();
while ($user = $sth->fetch(PDO::FETCH_ASSOC)) {
echo $user[1];
}
Using this fetch i dont get the expected result..
but this doesnt work, anybody could check it?
greetings
Why are you setting $dbh to null?
$dbh = new PDO('mysql:host=host;dbname=dbname', $user, $pass);
$dbh = null; <--remove this line.
It should be either:
while ($user = $sth->fetch(PDO::FETCH_ASSOC)) {
echo $user['username']; // Put the actual column name here, I'm just guessing
}
or:
while ($user = $sth->fetch(PDO::FETCH_NUM)) {
echo $user[1];
}
PDO::FETCH_ASSOC is like mysqli_fetch_assoc, and PDO::FETCH_NUM is like mysqli_fetch_row.

Migrating MySQL code to PDO [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am new to PDO and am attempting to convert my existing PHP/MYSQL code to meet PDO standards.
The problem i am having is I can connect to the database but no results are being shown and no errors are being displayed.
This is my database:
$db2 = new PDO('mysql:host=localhost;dbname=DATABASENAME;charset=utf8', 'USERNAME', 'PASSWORD');
$db2->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db2->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
I am using
include 'db.php';
to include the above database details in my main PHP script.
My main script using the following as a select statement to display the rows which match the criteria:
<?
foreach($db2->query('SELECT view_invoice FROM user_info where username = "$timeapp_username"') as $inrow) {
$inrow['view_invoice']; //etc...
}
?>
On running this I get no errors but no results displayed. I cannot spot what I am doing wrong. Can anyone advise what I am doing wrong here?
The query function is unsafe and should be used only for queries that will not return data, like UPDATE, DELETE, INSERT...
To make safe and working SELECT queries, prepare your query with the PDOStatement. See:
//Example querystring
$id = $_GET['id'];
try{
//Instantiate PDO
$pdo = new PDO('dsn', 'user', 'password');
//Create the statement
$statement = $pdo->prepare("SELECT * FROM `my_table` WHERE `id`=:id");
//Now you can bind values to the statement. This will automatically escape the values
//Defines the type of the value that you'll bind (optional)
$data_type = (is_numeric($id)) ? PDO::PARAM_INT : PDO::PARAM_STR;
//Replace the :id in the query by the value retrieved from the querystring
$statement->bindValue(':id', $id, $data_type);
//Now, let's execute our statement
$statement->execute();
//If the query has returned any rows, we can iterate over it
if ($statement->rowCount() > 0)
{
foreach ($statement->fetchAll() as $result)
{
//Now you can retrieve the values using the defined fetch method.
//Example with associative fetch mode:
echo 'My name is '.$result['name']."!";
echo '<br />';
}
}
else
{
//No results found
}
} catch (PDOException $pe){
die("An error has occurred: ".$pe->getMessage());
}

Categories