mysql_errno and mysql_error always reporting something - php

I have a query written as
mysql_query($query,$conn)
or
die(
"A MySQL error has occurred.<br />Your Query: " . $query . "<br /> Error: (" . mysql_errno() . ") " . mysql_error());
echo "You have been entered into our Database!";
This outputs
A MySQL error has occurred.
Your Query: INSERT INTO users (uid, twname, privacy) VALUES (15400743, 'gdhdh', 'accepted')
Error: (0)
so it doesn't list any errors or anything. When I copy/paste that query into the SQL tab of PHPMyAdmin, it runs successfully, and the DB connection isn't throwing anything bad (I know it works because a query works well elsewhere):
function get_db_conn() {
$conn = mysql_connect($GLOBALS['db_ip'], $GLOBALS['db_user'], $GLOBALS['db_pass']);
mysql_select_db($GLOBALS['db_name'], $conn);
return $conn;
}
Any thoughts on what I could fix? I'd really appreciate it.

Error 0 means that no error occurred.
Therefore if the code to output an error is being run when no error occurred you have a logic error in your code surrounding the call to the mysql_query() function.
It's hard to tell from your code what should and shouldn't run under different conditions and where the error may lie.
The following code is logically equivalent to what you are trying to achieve and should work as expected.
This code more clearly separates calling the mysql_query() function from checking the result of calling the function. I have also formatted the code a little to that it displays without any horizontal scrolling, although that's purely optional.
$queryResult = mysql_query($query, $conn);
if ($queryResult === false) {
$errorMessage = "A MySQL error has occurred.<br />"
. "Your Query: ".$query."<br />"
. " Error: (".mysql_errno().") ".mysql_error();
die($errorMessage);
}

I'm not sure if this is exactly what you're looking for, but the argument to the function is called $query, and the variable in your error is $your_query, so the value of $your_query displays in the error, but who knows what is in $query, so if it's NULL, that might cause the error number 0 with no message.

Related

1064: SQL syntax (MySQL INSERT)

To Start.. I am using mysqli_real_escape_string() on every text field, and leaving INT as they are:
The following query successfully inserts the record into the table without fail, every field is correctly stored... There has to be something I'm being glib about, I have blurry coding eyes at this point... But after the INSERT statement is run, mysqli_error($con) tosses the following error:
1064: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '1' at line 1
(I'm nearly 100% certain I do not even use the number 1 at all, whether it be in the php code or a value)
$query = mysqli_query($con,"INSERT INTO hj_media
(mediaID,MedDropID,MediaName,GLCode,Store,MediaType,MiscDetail,ArtDueDate,RunDate,EndDate,AdvMonth,Size,Dimensions,TotalCost,HJShare,CoOpShare,Vendor,HamiltonFiscal,VendorFiscal,AdDescription,Category,AddedtoVCM,ArtworkRequested,InvoiceProcessed,BilledVendor,NetCost,ProductionCost,CostPiece,QuantityOrdered,HJCostPrinting,Postage,DDFee,EventDescription,EventDate,DateToPrint,DateInMail,DateInHome,TotalPrintQuantity,TotalMailFile,TotalActualMail,ReturnedPieces,SalesResultsUnits,SaleResultsDollars,SpendNonPrint,SpendPrint,SpendAdvertising,SpendPR,MediaNameOther,ClientPersona,Campaign)
VALUES(NULL,$add_medid,'$add_vehicle',$add_glcode,'$add_loclist','$add_type','$add_miscdetails','$add_artdate','$add_rundate','$add_enddate','$add_month','$add_size','$add_dimensions','$add_totalcost','$add_hjshare','$add_coopshare','$add_vendor',$add_hamiltonfiscal,$add_vendorfiscal,'$add_addescription','$add_category','$add_addedtovcm','$add_artworkrequested','$add_invoiceprocessed','$add_billedvendor','$add_netcost','$add_productioncost','$add_costperpiece',$add_quantityordered,'$add_hjprintcost','$add_postage','$add_ddfee','$add_eventdescription','$add_eventdate','$add_datetoprint','$add_dateinmail','$add_dateinhome',$add_printquantity,$add_totalmailfile,$add_totalactualmail,$add_returnedpieces,$add_salesunits,'$add_salesdollars','$add_spendnonprint','$add_spendprint','$add_spendadvertising','$add_spendpr','$add_medianameother','$add_persona','$add_campaign')");
if (mysqli_query($con, $query)) {
echo "New record created successfully";
}
else {
echo mysqli_errno($con) . ": " . mysqli_error($con) . "\n";
}
UPDATED QUERY, TRY THIS
$query="INSERT INTO hj_media
(mediaID,MedDropID,MediaName,GLCode,Store,MediaType,MiscDetail,ArtDueDate,RunDate,EndDate,AdvMonth,Size,Dimensions,TotalCost,HJShare,CoOpShare,Vendor,HamiltonFiscal,VendorFiscal,AdDescription,Category,AddedtoVCM,ArtworkRequested,InvoiceProcessed,BilledVendor,NetCost,ProductionCost,CostPiece,QuantityOrdered,HJCostPrinting,Postage,DDFee,EventDescription,EventDate,DateToPrint,DateInMail,DateInHome,TotalPrintQuantity,TotalMailFile,TotalActualMail,ReturnedPieces,SalesResultsUnits,SaleResultsDollars,SpendNonPrint,SpendPrint,SpendAdvertising,SpendPR,MediaNameOther,ClientPersona,Campaign) ";
$query.=" VALUES(NULL,$add_medid,'$add_vehicle',$add_glcode,'$add_loclist','$add_type','$add_miscdetails','$add_artdate','$add_rundate','$add_enddate','$add_month','$add_size','$add_dimensions','$add_totalcost','$add_hjshare','$add_coopshare','$add_vendor',$add_hamiltonfiscal,$add_vendorfiscal,'$add_addescription','$add_category','$add_addedtovcm','$add_artworkrequested','$add_invoiceprocessed','$add_billedvendor','$add_netcost','$add_productioncost','$add_costperpiece',$add_quantityordered,'$add_hjprintcost','$add_postage','$add_ddfee','$add_eventdescription','$add_eventdate','$add_datetoprint','$add_dateinmail','$add_dateinhome',$add_printquantity,$add_totalmailfile,$add_totalactualmail,$add_returnedpieces,$add_salesunits,'$add_salesdollars','$add_spendnonprint','$add_spendprint','$add_spendadvertising','$add_spendpr','$add_medianameother','$add_persona','$add_campaign');";
$result =mysqli_query($con,$query);
If($result){
echo "Success"';
}
else{
echo " query failed ". mysqli_errno();
}
The problem is yoir sending a boolean gotten from the first query test into another mysqli query function. It's a good thing to have set a variable that refernces your query string, so that you use but this value in the mysqli query function . Try this
$query="put your myqli query here;";
$result =mysqli_query($con,$query);
If($result){
echo "Success"';
}
else{
echo " query failed ". mysqli_errno();
}
can you knidly thick the question answered if this solves your problem ?

MYSQL INSERT syntax error with incorrect line number

I'm currently working on creating a login system, one part of which is of course registration. It's been going smoothly up until this point, where I'm getting an error.
I've researched this as thoroughly as I can, but I can't find the solution as it is giving me an incorrect line number.
The error I'm getting is:
Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '1' at line 1
My SQL query is
$token = (round(microtime(true) * 1000));
$query = mysql_query("INSERT INTO "
. "`users` "
. "(name, password, email, token) "
. "VALUES "
. "('$_POST[user]'"
. ",'".hash('sha512',$_POST['pass'])."'"
. ",'$_POST[email]'"
. ",'$token')") or die(mysql_error());
if (mysql_query($query) === TRUE) {
//echo "Sucsessfuly registered! Check your email for a confirmation link.";
} else {
echo "Error: " . mysql_error();
}
(this is not the first line of the file, it's the 22d)
When the code runs, even though it throws the error it still is inserting the values into the table correctly.
Also when I run the same query in phpmyadmin, it runs just fine with no errors.
I've been trying to solve this error for the last 3 hours so any help would be appreciated ;)
You're calling mysql_query twice: first with the SQL, and then you're using the result of the query as if it were a query. The error you're getting is because $query is true, which gets turned into 1 when treated as a string.
Either you should just set $query to the SQL string:
$query = "INSERT INTO ...";
if (mysql_query($query)) {
...
} else {
...
}
or you should just check the value of $query:
$query = mysql_query(...);
if ($query) {
...
} else {
...
}

PHP MySql query error when executing SP

I have a PHP script which fires a MySQL SP. The SP cmd works when run directly against db (I'm using PhpMyAdmin UI). When tested, the PHP returns error 'Warning: mysql_num_rows() expects parameter 1 to be resource' due to the fact there is nothing returned from the SP...when i debug the script i see the variable $result1 has all its params set to null.
There is another SP executed successfully using the same code above this one in the script so im a bit puzzled. Any ideas what the issue is?
$result1 = $mysqli->query("CALL sp_playerInvite_pin_select('samsmith#hotmail.com')");
if(!$result1) die("CALL failed: (" . $mysqli->errno . ") " . $mysqli->error);
//echo json_encode($getPlayerInvitePin);
// check for empty result, if not then there is >1 pin corresponding to email
if (mysql_num_rows($result1) > 0)
{
//looping through all results-in theory should only 1 result
while ($row = mysql_fetch_array($result1))
{
$response["pin"] = $row["player_pin"];
}
// echoing JSON response
echo json_encode($response);
}
The SP...
Shouldn't it be mysqli_num_rows? thanks 'I Can Has Cheezburger' :

SQL syntax error

Im fairly new to both PHP and SQL but what i want is for the details entered into my form to be inserted into a database.
The code i have written works and the data is submitted into the database but there are a couple things not right.
Firstly here is the code;
<?php
include "credentials.php";
function insert_post($cnhost,$cnusername,$cnpassword,$cndatabase,$titlein,$contentin,$comment_optionin) {
$connect = mysqli_connect($cnhost,$cnusername,$cnpassword,$cndatabase);
if (mysqli_connect_errno($connect))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}else{
echo "Connection Success! <br>";
$submitpost_query = mysqli_query($connect,"INSERT INTO blog_posts (title,content,comment_option) VALUES ('".$titlein."','".$contentin."','".$comment_optionin."')");
if (!mysqli_query($connect,$submitpost_query))
{
die('Error: ' . mysqli_error($connect));
}else{
echo "Post submitted.";
}
mysqli_close($connect);
}
}
$title = $_POST["title"];
$content = $_POST["content"];
$comment_option = $_POST["comment_option"];
insert_post($host,$username,$password,$database,$title,$content,$comment_option);
?>
Although the data is submitted into the database as i want i get the following error;
"Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '1' at line 1"
The $comment_option variable contains the value 1 or 0, depending on which radio button is selected so this error might be referring to this variable but this SQL error is the same whether the value of $comment_option is 1 or 0.
I do see "Connection success!" before this error but do not see "Post submitted" even though the post is actually submitted. Any ideas why?
As well as helping me with this problem i would be very grateful if somebody could give me some general tips to improve what iv wrote. I am a noob so im sure there's a few things that could be improved here!
Thanks very much!
The problem is here:
if (!mysqli_query($connect,$submitpost_query))
You're passing a mysqli_query result which is $submitpost_query to another mysqli_query which is in the if statement.
The problem is with following chunk of code
if (!mysqli_query($connect,$submitpost_query))
it should be instead following
if (!$submitpost_query)
Reason : You are executing return object again through mysql_queri function that is causing warning, invalid resource, as this function only excepts valid sql query or connection object
I know your question is answered but I seriously recommend you to sanitize the POST data before concatenating it in a query.

How to check if a MySQL query using the legacy API was successful?

How do I check if a MySQL query is successful other than using die()
I'm trying to achieve...
mysql_query($query);
if(success){
//move file
}
else if(fail){
//display error
}
This is the first example in the manual page for mysql_query:
$result = mysql_query('SELECT * WHERE 1=1');
if (!$result) {
die('Invalid query: ' . mysql_error());
}
If you wish to use something other than die, then I'd suggest trigger_error.
You can use mysql_errno() for this too.
$result = mysql_query($query);
if(mysql_errno()){
echo "MySQL error ".mysql_errno().": "
.mysql_error()."\n<br>When executing <br>\n$query\n<br>";
}
If your query failed, you'll receive a FALSE return value. Otherwise you'll receive a resource/TRUE.
$result = mysql_query($query);
if(!$result){
/* check for error, die, etc */
}
Basically as long as it's not false, you're fine. Afterwards, you can continue your code.
if(!$result)
This part of the code actually runs your query.
mysql_query function is used for executing mysql query in php. mysql_query returns false if query execution fails.Alternatively you can try using mysql_error() function
For e.g
$result=mysql_query($sql)
or
die(mysql_error());
In above code snippet if query execution fails then it will terminate the execution and display mysql error while execution of sql query.
put only :
or die(mysqli_error());
after your query
and it will retern the error as echo
example
// "Your Query" means you can put "Select/Update/Delete/Set" queries here
$qfetch = mysqli_fetch_assoc(mysqli_query("your query")) or die(mysqli_error());
if (mysqli_errno()) {
echo 'error' . mysqli_error();
die();
}
if using MySQLi bind_param try to put this line above the query
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

Categories