I am trying to truncate a table in my database. The error I get is
PHP Fatal error: Uncaught Error: Call to a member function query() on boolean in /var/www/html/rubynetwork_servers/truncate.php:4\nStack trace:\n#0 {main}\n thrown in /var/www/html/rubynetwork_servers/truncate.php on line 4
I have tried allsorts including looking on stackoverflow for the answers. My code is
<?php
error_reporting(E_ERROR | E_PARSE);
$con = mysqli_connect("localhost","root","-snip-","ruby");
$sql = "truncate table ruby_servers";
if ($con->query($sql) === TRUE) {
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
?>
The issue is with the mode you are programming. The right working code will be:
<?
error_reporting(E_ERROR | E_PARSE);
$mysqli = new mysqli("localhost", "username", "password", "databasename");
$sql= "TRUNCATE TABLE tbl_name";
//$mysqli->query($sql) // this will execute query
// Your checking conditions here.
if ($mysqli->query($sql) === TRUE) {
} else {
echo "Error: " . $sql . "<br>" . $mysqli->error;
}
$mysqli->close();
?>
Please note the way I have used 'new'. It is required by object-oriented way of programming.
You are applying object-oriented way to code to procedural mode.
'->' can only be used when you have a "new" object. So, use new.
Don't forget to close the connection after using it.
If it's still hard for you to understand then you may still use procedural mode of mysqli extension. Please don't use old mysql extension in new projects.
Reference:
http://php.net/manual/en/mysqli.quickstart.dual-interface.php
Related
Can someone please help me with a scoping issue. I've been looking at this for so long and I just don't see why this isn't working:
connection.php
<?php
$hostname = "xxx.xxx.xxx.xxx";
$username = "xxxxxxxx";
$password = "xxxxxxxx";
$db_name = "xxxxxxxx";
function isSecure() {
return (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off')
|| $_SERVER['SERVER_PORT'] == 443;
}
global $link;
$link = mysqli_connect($hostname, $username, $password, $db_name);
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit();
}
?>
builder.php
<?php
$path = $_SERVER['DOCUMENT_ROOT'];
$connection = $path . '/scripts/connection.php';
include_once ($connection);
session_start();
$club_id = $_SESSION['club_id'];
if (mysqli_connect_errno()) {
trigger_error("Failed to connect to MySQL: " . mysqli_connect_error());
exit();
}
$sql = "SELECT * FROM Workout_types
WHERE club_id=$club_id
ORDER BY type";
$result = mysqli_query($link, $sql) or trigger_error("Error description:" . mysqli_error($link) . "done");
?>
and I get the dreaded
mysqli_query() expects parameter 1 to be mysqli, null given in...
error.
Implementing the troubleshooting tips below, I changed a couple of lines.
builder.php:
require_once ("../scripts/connection.php");
connection.php:
if (!$link) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit();
}
It still doesn't work, but the errors are a bit different:
PHP Warning: mysqli_query(): Couldn't fetch mysqli in G:\PleskVhosts\example.com\httpdocs\workouts\builder.php on line 114
PHP Warning: mysqli_error(): Couldn't fetch mysqli in G:\PleskVhosts\example.com\httpdocs\workouts\builder.php on line 114
PHP Notice: Error description:done in G:\PleskVhosts\example.com\httpdocs\workouts\builder.php on line 114
where line 114 is the mysqli_query line.
I checked the GoDaddy docs, and that path is correct.
Just to prove that my include path was correct, I added this to connection.php:
global $test;
$test = "hello world";
Then in builder.php, I added a line echo $test;, and it printed hello world with no trouble whatsoever.
I should mention two other things could be helpful:
The code that I posted for builder.php is embedded in html code for a web page. It's the only php code in that file.
I originally wrote this code about 5 years ago, and it's been functioning flawlessly until I upgraded the php version on my server from 5.6.40 to 7.3.27. That's when it began to fail.
This is my error:
Fatal error: Uncaught Error:
Function name must be a string in /home/kmsrutge/public_html/Login2process.php:5
Stack trace:
#0 {main} thrown in /home/kmsrutge/public_html/Login2process.php on line 5
My code:
$db_server = $mysqli_connect($db_hostname, $db_username, $db_password);
if (!$db_server) die("Unable to connect to MySQL: " . $mysqli_error());
$mysqli_select_db($db_database) or die("Unable to select database: " . $mysqli_error());
$sql = "UPDATE Invoices SET Ord_ID = '$9144' WHERE Prod_ID = '98'; ";
$result = $mysqli_query($sql);
if($result) echo "UPDATE success!"; else echo "UPDATE failed!";
if($result)
{
echo "<p>New row was successfully inserted</p>".
$insertQueryCount = $insertQueryCount+1;
}
else
{
echo "<p>Your insert failed.</p>";
die($mysqli_error());
}
?>
I read that it may be a possible PHP 7 issue. Any idea on how to correct this?
Try changing the result variable to the following:
$result = mysqli_query($db_server, $sql);
Please check your code SQL function do not start with $ so you got the error. remove all $ from mysqli.
Please change the first line:
$db_server = mysqli_connect($db_hostname, $db_username, $db_password,$db_database);
you don't require mysqli_select_db function so comment that line and check.
Also the fifth line change like mysqli_query($db_server,$sql).
Please read (https://www.w3schools.com/php/php_mysql_intro.asp)this documents how to connect SQL and how to write a query.
I have a need to copy some rows from a database to a different database. I am experiencing difficulty. I have found several methods except none of the seem to work. The php version I am using is 5.4.
Both connections are in the same server, however everything else is different
This is the php code that I have found and it doesnt seem to work at all, I am unable to select from the first database
// Create connection
$wpdb = mysql_connect($servername, $username, $password);
// Check connection
if ($wpdb->connect_error) {
die("Connection failed: " . $wpdb->connect_error);
}
echo "Connected local successfully\n";
//$starttime = date("h:i:sa");
$mydb = mysql_connect('localhost','dbname','dbpassword', true);
// Check connection
if ($mydb->connect_error) {
die("Connection failed: " . $mydb->connect_error);
}
echo "Connected to Integrity successfully\n";
mysql_select_db($database, $wpdb);
mysql_select_db('wordpress_0', $mydb);
you can try with PDO.that provide a common interface to talk with many different databases.
$pdo = new PDO('mysql:host=example.com;dbname=database', 'user',
'password');
I refuse to offer support for mysql_ syntax, so I'll offer the upgraded version.
Almost entirely copied from the php manual... http://php.net/manual/en/mysqli.select-db.php
Code:
/* attempt and check connection including first database selection "test" */
if (!$mysqli = new mysqli("localhost", "root", "", "test")) {
// never show the actual error to the public
echo "<div>Database Connection Error: " , $conn->connect_error , "</div>";
exit();
}
/* return name of current default database */
if (!$result = $mysqli->query("SELECT DATABASE()")) {
// never show the actual error to the public
echo "<div>Syntax Error: " , $conn->error , "</div>";
} else {
echo "<div>Default database is: " , $result->fetch_row()[0] , "</div>";
$result->close();
}
/* change db to "mysql" db */
$mysqli->select_db("mysql");
/* return name of current default database */
if (!$result = $mysqli->query("SELECT DATABASE()")) {
// never show the actual error to the public
echo "<div>Syntax Error: " , $conn->error , "</div>";
} else {
echo "<div>Default database is: " , $result->fetch_row()[0] , "</div>";
$result->close();
}
$mysqli->close();
Output:
Default database is: test
Default database is: mysql
This is the whole php code:
<html>
<head>
<title>Connect to MariaDB Server</title>
</head>
<body>
<?php
$dbhost = 'localhost';
$dbuser = 'test';
$dbpass = 'pass';
$dbname = 'databseName';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
if(! $conn ) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully<br><br>";
function add($url, $category){
$sql = "INSERT INTO tt (url, category) VALUES ('$url', '$category');";
if(mysqli_query($conn, $sql)){
echo "Recorded.";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
}
if(function_exists($_GET['f'])){
$_GET['f']($_GET['url'], $_GET['cat']);
}
mysqli_close($conn);
?>
</body>
</html>
When I typed in "http://localhost/connect.php?f=add&url=www.google.com&cat=google" in my browser, this is the result:
Connected successfully
Error: INSERT INTO tt (url, category) VALUES ('www.google.com', 'google');
Notice: Undefined variable: conn in /var/www/html/connect.php on line 24
Warning: mysqli_query() expects parameter 1 to be mysqli, null given in /var/www/html/connect.php on line 24
Fatal error: Uncaught Error: Call to undefined function mysqli_errot() in /var/www/html/connect.php:27 Stack trace: #0 /var/www/html/connect.php(32): add('www.google.com', 'google') #1 {main} thrown in /var/www/html/connect.php on line 27
I tried a lot of other possible solutions I found online but none of them work. Please help, many thanks in advance!
In your function of:
function add($url, $category) {
// code
}
You are trying to use the variable $conn. Which is defined outside of the function.
You should pass that variable into the function:
function add($url, $category, &$conn) {
// code
}
if(function_exists($_GET['f'])){
$_GET['f']($_GET['url'], $_GET['cat'], $conn);
}
You could just use global $conn; inside the function, but it is suggested to avoid using global entirely. It makes for messy and dangerous code conditions in larger projects. Less control. By passing the $conn by reference, you are specifically ensuring the right value is going to be used.
As a side note: prepared statements would be good to use for your SQL since you are putting passed in values which can have malicious SQL inside them.
As a side side note: thiswhole process you are making looks a bit precarious and lots of care should be taken to whitelist function names and set up. You may wish to move it all to a class too.
I am working on converting some PHP code from mysql to mysqli. I have created an error and am unable to understand how to fix it. Any suggestions would be greatly appreciated.
The code looks like this:
<?php
include ("admin/includes/connect.php");
$query = "select * from posts order by 1 DESC LIMIT 0,5";
$run = mysqli_query($conn["___mysqli_ston"], $query);
while ($row=mysqli_fetch_array($run)){
$post_id = $row['post_id'];
$title = $row['post_title'];
$image = $row['post_image'];
?>
The error produced is: Fatal error: Cannot use object of type mysqli as array
The error is being called out on this line:
$run = mysqli_query($conn["___mysqli_ston"], $query);
In the line above $conn is a variable from the database connect file which has this code:
<?php
// Stored the db login credentials in separate file.
require("db_info.php");
// Supressing automated warnings which could give out clues to database user name, etc.
mysqli_report(MYSQLI_REPORT_STRICT);
// Try to open a connection to a MySQL server and catch any failure with a controlled error message.
try {
$conn=mysqli_connect ('localhost', $username, $password) or die ("$dberror1");
} catch (Exception $e ) {
echo "$dberror1";
//echo "message: " . $e->message; // Not used for live production site.
exit;
}
// Try to Set the active MySQL databaseand catch any failure with a controlled error message.
try {
$db_selected = mysqli_select_db($conn, $database) or die ("$dberror2");
} catch (Exception $e ) {
echo "$dberror2";
//echo "message: " . $e->message; // Not used for live production site.
exit;
// We want to stop supressing automated warnings after the database connection is completed.
mysqli_report(MYSQLI_REPORT_OFF);
}
?>
This line
$run = mysqli_query($conn["___mysqli_ston"], $query);
should be
$run = mysqli_query($conn, $query);
If you're migrating to mysqli, you should really read these docs at least.
The proper way to use a mysqli connection:
<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
$res = $mysqli->query("SELECT id FROM test ORDER BY id ASC");
while ($row = $res->fetch_assoc()) {
echo " id = " . $row['id'] . "\n";
}
?>
you should also consider utilizing mysqli's prepared statements