i am very new at MYSQL and after i created this script to update a row in the table of a MYSQL Database and run it i get this 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 '265'', Employer_VAT_number = ''45698'', Employer_Name = ''Namtax_Ltd'', Employer' at line 3
here is the code
// username and password sent from form
$Numb=$_POST["Numb"];
$VAT=$_POST["VAT"];
$Name=$_POST["Name"];
$Addr=$_POST["Addr"];
$PO=$_POST["PO"];
// To protect MySQL injection (more detail about MySQL injection )
$Numb = stripslashes($Numb);
$VAT = stripslashes($VAT) ;
$Name = stripslashes($Name) ;
$Addr = stripslashes($Addr) ;
$PO = stripslashes($PO) ;
$Numb = "'" . mysql_real_escape_string($Numb) . "'";
$VAT = "'" . mysql_real_escape_string($VAT) . "'";
$Name = "'" . mysql_real_escape_string($Name) . "'";
$Addr = "'" . mysql_real_escape_string($Addr) . "'";
$PO = "'" . mysql_real_escape_string($PO) . "'";
$sql=("UPDATE $tb1_name SET Employer_Registration_Number ='".$Numb."', Employer_VAT_number = '".$VAT."', Employer_Name = '".$Name."', Employer_Address = '".$Addr."', Employer_Postal_Address = '".$PO."' WHERE Employer_Name = '".$Name."' ");
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "Successfully Updated";
mysqli_close($con);
?>
</body>
This here:
$Numb = "'" . mysql_real_escape_string($Numb) . "'";
Firstly, that isn't proper syntax and you're using mysqli_ to connect with, least I sure hope you are.
Those different MySQL APIs do not intermix with each other.
That should read as:
$Numb = mysqli_real_escape_string($con,$Numb);
while doing the same for the rest of your variables, following the same method outlined here.
Footnotes:
Seeing you didn't post what $tb1_name is, doubt that would be causing an issue. But just for the sake of argument, wrap that variable in ticks, just so if your table name changes to something containing a hyphen or a space, or anything that MySQL will complain about.
UPDATE `$tb1_name` SET...
Plus, since you didn't mention which MySQL API you're using to connect with, make sure it is in fact mysqli_ and not mysql_ or PDO.
It doesn't look like it, but I have to be 100% sure.
Your connection should resemble something like this:
$con = mysqli_connect("yourhost","user","pass","your_DB")
or die("Error " . mysqli_error($con));
Again, those different MySQL APIs do not intermix with each other.
Consult (PHP: Choosing an API - Manual): https://php.net/mysqlinfo.api.choosing
"I am very new at MYSQL..."
Seeing you're new to this:
Use mysqli with prepared statements, or PDO with prepared statements.
Additional notes. (as an edit)
I noticed another question you posted earlier:
https://stackoverflow.com/q/30191388/
where you said "Thank you it worked " in the answer given https://stackoverflow.com/a/30191647/
I don't get that.
How could that possibly work where you're using if (!mysqli_query($con,$sql))?
You'll need to show us the way you're connecting with here.
If you truly want to see if your query was successful, use mysqli_affected_rows().
if(mysqli_affected_rows($con)){
echo "Successfully updated.";
}
else{
echo "Not updated.";
}
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Error reporting should only be done in staging, and never production.
Related
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
Have some problem I couldn't find solution for, though searched through many sources (and questions here too). So, here it is.
With the PHP-code below I suppose to collect data from a HTML-form and send it to a local WAMP-server. But, though final check shows me "Success!", no new rows in the database's table are found, it stays empty. Names are correct, commands are (as I see it) too, so I just don't know what's wrong.
I hope you guys could help me. ^^
//Check if user submited a form
if (isset($_POST['submit'])) {
//Check if from is properly filled
if (empty($_POST['itemName']) || empty($_POST['itemPic']) || empty($_POST['itemPrice']) || empty($_POST['itemProvider'])) {
echo '<script>alert ("Fill out the form please!")</script>';
} else {
$conn = new mysqli('localhost:3306', 'root', '', 'goods-review');
//Check if connection established
if (mysqli_connect_errno()) {
exit('Connect failed: ' . mysqli_connect_error());
}
//Sending data
$newItem = array('itemName' => $_POST['itemName'], 'itemPic' => $_POST['itemPic'], 'itemPrice' => $_POST['itemPrice'], 'itemProvider' => $_POST['itemProvider']);
$sql = "INSERT INTO goods (itemName, itemPic, itemPrice, itemDate, itemProvider) VALUES ('" . $newItem['itemName'] . "', '" . $newItem['itemPic'] . "', '" . $newItem['itemPrice'] . "', date('Y:m:d, H:i:s'), '" . $newItem['itemProvider'] . "')";
//Check if sent
if ($sql) {
echo '<script>alert ("Success!")</script>';
} else {
echo '<script>alert ("Error!")</script>';
}
$conn->close();
}
}
The code is just assigning a string value to a variable.
$sql = "INSERT ...";
And the string value is not submitted to the database; it's not being executed as a SQL statement. There's nothing magical about the name of the variable. As far as PHP is concerned, the code is just assigning a value to a variable. That's it.
If you want to execute a SQL statement, you need to add code that actually does that. It shouldn't be difficult to find an example of how to do that.
IMPORTANT NOTE: The code in the question appears to create a SQL statement that is vulnerable to SQL Injection. A much better pattern is to use prepared statements with bind placeholders.
Reference: mysqli_prepare
If there's some (unfathomable) reason that you can't use prepared statements, then at a minimum, any potentially unsafe values that are included in the SQL text must be properly escaped.
Reference: mysqli_escape_string
If you have setup the $newItem array first.
Normaly you will validate the user-input and ensure that the user-input has no SQL injections in it.
Read here about it: What is SQL injection?
After that
(You have to add $newItem['itemDate']=date('Y:m:d, H:i:s');)
$sql = "INSERT INTO goods (".implode(', ',array_keys($newItem)).")"
." VALUES ('".implode("', '",$newItem)."')";
if (mysqli_query($conn,$sql)){
echo '<script>alert ("Success!")</script>';
} else {
echo '<script>alert ("Error!")</script>';
}
If you are using this:
you dont have too keep an eye on the right field order
every field value becomes ' around them
you have less code to write
field count and order can change
Finally mysqli_query() returns FALSE if nothing is insert and you can check for that.
Sidenote: Try to use OOP Version of the MYSQLi Extention and Prepared Statments. Read about it here: mysqli, OOP vs Procedural
Alright. I have searched and searched for an answer, but I just could not find it.
I am writing a simple php script that takes the url information and runs it through a MySQL query to see if a result comes up. I try to echo the variable holding the query out, but nothing shows up. I know there must be a result because if I enter the query manually in MySQL it displays my desired result.
$result = mysqli_query("SELECT * FROM pages WHERE pageq = '" . $_GET['page'] . "'" );
$data = mysqli_fetch_assoc($result);
echo ("You have just entered in " . $data['id'] . "!!! YAY");
I have tried to echo out both the $result and $data. But there is nothing displayed. I am so new to programming, and this is my first StackOverflow post, so forgive me if I am making huge errors.
Actually mysqli_query() requires two parameters... check the following sample example ..
<?php
$conn = mysqli_connect('localhost','root','','your_test_db');
$_GET['page'] = 1;
$result = mysqli_query($conn,"SELECT * FROM your_table WHERE id = '" . $_GET['page'] . "'");
$data = mysqli_fetch_assoc($result);
echo ("You have just entered in " . $data['id'] . "!!! YAY");
?>
As you have stated you are just in a learning phase, it is okay to code these sort of queries just to learn yourself but do not code these kind of queries as these queries are vulnerable so i would suggest you to use prepare queries or PDO...
Also never use SELECT * in your queries, this is a bad practice, only deal with the fields which you requires in return.
Also, you can always check whether your database is connected or not. So that you have a better idea.
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
you have not mentioned whether you are following OOP structure or not .. so i would suggest you to check error_reporting() and connect database on the same page to check the things around ..
Also you can check whether you without WHERE condition for now "SELECT * FROM your_table just to make sure whether you are getting atleast all the records or not.
The problem is that you're not setting up the connection in the query. mysqli_query() requires two parameters.
Make the connection first:
$conn = mysqli_connect("localhost", "user", "password", "dbname");
Now execute the query:
$result = mysqli_query($conn,"SELECT * FROM pages WHERE pageq = '" . $_GET['page'] . "'" );
NOTE: Your code is heavily vulnerable to MySQL injections. Use MySQLi or PDO Prepared statements.
Also, you should use mysqli_errno() to find out your query bugs.
Edit:
Also do this:
while($row=mysqli_fetch_assoc($result)){
//do the result output.
}
It's pretty much one of my first times working with MYSQL, and I can't seem to fix this one error I keep getting. I'm trying to store data to a table which has an auto_increment on its id (first column).
The error I keep getting is this:
"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 'voorletters ='asd', tussenvoegsel ='', achternaam ='', roepnaam ='', adres ='', ' at line 1"
I just filled the textboxes with a little bit of rubish, there are no columns that require data either. Here is the code I use:
if(isset($_POST['save']))
{
$voorletters = $_POST['voorletters'];
$tussenvoegsel = $_POST['tussenvoegsel'];
$achternaam = $_POST['achternaam'];
$roepnaam = $_POST['roepnaam'];
$adres = $_POST['adres'];
$postcode = $_POST['postcode'];
$plaats = $_POST['plaats'];
$geslacht = $_POST['geslacht'];
$emailadres = $_POST['emailadres'];
$telefoonnummer = $_POST['telefoonnummer'];
$mobielenummer = $_POST['mobielenummer'];
$geboortedatum = $_POST['geboortedatum'];
$bsn = $_POST['bsn'];
mysql_query("INSERT INTO `naw` "
. "voorletters ='$voorletters', "
. "tussenvoegsel ='$tussenvoegsel', "
. "achternaam ='$achternaam', "
. "roepnaam ='$roepnaam', "
. "adres ='$adres', "
. "postcode ='$postcode', "
. "plaats ='$plaats', "
. "geslacht ='$geslacht', "
. "emailadres ='$emailadres', "
. "telefoonnummer ='$telefoonnummer', "
. "mobielenummer ='$mobielenummer', "
. "geboortedatum ='$geboortedatum', "
. "bsn ='$bsn' "
. "WHERE id = '$id'")
or die(mysql_error());
If this isn't enough information, please tell me. I've tried a lot of things, but I can't seem to figure it out.
You mix up insert and update syntax. Replace
INSERT INTO `naw` voorletters ='$voorletters'...
with
UPDATE `naw` set voorletters ='$voorletters'....
And you should really use Prepared Statements to avoid syntax errors and SQL injections due to user input.
You have a wrong syntax
The INSERT syntax is
INSERT INTO `YourTableName`(`Field1`, `Field2`, `Field3`, `Field4)
VALUES ('value-1','value-2','value-3','value-4')
The UPDATE syntax is
UPDATE `YourTableName`
SET `Field1`='value-1',`Field2`='value-2',`Field3`='value-3',`Field4`='value-4'
WHERE YourConditions
Just use following code. Make sure that you are inserting data for every field sequentially-
mysql_query("INSERT INTO `naw` VALUES(
'".$voorletters."',
'".$tussenvoegsel."',
'".$achternaam."',
'".$roepnaam."',
'".$adres."',
'".$postcode."',
'".$plaats."',
'".$geslacht."',
'".$emailadres."',
'".$telefoonnummer."',
'".$mobielenummer."',
'".$geboortedatum."',
'".$bsn."')")
or die(mysql_error());
You should remove the `` around naw, it's ok in phpmyadmin but quite messy almost every where else.
And you souldn't concatenate every line, do it in one "..." and use backspace to make it more readable.
So:
mysql_query("INSERT INTO naw
VALUES('$voorletters',
'$tussenvoegsel',
... ,
WHERE id = '$id'");//you can't do that, maybe you should use an UPDATE
I have my code below to update a my MySQL database, it's running but is not updating the database when I check rcords using phpmyadmin. plae hlp me.
$database = "carzilla";
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
$manufacturerTable = $_POST[vehicleManufacturer];
$numberToSearch = $_POST[vehicleIdNo];
$engineType = $_POST[engineType];
$engineCC = $_POST[engineCC];
$year = $_POST[year];
$numberofDoors = $_POST[numberofDoors];
$tireSize = $_POST[tireSize];
$chasisNumber = $_POST[chasisNumber];
$vehicleMake = $_POST[vehicleMake];
$price=$_POST[price];
mysql_select_db("$database", $con);
$sql = mysql_query("UPDATE $manufacturerTable SET username='vehicleMake',
engineType='$engineType', engineCC='$engineCC', year='$year', chasisNo='$chasisNumber', numberOfDoors='$numberofDoors' ,numberOfDoors='$numberofDoors', tireSize='$tireSize', price='$price' WHERE `index` ='$id'");
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo 'record has been successfuly';
mysql_close($con);
?>
Take a good look at your query. You are referring to PHP variables in several different fashions in the same statement. In the query $manufacturerTable is just $manufacturerTable, you encase a few others in single quotes, some of which you remove the $ from, others you do not. I know I preach this far too often, but you should really look into using prepared statements. They take all the guess work out of using variables in your queries, and they prevent you from being victimized by injection hacks. But the short answer here is that you are not referencing your variables correctly in the query.
Sometimes putting the variables directly in the syntax can cause issues. Have you tried to use concatenation for the query.
$query = "UPDATE ".$manufacturerTable." SET username='vehicleMake', engineType='."$engineType."', engineCC='".$engineCC."', year='".$year."', chasisNo='".$chasisNumber."', numberOfDoors='".$numberofDoors."' ,numberOfDoors='".$numberofDoors."', tireSize='".$tireSize."', price='".$price."' WHERE index =".$id;
$sql = mysql_query($query); # this should be put in the if else
If index is number based you do not need the '' surrounding it. Plus is username='vehicleMake' or is it a variable. if it is a variable, add the $ or use concatenation like the rest. Your SQL check should be something like follows.
if (mysql_query($query))
{
echo 'record has been successfuly';
} else {
die('Error: ' . mysql_error() . ' | ' . $query);
}
The reason you export the query is so you can try it manually to make sure it works and what error you may be getting. phpMySQL can show a different error then the mysql_error() at times
Plus you should be escaping all input that is user entered using mysql_escape_string() or mysql_real_escape_string()