Basic php/mysql query struggles - php

I am frustrated and I am beginning to wonder if there is some catch with my hosting company that might be causing this issue. I have done this type of thing before (not with this hosting company) so I am at a loss.
<?php
$q = "SELECT * FROM sunsetUsers";
$r = #mysqli_query($dbh, $q);
if ($r) {
echo 'good job';
} else {
echo 'you suck';
}?>
The connection info is being called in the header and it works. It will connect to the database and supply me with a good message when I tell it to. Yet, when I try to execute a simple query, I get nothing. No errors at all other than it tells me, "you suck." Heh...which is what it should do when the query fails. I am not trying to do anything with the data...I just want to ensure that the query executes with no problems.
Is there any other information I can give that might help here? This seems really simple to me...yet so confused here as to why this isn't working.

You can see your mysql errors with mysql_error (for the purposes of learning):
if (!$r) {
echo mysqli_error(); // display the last error detected
}
Also using the mysql_* & mysqli_* functions are a very old & insecure way of communicating with mysql. Look into pdo for a better way.

Related

mysql dies everytime I try to create a new table

I am attempting to create new tables every time I post to this method, but for some reason I can not figure out why it dies.
<?php
$host = "127.0.0.1";
$username = 'cotten3128';
$pwd = 'pwd';
$database = "student_cotten3128";
$pin = $_REQUEST['pinSent'];
$words = $_REQUEST['resultSent'];
$tableName = $pin;
$db = new mysqli($host, $username, $pwd, $database);
if ($sql = $db->prepare("CREATE TABLE $pin (id INT(11) AUTO_INCREMENT);")) {
$sql->execute();
$sql->close();
}else{
echo $mysql->error;
die('Could not create table');
}
for($i=0;$i<count($words);$i++){
if($sql = $db->prepare("INSERT INTO ".$pin.$words[$i].";")) {
$sql->execute();
$sql->close();
}else{
echo $mysql->error;
die("Could not add data to table");
}
}
mysqli_close();
?>
Any help or insight would be greatly appreciated.
The intention of my post is to help you finding the issue by yourself. As you did not added much information I assume my post is helpful for you.
Based on the code you have shared I guess you mean one of your called die() functions is executed.
Wrong function call
As Jay Blancherd mentioned mysql_close is the wrong function. You rather have to use mysqli_close as you created a mysqli instance.
Beside of that mysql_* is deprecated and should not be used anymore.
Debugging Steps
Not only for this case but in general you should ask yourself:
Is there an error message available? (Frontend output, error log file, ...)
YES:
What's the message about?
Is it an error you can search for? E.g. via a search engine or the corresponding documentation?
Look up in the bug tracker (if available), by the software developer of the software you are using, and if it has not been reported yet report the issue.
NO: (if none error message available OR you cannot search for it as it is a custom error message)
Search in the files of the software you are using for the error message and start a core-debugging.
STILL NO SOLUTION?:
Ask on stackoverflow.com e.g. and tell your issue and the steps you have performed to find and fix the bug. Post only as much code as necessary plus use a proper format.
Debugging in your case:
In order to narrow down the scope. Which of the die() is executed? Depending on that echo the query to execute just before it actually is executed. Then copy the SQL query to an SQL editor and look at it syntax. After that you probably know the problem already.

MySQLi Commands out of sync, with simple query() function

I can't figure out why I'm getting the Commands out of sync; you can't run this command now error. I can't seem to find a way to fix this.
As you can probably see from the code, I need to execute TWO SQL statements. One to check if the password is correct, and the other, which runs only if the previous one returns true, to store all user data in session variables.
Here is my code:
$check_pw_query = $conn->query("CALL checkPassword('{$username}', '{$password}')");
$check_pw_fetched = $check_pw_query->fetch_assoc();
$check_pw_query->close();
if($check_pw_fetched['password_correct']) {
unset($check_pw_fetched);
if(!$get_user_data = $conn->query("CALL getUserData('{$username}')")/*->fetch_assoc()*/) {
echo $conn->error;
}
$_SESSION["user_username"] = $username;
$_SESSION["user_id"] = $get_user_data["id"];
$_SESSION["user_name"] = $get_user_data["name"];
$_SESSION["user_email"] = $get_user_data["email"];
$_SESSION["user_type"] = $get_user_data["type"];
$conn->close();
unset($conn);
send_home(false);
}
Help is much appreciated.
Thank you
Ok, as there were no real helpfully answers, I'll answer it myself, to hopefully help someone else with the same problem.
The problem is that, whenever you call a stored procedure, it will output one more result that defined anywhere. So if your procedure returns 1 value, php will get 2. The last one is only there to tell you that there are no more values. BUT you have to deal with that one as well to free the connection ($conn in my example).
So, that you do is, simply, add this to your code, right after the $check_pw_query->close(); :
$conn->next_result();
And there you have it. It will now work perfectly fine.

PHP and MySQL INSERT INTO does not work -- No error and no new lines in DB

This my first post on this site. I will do my best to include all the needed information. I have read many of the answers regarding this same problem. I have tried many combinations and none of them work. The following is the one that gets me the closest to my very simple goal --> Write a line to my database. This code is in a password protected portion of my site.
<?php
//Connect to database
include("../ConfigFiles/ConnectDB_live.php");
echo "<br> I am still alive? <br>";
//Can I read from DB --- This worked on live
$strSQL = "SELECT * FROM invoicelist_table";
$rs = mysql_query($strSQL);
while($row = mysql_fetch_array($rs))
{
echo $row['FileName'] . "<br>";
}
//Can I write to the DB --- Live
//Lets mix a few ideas together
mysql_query($bdd,"INSERT INTO `invoicelist_table` (`InvoiceNo`, `FileName`, `FilePath`) VALUES ('9999', 'MyName', 'MyPath')") ;
echo mysql_error();
//or die(mysql_error());
echo "I wrote something to the DB successfully <br>";
// Close the database connection
mysql_close();
echo "The connection to DB is closed";
?>
Note that I can read the database just fine but I can't seem to write to it. I have also tried the recommended mysqli version but that does not work either. I have tried various ways of trapping an error and I get nothing... literally nothing! I have tried at least a dozen syntax variations. I am ready to throw up!
I am new to web programming and find most of my answers online. I think I am doing pretty good for my limited knowledge. This one is blowing my mind. None of the recommendations I read about work or make sense to me. So please answer me like I am a 5-yr old!
Thanks in advance.
Move your connection as the second parameter or remove it if you didnt close the connection
mysql_query("INSERT INTO `invoicelist_table` (`InvoiceNo`, `FileName`, `FilePath`) VALUES ('9999', 'MyName', 'MyPath')") ;
Docs

Handling MySQL errors in PHP [duplicate]

This question already has answers here:
mysql_fetch_array()/mysql_fetch_assoc()/mysql_fetch_row()/mysql_num_rows etc... expects parameter 1 to be resource
(31 answers)
Closed 2 years ago.
While developing my website I use mysql_error() to display errors so I know how to fix them.
My question is... when the website goes live, how should I handle the errors, because I do not want the user to see the errors but instead see a user friendly message like "Oops, something went wrong".
Firstly, I'd strongly recommend moving from the deprecated mysql_ functions to either one of the MySQLi or PDO classes. Both are far more secure, and being maintained for current and foreseeable future versions of PHP.
Some possible solutions to displaying an error could be:
$sql = new mysqli($host, $user, $password, $database);
$query = //your query
//Option 1
$result = $sql->query($query) or die("Something has gone wrong! ".$sql->errorno);
//If the query fails, kill the script and print out a user friendly error as well
//as an error number for them to quote to admins if the error continues to occur,
//helpful for debugging for you, and easier for users to understand
//Option 2
$result = $sql->query($query);
if($result) {
//if the query ran ok, do stuff
} else {
echo "Something has gone wrong! ".$sql->errorno;
//if it didn't, echo the error message
}
You could also use the PHP error_log function to put a new error into the error log which could contain the full $sql->error details for admins to view, and completely skip the $sql->errorno printout. For more info on error logging, check the PHP Docs
Normally you want to log these errors in a live enviroment (meaning, you write the error message and some further infromation like time, ip, .. to a file)
On the userside you should also provide the User some feedback, so print a nice error message so that the user knows that something went wrong.
Just use Google to find some Logger-libraries. Mostly, they can be configured to change behaviour in live and development enviroment!
You might also have a look at: https://www.php-fig.org/psr/psr-3/
While developing your website, you should not use mysql_error(), because you should not use any of the mysql_* functions, because they are deprecated.
The most basic error handling is to throw an Exception. The exception handler should log the error message along with a stack trace and output an error page.
What you need is to handle the answer you receive from the SQL query. Like if success or if error.
Like this:
<?php
$response = 0;
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno()){
$response = "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Perform a query, check for error
if (!mysqli_query($con,"INSERT INTO Persons (FirstName) VALUES ('Glenn')")){
$response = "Error description: " . mysqli_error($con);
}
mysqli_close($con);
echo $response;
?>
Then in your Frontend side, you can give a format to your response, with a jQuery plugin, or some framework. I recommend to use: jquery confirm.
References:
https://www.w3schools.com/php/func_mysqli_error.asp
https://craftpip.github.io/jquery-confirm/
If you want to handle the specific error, try it by detecting the exactly error number code.
https://dev.mysql.com/doc/refman/5.5/en/server-error-reference.html
https://www.php.net/manual/es/mysqli.errno.php
You can use:
if (mysqli_error($conn)) {
$error = 'Oops something went wrong!';
}
echo $error;
The $conn stands for the database connection through which the query was carried out.

mysqli never returns anything

As part of a PHP web application, I'm querying a MySQL database using mysqli and prepared statements.
I've used exactly the same code on a few queries and it works, but on one particular query, it always returns an empty record set. I've run exactly the same query from the MySQL command line, and it correctly returns the result. I've checked the parameters being passed in, and they're fine.
I've spent the best part of a day trying to figure out why I'm always getting an empty record set with no errors or warnings. I've got PHP's errors set to display on the page, and I've got them set to E_ALL|E_STRICT. I still don't get any warnings or errors.
I've tried all the obvious things, like making sure I can actually connect to the database, checking the parameters that are being passed in, and making sure the row I'm trying to return actually exists in the database. I've had var_dump()s and die()s all over the page to check what's coming back, and it's always a legitimate, but empty, recordset.
function salt() {
return("I've removed my salt from this sample code");
}
function openDatabase() {
$conn = new mysqli("127.0.0.1", "username", "password", "database")
or die("Error: Could not connect to database.");
return($conn);
}
function checkUserCredentials($username, $password) {
$goodPassword = md5(salt().$username.$password);
$conn = openDatabase();
$query = $conn->stmt_init();
$query->prepare("SELECT id FROM users WHERE email = ? AND passwordHash = ?")
or die('Problem with query');
$query->bind_param("ss", $username, $goodPassword)
or die('Error binding parameters');
$query->execute() or die("Could not execute");
$query->bind_result($col1) or die ("Could not bind result");
if ($col1 !== 0) {
die("Authentication Complete");
} else {
die("Authentication Failure! Number of Rows: ".$query->num_rows." Username: " . $username . " Password Hash: " . $goodPassword);
}
}
Any feedback is appreciated. I'm sure I'm missing something simple, but if I didn't shave my head I'd be tearing my hair out right now.
Thanks
I'm not familiar with the mysqli library (I usually use PDO which provides a very similar cross platform API) so I can't immediately see any problem. However, you might try watching the mysqld log. See here for info:
http://dev.mysql.com/doc/refman/5.1/en/query-log.html
By tailing the log, you should be able to see the exact query that was submitted.
One final note, I notice you're using a fixed salt value. Wouldn't it be better to generate this value randomly each time you need it and then store it in the users table? Generally, a salt is not intended to be secret, it's just there to prevent people precomputing tables of passwords using the hash algorithm that you use.
In case anyone else runs into similar issues, it really helps if you run fetch() on your mysqli_stmt object.
In my code above, the solution looks like this:
$query->bind_result($col1) or die ("Could not bind result");
$query->fetch(); // <--- How could I forget to do this?
if ($col1 !== 0) {
return true;
} else {
return false;
}
Added on behalf of OP

Categories