Mysqli_error() does not work - php

The following code:
$dbc = mysqli_connect("localhost","root","root","magnificantDatabase")
or die("Could not connect to database");
$sql = "INSERT INTO accounts(username, password, ip)
VALUES('$username','$password','$ip')";
mysqli_query($dbc, $sql)
or die(mysqli_error($dbc));
Should return an error when the mysqli_query fails return an error, shouldn't it?
It doesn't though :/
Anyone have any ideas why it doesn't?
Oh and, by returning no error I mean it returns nothing at all.
just completely blank.
Edit: I'd like to let you know that after having searched the web (even though as this would seem a common problem) I have -NOT- found anything that fixes this, there are issues close to this one, but none of them I have found appear to be the exact same.

Same thing happened to me when I executed an UPDATE statement.
mysqli_error, mysqli_errno and mysqli_error_list were all empty.
Then I discovered that the problem was that the database user assigned to the connection object did not have the UPDATE privilege. I don't know why I did not receive an error message or an error number for this security/privilege breach.

Try to this..
$dbnm = "magnificantDatabase";
$abc= mysqli_connect("localhost","root","root") or die ("could not connect to mysql");
mysqli_select_db($abc,$dbnm) or die ("no database");
$sql = "INSERT INTO accounts(username, password, ip) VALUES('$username','$password','$ip')";
mysqli_query($dbc, $sql) or die(mysqli_error($dbc));

Related

PHP wont connect to mysql database

I cant seem ton get a connection between this php script and my MySQL database. As far as I am aware this code is correct and should execute the query. The problem is with the connection on line 1. I'm just wondering does anyone know of any reason why this is not working, or am I making a really foolish mistake.
<?php
$con = mysqli_connect("localhost","username","password","database_name");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query = "INSERT INTO lat_long (uname, lat, lon) VALUES ('boo', 'boo', 'boo')";
mysqli_query($con, $query);
mysqli_close($con);
?>
EDITED: Here is the error
Fatal error: Call to undefined function mysqli_connect() in /var/www/project
/insertar.php on line 7
If you are getting a connection error, chances are your problem will be found on this line:
$con = mysqli_connect("localhost","username","password","database_name");
Are you sure you have got the correct host address, username, password and name of your database schema?
You may also want to check that you have the mysqli php extension installed on wherever this database is being hosted.

php mysql Insert into not working

So what I am trying to do is a very basic and straight way of inserting a record into mysql db.
It is just something I have done few times before, however for some reason it is not working with me this time.
So in the following couple of lines of code I will show my code, which basically do the following
1- Check if the user exists in the DB (An existing user is a user with the same email)
2- If the user exists in the DB then it sends an http response with a status code of 409 which means duplication.
(Anyway note that this works perfectly, which implies the connection was made successfully to the DB, and it was able to retrieve any exact user, if any)
3- If the user does not exist it should be inserted in the DB (Here is the problem)
My Code
//Checking if the user exist
$result = mysql_query("SELECT * FROM $table_name WHERE email='".$post_email."'",$con) or die ('Error: '.mysql_error ());
$num_rows = mysql_num_rows($result);
if($num_rows > 0){
// Close Connection
mysql_close($con);
echo "409";
}
else{
mysql_query("INSERT INTO samam_users (username,password,email) VALUES ('ALI','AHMED','amsh-1992#hotmail.com')",$con);
// Select the record
$user_id = mysql_insert_id();
$result = mysql_query("SELECT * FROM $table_name WHERE email='".$post_email."'",$con) or die ('Error: '.mysql_error ());
// Close Connection
mysql_close($con);
echo "200 " . $result['username'];
}
I googled the possible solutions for this issue, however all similar issues I went through were because of syntax errors.
Any suggestions? Thanks in advance :)
What is the exact error message you are getting? Copy/paste that here, please.
Also, the only odd thing I see is that you are doing the SELECT commands with a variable $table_name, and in the INSERT command you are hard-coding a table name..? Maybe that's it?
INSERT INTO samam_users ...
just put the same table name variable there?
INSERT INTO $table_name ...
Let me know if this helps. :)
$sql = "INSERT INTO samam_users (username,password,email) VALUES ('ALI','AHMED','amsh-1992#hotmail.com')";
if(!mysql_query($sql,$con)) {
die(mysql_error());
}else {
echo 'inserted succesfully';
}
mysql_error() will give you information about why your query isn't working - allowing you to debug it.
Also don't use mysql_*, it's going to be deprecated and there are much better more secure options like MySQLi or preferably PDO
I think you have to put all the values in INSERT command in double quotes instead of single quote

Why is mysql_error() used?

I am a beginner in php and I am making a form and pass the values to database using php. Also I am trying to check a field if it is empty or not when I press the submit button. I have read about mysql_error(), but I dont understand exactly what it does. So can anyone explain me which is the difference between the lines below:
if(empty($_POST['fname']))
die ('Name is empty </body></html>');
and
if(empty($_POST['fname']))
die ('Name is empty'. mysql_error().'</body></html>');
When I press the submit button in both cases I have the same result...Only the message: Name is empty. So which is the use if mysql_error() ?
Thanks in advance!
You're not executing a MySQL database call on that code. So it won't return anything. This code:
if(empty($_POST['fname']))
die ('Name is empty'. mysql_error().'</body></html>');
Uses die if Name is empty. However, Name has nothing to do with MySQL, even though it is being passed to MySQL, it is not directly involving it. $_POST variables are variables, not directly related to MySQL. If this were say a MySQL query, like:
$mysql = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if(!mysql)
die ('Could not connect: '. mysql_error().'</body></html>');
Then it would tell you that it couldn't connect and the specific error message.
mysql_error() provides you with the error message if a mysql error has occured. If none has occured, it won't return anything.
More info at the PHP manual.
On a sidenote, the mysql extension has been deprecated. You really should switch to using either MySQLi or PDO.

Mysql_error() Not Catching INSERT Error in PHP

new here and really green to programming, so go easy..
I discovered I have an INSERT that is failing because of a duplicate record error. I figured it out by running the query in a MySQL console with literals, where err#1062 popped up.
What I want to understand is why mysql_error() or mysql_errno() didn't catch this error in my PHP script.
Below is a generic setup of what I've done. I have a form that submits to a php file that calls data_insert()
function data_insert($var1, $var2, $var3, $var4){
$db = db_connect();
$query = "INSERT INTO exampletable (id, id_2, id_3, id_4)
VALUES ('$var1', '$var2', '$var3', '$var4')";
$result = $db->query($query);
if (!$result)
{
echo ('Database Error:' . mysql_error());
}
else
{
echo "Data added to db";
}
}
The DB connection:
function db_connect()
{
$result = new MySQLi('localhost', 'root', 'root', 'dbname');
if (!$result)
throw new Exception('Could not connect to database server');
else
return $result;
}
Result I'm getting is:
Database Error:
PHP echos "Database Error:" because the INSERT fails, but no subsequent MySQL error info is echoed. Honestly, I'm not exactly sure what I'm supposed to see, but through reading some other SO questions, I've double-checked my php.ini file for error handling and E_ALL and display_errors is set appropriately (although not sure if it matters in this case).
Is there something in my logic that I'm not understanding, like the scope of the link resource mysql_error() takes?
Thanks for your help, I'm hoping this is something embarrassingly obvious.
I know the above is missing XSS and security precautions and uniform exception handling. Baby steps though. It's simplified here for discussion's sake.
You're using mysqli (note the i) for your DB operations, but are calling mysql_error (no i). They're two completely different interfaces, and do not share internal states at at all. DB handles/results from one are not usable in the other.
Try mysqli_error() instead (note the I).
As far as I can tell, you appear to be using the MySQLi class for connecting and queries, but you're trying to access MySQL error message. MySQLi and MySQL aren't the same, so errors in one will not show in the other. You should look up error handling for MySQLi, not MySQL.
You are confusing two seperate methods for connecting to a mySQL DB.
mysql_error() will only work on queries that are run through mysql_query().
As you are using mysqli, you must use mysqli_error()

mysql_select_db fail on somepage

I am making a social website for my company. The problem appears only in "diary" page. Most of time, my code connects to database successful, but sometime, it throws error:
Could not select database
This is my php code to connect to database on localhost:
function execute_action($query)
{
$link = mysql_connect("localhost", "root", "123456") or
die("Could not connect");
mysql_select_db("2t") or die("Could not select database");
$query = $query;
$result = mysql_query($query) or die("Query failed");
return $result ;
}
Do you have any solution to help me. Thanks for reading.
As you arent closing your database connections between querys, so, my first thought would be is you're reaching a max connection barrier to the mySQL server.
While this may not be the answer - showing the mysql_error would help.
As someone else pointed out, theres no need to connect and drop each time. Unless your page has incredibly long processing time, connecting at the start, closing at the end should be enough.
You need to pass the dbconfiguration $link while selecting the db and executing the query
mysql_select_db("2t", $link)
even in mysql_query( $query, $link)

Categories