This question already has answers here:
How to change mysql to mysqli?
(12 answers)
Closed 1 year ago.
I need some help in converting my script from using mysql to mysqli I have been trying for ever to do this and keep getting errors I have read articles on how to do this and still can get it to work.
Here is the original working script below.
<?php
require_once ('./mysqli_connect.php'); // Connect to the db.
if (isset($_POST['submitted'])) {
if ($dbc = mysql_connect (DB_HOST, DB_USER, DB_PASSWORD)) { // Make the connnection.
if (!mysql_select_db (DB_NAME)) { // If it can't select the database.
// Handle the error.
trigger_error("Could not select the database!\n<br />MySQL Error: " . mysql_error());
exit();
} // End of mysql_select_db IF.
} else { // If it couldn't connect to MySQL.
// Print a message to the user, include the footer, and kill the script.
trigger_error("Could not connect to MySQL!\n<br />MySQL Error: " . mysql_error());
exit();
} // End of $dbc IF.
// grab the tag
$tag = mysql_real_escape_string($_POST['tag']);
// see if the tag already exists and potentially what the current count is
$query = "SELECT id, count, page FROM tags WHERE tag='$tag'";
$result = mysql_query($query);
//--if there is a row, that means the tag exists
if(mysql_num_rows($result))
{
//--pull out the tag ID and the current count and increment by one.
$tag_info = mysql_fetch_array($result);
$tag_info_id = $tag_info["id"];
$tag_info_count = $tag_info["count"] + 1;
//--update the table with the new count
$sql_update_cnt = "UPDATE tags SET count='$tag_info_count'
WHERE id='$tag_info_id'";
mysql_query($sql_update_cnt);
echo "$tag now with $tag_info_count instances";
}
else
{
// tag is not there, so insert a new instance
$query = "INSERT INTO tags (tag, count) VALUES ('$tag', 1)";
if (!mysql_query($query, $dbc))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
}
mysql_close($dbc);
}
?>
Here is the errors I keep getting.
Warning: mysqli_select_db() expects exactly 2 parameters, 1 given on line 13
Warning: mysqli_error() expects exactly 1 parameter, 0 given on line 16
If you're going to go through the hassle, I would really recommend you consider PDO instead.
It's all a matter of changing mysql to mysqli.
For example, you could call mysqli_query just like you do mysql_query here.
When you call these functions, you need to pass in the database reference as the first parameter.
See the mysqli function reference here
It's been a while since I've done a mysql->mysqli conversion (like 2 or 3 years), but IIRC there are some functions for which you also have to reverse the parameter order. Isn't that lovely?
Related
This question already has an answer here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Closed 4 years ago.
I've spent the past 2 hours trying to solve this one error. I am a complete rookie so I dont know what's going on. Here's the code, please help:
<?php
header('Access-Control-Allow-Origin: *');
$host="localhost"; // Host name
$username="id11111_ab"; // Mysql username
$password="*****"; // Mysql password
$db_name="id11111_cd"; // Database name
$tbl_name="ef"; // Table name
// Connect to server and select database.
$link = mysqli_connect($host, $username, $password, $db_name);
// Retrieve data from database
$sql = "SELECT * FROM scores ORDER BY score DESC LIMIT 10";
$result = mysqli_query($link,$sql);
// Start looping rows in mysql database.
while($rows=mysqli_fetch_array($result)){
echo $rows['name'] . "|" . $rows['score'] . "|";
// close while loop
}
?>
mysqli_query() returns false if it fails. Subsequently, the mysqli_fetch_array() function is being passed this false boolean value, on which it can't operate. You'd be wise to check the value that mysqli_query() returns isn't false prior to attempting to retrieve the resource. E.g.:
$result = mysqli_query($link,$sql);
if (!$result) {
die('Query failed');
}
It seems like the mysql connection is not established properly.
Check for errors using this:
if(mysqli_connect_errno()){
echo mysqli_connect_error();
}
I keep getting this error when deleting from a database. It worked on a different server, no error message. I'm scratching my head here. $id is a number (the id column in the MySQL table) and I can't figure it out. I've seen a few answers that matched my code, but I still get it. Here's the code.
$db = new mysqli('localhost', 'user', 'pass', 'table');
// get id number
$id=$_GET['page'];
if ($db->connect_errno) {
echo "Failed to connect to MySQL: ("
. $db->connect_errno . ") " . $db->connect_error;
}
$query =
"DELETE FROM listing WHERE id='$id'";
$conn = $db->prepare($query);
// the problem line
$conn->bind_param('i', $id);
if ($conn->execute()) {
print "Successfully deleted the entry";
} else {
echo ' No ';
$db->close();
}
The point of preparing is to not insert the variable directly - that is, so that you don't have to do WHERE id='$id'. Instead, mysqli takes care of this for you. In fact, you don't even need the quotes.
What you want is to put a placeholder there, like this:
$query = "DELETE FROM listing WHERE id = ?";
Then, when you bind the parameter later, the system looks for the placeholder:
$conn->bind_param('i', $id);
The 'i' means to treat the $id as an integer.
This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 1 year ago.
I've been trying to spot the error in my database connection , I read several answers suggesting to make sure of the password grant full access ... I checked everything the problem is still appearing ...
My question is ... I understand mysqli is in this case better (from what I read) so ...
if I replace mt $dbcon with
$dbcon = mysqli_connect("$host","$username","$password","$db_name") ;
will that fix the problem and if it does, how do I get rid of the never ending
mysqli_error expects exactly 1 parameter, 0 given ... error
My php is
<?php
$host="****" ;
$username="****" ;
$password="****" ;
$db_name="****" ;
$tbl_name="courses" ;
$dbcon = mysql_connect("$host","$username","$password","$db_name") ;
if (!$dbcon) {
die('error connecting to database'); }
echo 'Courses successfully registerd , ' ;
// escape variables for security
$studentid = ( $_GET['studentid']);
$fname = $_POST["name"]; //echo $studentid;
$query=mysql_query("select * from courses where studentid='".$studentid."' ") or die(mysql_error());
$duplicate=mysql_num_rows($query);
if($duplicate==0)
{
$query1=mysql_query("insert into user values('".$studentid."')") or die(mysql_error());
}
else
{
echo'The ID you entered '.$studentid.' already registered, please wait 24 hours until you can register again';
}
// Get Cources
$name = $_GET['ckb'];
if(isset($_GET['ckb']))
{
foreach ($name as $courcess){
$cc=$cc. $courcess.',';
}
}
$sql="INSERT INTO courses (studentid, ckb, name)
VALUES ('$studentid', '$cc', $fname)";
if (!mysql_query($dbcon,$sql)) {
die('Error: ' . mysqli_error($dbcon));
}
echo " Thank you for using IME Virtual Registeration ";
mysql_close($dbcon);
?>
The problem is in Your PHP on line 7. mysql_connect() has those parameters:
mysql_connect(string $server, string $username, string $password, #optional bool $new_link = false, #optional int $client_flags = 0)
You are giving the fourth parameter $db_name =MISTAKE (fourth parameter must be boolean as you can see.) There's a function mysql_select_db() to tell PHP which database are you using. So here's a rework of your 7th line:
$dbcon = mysql_connect("$host","$username","$password");
mysql_select_db("$db_name");
but I recommend you to use mysqli or PDO ->they are inbuilt PHP libraries, so you don't have to download anything and what's more important they are easy to use.
Good Luck :)
Although we are mostly using a PDO interface now, here is the code also use to connect to the database with some simple command line scripts:
$sql_link=mysql_connect ('host','user','password') or die('Cannot connect to the database because: ' . mysql_error());
if (!$sql_link) {
echo('Could not connect to database : ' . mysql_error());
exit;
}
mysql_select_db('database_name') or die(mysql_error());
Hope that helps!
I've got a pretty standard call to a MySQL database and for some reason I can't get the code to work. Here's what I have:
$mysqli = mysqli_connect("localhost","username","password");
if (!$mysqli)
{
die('Could not connect: ' . mysqli_error($mysqli));
}
session_start();
$sql = "SELECT * FROM jobs ORDER BY id DESC";
$result = $mysqli->query($sql);
$num_rows = mysqli_num_rows($result);
Now, first, I know that it is connecting properly because I'm not getting the die method plus I added an else conditional in there previously and it checked out. Then the page displays but I get the errors:
Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in blablabla/index.php on line 11
Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in blablabla/index.php on line 12
I've double-checked my database and there is a table called jobs with a row of "id" (it's the primary row). The thing that confuses me is this is code that I literally copied and pasted from another site I built and for some reason the code doesn't work on this one (I obviously copy and pasted it and then just changed the table name and rows accordingly).
I saw the error and tried:
$num_rows = $mysqli_result->num_rows;
$row_array = $mysqli_result->fetch_array;
and that fixed the errors but resulted in no data being passed (because obviously $mysqli_result has no value). I don't know why the error is calling for that (is it a difference in version of MySQL or PHP from the other site)?
Can someone help me track down the problem? Thanks so much. Sorry if it's something super simple that I'm overlooking, I've been at it for a while.
You didn't selected the database
$mysqli = mysqli_connect("localhost","username","password","database");
The problem is you haven't selected the database.
use this code for select database.
$mysqli = mysqli_connect("localhost","username","password");
mysqli_select_db("db_name",$mysqli);
You have to select database in order to fire mysql queries otherwise it will give you error.
I believe that schtever is correct, I do not think you are selecting the database. It isn't in the code snip and if you search online you see other people with similar errors and it was because the database wasn't selected. Please let us know if you selected a database before anything else is checked. Thanks.
Try this:
session_start();
$mysqli = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
if ($mysqli->connect_errno)
{
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
$mysqli->close();
}
$query ="SELECT * FROM jobs ORDER BY id DESC";
$values = $mysqli->query($query);
if($values->num_rows != 0)
{
while($row = $values->fetch_assoc())
{
//your results echo here
}
}
else
{
//if no results say so here
}
See this manual for mysqli_connect you can select the database right in this function.
This question already has answers here:
Warning: mysqli_error() expects exactly 1 parameter, 0 given error
(4 answers)
Closed 2 years ago.
I am trying to get my head around mysql. Can someone tell my why this mysql query is not working? I am getting the following error:
Warning: mysqli_error() expects
exactly 1 parameter, 0 given in
/home/freebet2/public_html/test.php on
line 11
test.php
<?php
require_once($_SERVER['DOCUMENT_ROOT'].'/includes/db.php');
$conn = db_connect();
$result = $conn->query("ALTER TABLE users ADD COLUMN refer_old INT(10) AFTER refer_id");
if(!$result){
echo "Error with MySQL Query: ".mysqli_error();
}
?>
db.php
<?php
function db_connect() {
$result = new mysqli('localhost', 'user', 'password', 'db');
if (!$result) {
throw new Exception('Could not connect to database server');
} else {
return $result;
}
}
?>
If I change the alter string to something like : $result = $conn->query("SELECT * FROM users refer_id"); I get no error for some reason.
You are mixing the object-oriented and the procedural styles of the mysqli API :
You are using object-oriented :
$result = new mysqli('localhost', 'user', 'password', 'db');
And, then, procedural :
echo "Error with MySQL Query: ".mysqli_error();
You should use either OO, or procedural -- but not both ; and if you choose procedural, the functions expect the link identifier passed as a parameter.
For instance, mysqli_error should be called either using the object-oriented API :
$link = new mysqli(...);
echo $link->error;
Or the procedural API :
$link = mysqli_connect(...);
echo mysqli_error($link);
(Of course, it will not change the fact that you are having an error in your SQL query, but it'll allow you to get the error message, which should help finding the cause of that error)
As far as the sql error is concerned, does 'user' have permissions to alter the table?
Use mysqli_error($result) as mysqli_error expects the connection to be passed as a parameter.