I am following the last part of the following video tutorial "How to create a database website with PHP and mySQL 07 - Add in input form" :
https://www.youtube.com/watch?v=MGIG00d1Xzc&list=PLhPyEFL5u-i0zEaDF0IPLYvm8zOKnz70r&index=7
At the end here is my code, for the inserting portion to the database for the new_jokes.php script (everything up to this point of the series I have gotten to work fine so far)
Basically I am getting the seemingly classic "INSERT INTO" not working although all my syntax looks correct. Am I missing something obvious here? I get no errors, just the row isn't added.
<?php
include "db_connect.php";
$new_joke_question = $_GET["newjoke"];
$new_joke_answer = $_GET["newanswer"];
// Search the database for the word chicken
echo "<h2>Trying to add a new joke and answer: $new_joke_question
$new_joke_answer </h2>";
$sql = "INSERT INTO Jokes_table (JokeID, Joke_question, Joke_answer) VALUES
(NULL, '$new_joke_question', '$new_joke_answer' )";
$result = $mysqli->query($sql);
include "search_all_jokes.php";
?>
Return to the main page
Here is the db_connect.php code as requested:
<?php
// four variables to connect the database
$host = "localhost";
$username = "root";
$user_pass = "usbw";
$database = "test";
// create a database connection instance
$mysqli = new mysqli($host, $username, $user_pass, $database);
?>
Here is search_all_jokes.php (which has minor error checking):
// if there are any values in the table, select them one at a time
if ($mysqli->connect_errno) {
echo "Connection to MySQL failed: (" . $mysqli->connect_errno . ") " .
$mysqli->connect_error;
}
echo $mysqli->host_info . "<br>";
$sql = "SELECT JokeID, Joke_question, Joke_answer FROM Jokes_table";
$result = $mysqli->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "JokeID: " . $row["JokeID"]. " - Joke_question: " .
$row["Joke_question"]. " " . $row["Joke_answer"]. "<br>";
}
} else {
echo "0 results";
}
?>
Also here is the table structure screenshot viewed in myPHPAdmin:
I added error capturing into new_jokes.php inspired by this Stack Overflow post:
INSERT INTO SYNTAX ERROR
And 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 't jump.' )' at line 1localhost via TCP/IP
Thank you everyone for helping out with this! Syntax can really throw a wrench in everything. I also will read up on prepared statements since that also could have prevented the issue. The ultimate help to this I found the solution to by adding the function referenced here for MySQLi real_escape_string to clean the single quote I had within the answer I was submitting to my joke table:
(Can a kangaroo jump higher than the empire state building? Of course, the empire state building can't jump.)
As shown in the documentation #miken32 linked as a comment here it is says: "But if $val1 or $val2 contains single quotes, that will make your SQL be wrong. So you need to escape it before it is used in sql; that is what mysql_real_escape_string is for. (Although a prepared statement is better.)"
But now the code for this part 7 of the tutorial on you tube I found works and adds it into a row on the database table, then displaying the full new table on the next webpage. I spent a good while shooting in the dark on while the answer ended up being fairly simple. Again special thanks to #miken32 for pointing me the right direction.
Here is my completed code that ended up working to at least achieve the goal of the tutorial:
<?php
include "db_connect.php";
$new_joke_question = $_GET["newjoke"];
$new_joke_answer = $_GET["newanswer"];
$new_joke_question = $mysqli->real_escape_string($new_joke_question);
$new_joke_answer = $mysqli->real_escape_string($new_joke_answer);
// Search the database for the word chicken
echo "<h2>Trying to add a new joke and answer: $new_joke_question $new_joke_answer
</h2>";
if ($mysqli->connect_errno) {
echo "Connection to MySQL failed: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
echo $mysqli->host_info . "<br>";
$sql = "INSERT INTO Jokes_table (JokeID, Joke_question, Joke_answer) VALUES (' ',
'$new_joke_question', '$new_joke_answer' )";
$result = $mysqli->query($sql);
if ($mysqli->query($sql) === TRUE) {
echo 'users entry saved successfully';
}
else {
echo 'Error: '. $mysqli->error .'<br>';
}
include "search_all_jokes.php";
?>
Return to the main page
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'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 {
...
}
Hi all I have this line in my php code
`$insert = "DELETE FROM allocation_table WHERE job = '$jobnumber' " ;
Mysql_query ($insert) ;`
The problem is it will remove all the values from the one line in my table but not the entry itself. as you can see in the picture if I delete where job = 315 , it does not delete the line but does delete all the entries
Yet in this code that preceeds it (a different table) . it works fine and the whole line is removed
$insert = "DELETE FROM event WHERE jobnumber = '$jobnumber' " ;
mysql_query ($insert) ;enter code here
can anyone offer some advice please ?? alt text http://img34.imageshack.us/img34/4431/tablenj.jpg
Do you have any error handling routines in your code?
You might also want to add some debug output (or even better use a debugger like xdebug)
(oversimplified) example:
$insert = "DELETE FROM allocation_table WHERE job = '$jobnumber' " ;
echo '<pre>Debug: query=', htmlspecialchars($insert), '</pre>';
$rc = mysql_query($insert);
if ( !$rc ) {
echo '<pre>mysql_query failed: ', mysql_error(), '</pre>';
}
else {
echo '<pre>Debug: affected rows=', mysql_affected_rows(), '</pre>';
}
$insert = "DELETE FROM event WHERE jobnumber = '$jobnumber' " ;
echo '<pre>Debug: query=', htmlspecialchars($insert), '</pre>';
$rc = mysql_query($insert);
if ( !$rc ) {
echo '<pre>mysql_query failed: ', mysql_error(), '</pre>';
}
else {
echo '<pre>Debug: affected rows=', mysql_affected_rows(), '</pre>';
}
Maybe you have some weird setting on your MySQL table that is causing the query to function differently. Did you create the table yourself (with PMA?) or import it from somewhere else?
When you delete using PHPMyAdmin, what is the query that it runs?
Try deleting in PhpMyAdmin and see what happens. At least there you'll be able to easily see any error message.
Do you have foreign keys defined and/or table constraints?