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 ?
I have basic PHP/MySQL experience, having taken an introductory class. My knowledge is literally limited to the following PHP codes:
if(!($stmt = $mysqli->prepare...)
if(!($stmt->bind_param...)
if(!$stmt->execute...)
I'm currently trying to write a program that allows a user to enter a new password, and checks the password against existing passwords in the database.
Here is what I have:
<?php
foreach($Password){
$dupesql = "SELECT PasswordID Passwords WHERE (Password = '$Password')";
$duperaw = mysql_query($dupesql);
if(mysql_num_rows($duperaw){
echo nl2br("$Password has already been used \n");
}
else{
echo "Password added \n";
}
}
?>
I got the code from this post: Check for duplicates before inserting
I'm not sure if the code itself has problems or if I need to add anything else to my PHP code to get this working, as it's currently producing an "Error 500".
MySQL extension is deprecated and probably you have PHP 7.0 from where it is removed. Rewrite your code to MySQLi or PDO. Check this question on how to convert to MySQLi: How could I change this mysql to mysqli?
Also, your code just doesn't add a password (never). Probably you expect to add it before the "Password Added" message, but be aware: the solution you want to use is not ideal, because there is a risk of race condition between checking the password for existence and adding it. This means that it is possible to add a password twice.
To solve this problem, you might want to use transactions. More details are covered in this question: PHP + MySQL transactions examples
I decided to go an entirely different route, which is to set the Password column as unique.
Then I did a simple INSERT that would prompt an error if the user attempts to add a duplicate:
<?php
if(!($stmt = $mysqli->prepare("INSERT INTO Heroes(HeroName, FirstName, LastName, Age, HomeCountry, RoleID) VALUES (?,?,?,?,?,?)"))){
echo "Prepare failed: " . $stmt->errno . " " . $stmt->error;
}
if(!($stmt->bind_param("sssisi",$_POST['HeroName'],$_POST['FirstName'],$_POST['LastName'],$_POST['Age'],$_POST['HomeCountry'],$_POST['RoleID']))){
echo "Bind failed: " . $stmt->errno . " " . $stmt->error;
}
if(!$stmt->execute()){
echo "Execute failed: " . $stmt->errno . " " . $stmt->error;
} else {
echo "Added " . $stmt->affected_rows . " row to Heroes.";
}
?>
I have been reading about the Commands out of sync; you can't run this command now problem for some time now, and see that you cannot have any unread results left, which makes sense to me. However, in the following case, I don't see which results I am missing to free. I have left out the irrelevant things from my PHP and SQL code below.
# Set local variables
$sql = "
SET #STARTDATE = '2014-09-01';
SET #RANK = 0;
";
if (mysqli_multi_query($conn, $sql)) {
# Success: do nothing else
} else {
# Failure: output the error message
echo "Error: " . $sql . "<br>" . $conn->error;
}
# Fetch and store the results
$sql = "
SELECT * FROM MyTable
";
$result = mysqli_query($conn, $sql);
if (!$result) {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
The second query (the if (!$result) block) returns the infamous Commands out of sync error. If I comment out the first part, the second query runs no problem. If I change the first query into only one SET statement instead of two, the second query runs no problem. Therefore, it seems that I have to clear the 'success-flag' of every individual SQL statement from the first part. Is this correct? If so, how shall this be done?
EDIT: indeed it seems you have to flush all results in between. Adding the following line between part 1 and part 2 solves the problem.
while (mysqli_next_result($conn)) {;} // Flush multi_queries
I found this solution in a user comment on the PHP manual: http://nl3.php.net/manual/en/mysqli.multi-query.php
Quite simply, your first query
SET #STARTDATE = '2014-09-01';
SET #RANK = 0;
Will generate 2 result sets and until they have been processed, even though the result will be just a status you cannot continue.
So you need to do something like this :-
if (mysqli_multi_query($conn, $sql)) {
do {
/* unload result set */
if ($result = $mysqli->store_result()) {
// Check status
$result->free();
}
} while ($mysqli->next_result());
} else {
# Failure: output the error message
echo "Error: " . $sql . "<br>" . $conn->error;
}
Of course you should probably check for errors in that loop
We have a website that accesses a SQL Server 2005 server for one query. Currently, the site is in ASP, we are moving it to PHP, and the PHP one is currently being tested. After we run a few successful queries on the PHP site, it returns the "Error in database query. Please try again later" line in the code below. When I rewrote that line with sqlsrv_errors to elaborate, it told me that the table didn't exist. There are about 40 tables in the database, but after the error happens it only shows 8 of them in Management Studio. However, if I allow it to sit for about 5 minutes, all of the tables are restored. No matter how many times the old ASP site is used, the table does not do this. However, when the tables disappear from using the new site, the old site shows inaccessible for a few minutes until the tables re-appear in SQL Server management studio. I didn't see any kind of connection limits on the SQL Server, so I don't know whether it's something I'm doing in the PHP SQL queries or within the SQL Server properties.
<?php
include ("dbvals.inc.php");
if (!empty($_POST['lastnamebox'])) {
$dbhandle = sqlsrv_connect($dbServer, $connectioninfo);
if($dbhandle == false){
echo "Error connecting to database. Please try again later. ";
}
else{
$query = "SELECT * FROM Person WHERE LastName LIKE '%' + ? +
'%' AND InactiveFlag = 'N' ORDER BY LastName, FirstName";
$params = array();
array_push ($params, $_POST['lastnamebox']);
$results = sqlsrv_query($dbhandle, $query, $params);
if($results == false){
echo "Error in database query. Please try again later.";
//This is printed when database tables temporarily disappear
}
else
{
$row = sqlsrv_fetch_array( $results, SQLSRV_FETCH_ASSOC);
if($row){
do{
echo "<tr><td class='tablecell'>";
echo $row['LastName'] . "," . $row['FirstName'] . "<br>";
echo "Address: " . $row['Address'] . "<br>";
echo "City, State, Zip: " . $row['CSZ'] . "<br>";
echo "</tr></td'>";
}while($row = sqlsrv_fetch_array( $results, SQLSRV_FETCH_ASSOC));
}
else{
echo "No results found. Please try another query.";
}
}
}
sqlsrv_free_stmt($results);
sqlsrv_close($dbhandle);
}
else {
echo "Please type a value in the search box.";
}
?>
The $query is wrong to begin with. Change it to:
$query = "SELECT * FROM Person WHERE LastName LIKE '%' + ? +
'%' AND InactiveFlag = 'N' ORDER BY LastName, FirstName";
Not sure about the tables disappearing though. What driver are you using?
Just another issue I'm seeing with the code not sure if it's related to your problem. or another copy error but here it is.
if ($r1 = sqlsrv_fetch_array($results)) {
while( $row = sqlsrv_fetch_array( $results, SQLSRV_FETCH_ASSOC)){
The first fetch should also have '($results,, SQLSRV_FETCH_ASSOC)'
Additional that check is going to eat the first returned record which may or may NOT be what you intended.
Also it is possibly that PHP seeing some results in the while as false even though they aren't and the server is still waiting on you to finish getting the rest. Seen code like that cause 'Server has got away' errors in MySQL which could be what is going on here as well.
Not sure of the syntax but a sqlsrv_clode_cursor() just before the connection close might also fix your issue if there's some kind of connection polling going on. Could be simply running out of connection or getting old one in a incorrect state.
SELECT * FROM Person WHERE AND LastName LIKE
Looks like there something missing between the WHERE and AND to me.
I don't know SQL Server really so it could allow that but it's not standard SQL. Depending on how it's reacting to that error I could see it 'Going away' so to say and reporting tables missing.