MySql not inserting - php

Is not giving me any error, I am already linked with server but I am still unable to get it work.
It's still unable to add message, do you see any errors?
function pridaj_tovar() {
if ($link = spoj_s_db()) {
$sql = "INSERT INTO `Auto-Moto`".
"(`Tovar`, `Kategoria`,`Mesto`, `Cena`, `ID`, `Popis`)".
"VALUES".
"('$_POST['nazov']', '$_POST['kategorie']', '$_POST['mesta']',' $_POST['cena']', NULL,'$_POST['popis']')";
$result = mysql_query($sql, $link);
if ($result) {
// unable to add
echo '<p>inserting was successful.</p>'. "\n";
} else {
// unable to add!
echo '<p class="chyba">Nastala chyba pri pridávaní tovaru.</p>' . "\n";
}
mysql_close($link);
} else {
// NEpodarilo sa spojiť s databázovým serverom!
echo '<p class="chyba">NEpodarilo sa spojiť s databázovým serverom!</p>';
}
}

This is how you should handle field and table names with spaces,dashes (etc) :
$sql = "INSERT INTO `Auto-Moto`".
"(`Tovar`, `Kategoria`,`Mesto`, `Cena`, `ID`, `Popis`)".
"VALUES".
"('Something', 'Something1', 'word', '50', NULL, 'anotherword')";
$sql = "INSERT INTO `Auto-Moto`".
"(`Tovar`, `Kategoria`,`Mesto`, `Cena`, `ID`, `Popis`)".
"VALUES". "
('{$_POST['nazov']}', '{$_POST['kategorie']}', '{$_POST['mesta']}','{$_POST['cena']}',
NULL,'{$_POST['popis']}')";

You have several problems in your way of making query.
Firstly, your table name is quite non standard (Auto-Moto) so you might need to add quotes around it.
Secondly, it is always a good practice to add some space on proper locations so you could change:
"VALUES"
with
" VALUES "
But you need to provide which error you have received and your table structure.

You missed a lot of space in your Query :
Copy this :
$sql = "INSERT INTO Auto-Moto ".
"(Tovar, Kategoria, Mesto, Cena, ID, Popis) ".
"VALUES ".
"('Something', 'Something1', 'word', '50', NULL, 'anotherword')";

If you want to see an error message change this line:
$result = mysql_query($sql, $link);
To this:
$result = mysql_query($sql, $link) or die ("Error in query: $query. " . mysql_error());
But you should really learn to use mysqli_* extensions since mysql_* extensions—such as what you are using—will be depreciated in PHP 5.5. So change that to this:
$result = mysqli_query($sql, $link) or die ("Error in query: $query. " . mysqli_error());
And be sure to change any other mysqli_* extensions you code might have in place, such as in the spoj_s_db() function you are calling as the $link for a DB connection.
Additionally, your $sql has a few formatting errors. Try this instead:
$sql = "INSERT INTO Auto-Moto"
. " (Tovar, Kategoria, Mesto, Cena, ID, Popis)"
. " VALUES"
. " ('Something', 'Something1', 'word', '50', NULL, 'anotherword')"
;
Note the spaces in the query around the . " concatenation strings. In your original query the formatting had no spaces at all. Which would cause MySQL to choke on the query.

Related

cant insert data into existing table in mysql database with php

I get the message that the new record was created but when I reload phpmyadmin the table is the same. Also I have retrieved information from the same DB,
from the same table, with SELECT command, so the connection works..(plainly said). I have no clue why is not updating. Please help. Thank you in advance.
<html>
<head>
</head>
<body>
<?php
define('DB_NAME', 'appointments');
define('DB_USER', 'root');
define('DB_PASSWORD', '');
define('DB_HOST', 'localhost');
$link = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (!$link) {
die('Could not connect: ' . mysql_error());
}
$hos=$_POST['hos'];
echo $hos;
echo "<br/>";
$doc=$_POST['doc'];
echo $doc;
$date=$_POST['fdate'];
echo $date;
$time=$_POST['time'];
echo $time;
$pat=5;
echo $pat;
$sql = "INSERT INTO rantevou ('app_id','patient_id','date','time','hos','doc') VALUES ('4','$pat','$date','$time','$hos','$doc');";
if ($sql) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
mysqli_close($link);
?>
</body>
</html>
There are many mistake in your code
1. use of mysql_error()
you can't use mysql_error because you use mysqli for data base connection.second thing mysql is no more supported
Solution use mysqli_error($link);
2. use of $conn->error
You can't us of $conn->error beacuse you connect with mysqli procedure way not like object oriented way and you also not define a $conn instead you used $link
Solution use mysqli_error($link);
Correct Code
if(!mysqli_query($link, $sql)){
printf("Errormessage: %s\n", mysqli_error($link));
die;
}else{
echo "New record created successfully";
}
Why Data Not Inserted
because you declare variable $sql but you didn't executed that
the new record was created
You get this message all ways because your if condition check that variable have a value (not 0) and yes $sql have value
1.You must use prepare statement,if you don't wan't any sql injection in insert statement SQL INJECTION
2.'' single quote or "" apply only on a string not on id if your app_id is a int don't use ('' or "") quote instead of that convert '4' to int
3.handle error log https://stackoverflow.com/a/3531852/3234646
4.Please clear Concept use of Database Extension
http://php.net/manual/en/class.mysqli.php
You forgot to execute the query, if ($sql) { merely evaluates the variable.
if (mysqli_query($link, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
Also, you need to use backticks for SQL-related variables, not single quotes:
$sql = "INSERT INTO rantevou (`app_id`,`patient_id`,`date`,`time`,`hos`,`doc`) VALUES ('4','$pat','$date','$time','$hos','$doc');";
You're not actually executing your query. If you add the line $result = mysqli_query($link, $sql); after declaring $sql you will execute the query.
You can then assess whether it worked using the same if, but change that line to be
if ($result) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($link);
}
In the above example, I have also changed your error reporting as it was referencing $conn, a variable you had not declared before. It now uses the same $link variable as the rest of your code.
Also, I would highly recommend escaping your data since you're inserting the contents of posted data. Escaping your data will help protect against SQL Injection. It's not comprehensively safe, but it's a good start.
To add in escaping, change each $var = $_POST['var'] line to read $var = mysqli_real_escape_string($link, $_POST['var']);
For example, $hos=$_POST['hos']; becomes $hos = mysqli_real_escape_string($link, $_POST['hos']);
This helps prevent moments like this wonderful example by XKCD
1) Remove single quotes (') from column name to backtick (`)
2) Execute your query. You didn't executed.
3) If app_id column is auto incremented and primary key. Then, no need to pass value. Leave it blank.
<?php
$sql = "INSERT INTO rantevou (`app_id`,`patient_id`,`date`,`time`,`hos`,`doc`) VALUES ('','$pat','$date','$time','$hos','$doc');";
$query = mysqli_query($link,$sql) ;
if ($query) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
Instead of
"INSERT INTO rantevou ('app_id','patient_id','date','time','hos','doc') VALUES ('4','$pat','$date','$time','$hos','$doc');"
unquote the columns
"INSERT INTO rantevou (app_id, patient_id, date, time, hos, doc) VALUES ('4','$pat','$date','$time','$hos','$doc');"
or use backticks
"INSERT INTO rantevou (`app_id`, `patient_id`, `date`, `time`, `hos`, `doc`) VALUES ('4','$pat','$date','$time','$hos','$doc');"
you've forgot to execute your query
mysqli_execute($con, "INSERT INTO rantevou (`app_id`, `patient_id`, `date`, `time`, `hos`, `doc`) VALUES ('4','$pat','$date','$time','$hos','$doc')");
EDIT: What luweiqi said: the statement has yet to be executed!
It seems like you know what you are doing. Are you sure that the paramaters here:
$sql = "INSERT INTO rantevou (**'app_id','patient_id','date','time','hos','doc'**) VALUES ('4','$pat','$date','$time','$hos','$doc');";
if ($sql) {
exactly match your column titles in your database?
Another good way to check your statements, is to go to phpmyadmin and go to the SQL notepad and enter the query with the same structure and see what is being returned.
Your query may be returning a message, but a message saying that it has failed... which would still trigger your echo "New record created successfully";
This is how i've structured my most recent insert to DB:
<?php
// to get data from android app
$gardenID=$_POST["gardenID"];
$vID=$_POST["vID"];
$quantity = $_POST["quantity"];
$timePlanted = date("Y/m/d");
// establishes connection to database
require "init.php";
echo "here";
echo $timePlanted;
echo $quantity;
$query = "insert into garden_veg (gardenID, vID, quantity, timePlanted) values ('".$gardenID."','".$vID."',
'".$quantity."', '".$timePlanted."' );";
$result = mysqli_query($con,$query);
$response = array();
$code = "addItem_success"; //changed code
$message = "Item(s) added!";
array_push($response,array("code" => $code, "message"=>$message));
echo json_encode(array("server_response"=>$response));
mysqli_close($con);
?>
First of all, don't use single quotes for column names, either use nothing or use backticks.
Secondly, you forgot to execute the query.
Also, using OOP is better.
Please try:
$mysqli = new mysqli(DB_HOST,DB_USER,DB_PASSWORD,DB_NAME);
and
$query = "INSERT INTO rantevou (app_id,patient_id,date,time,hos,doc) VALUES ('4','$pat','$date','$time','$hos','$doc');";
if ($mysqli->query($query)) echo "New record created";
else echo "Error: ".$mysqli->error;

Data not inserting to MySQL database

I have my table setup as shown in the image below.
When I try and run the following code to insert the values into the database I get the error:
FAIL: INSERT INTO Betfairodds
(Horse,Back,Lay,TimeformTR)VALUES( 'Intrepid','5.5', '5.9',
'0')
Would anyone be able to help, as I have tried to debug the code.
//loop through each individual card
foreach ($getdropdown2 as $dropresults) {
$horse = preg_replace('/\h*[^ a-zA-Z].*$/m', '', trim($dropresults->childNodes->item(8)->textContent));
$back = trim(GetBetween($dropresults->childNodes->item(18)->textContent, 'Back', '£'));
$lay = trim(GetBetween($dropresults->childNodes->item(20)->textContent, 'Lay', '£'));
$sql = "INSERT INTO `Betfairodds` (`Horse`,`Back`,`Lay`,`TimeformTR`)VALUES( '$horse','$back', '$lay', '0')";
$res = mysqli_query($db, $sql);
if (!$res) {
echo PHP_EOL . "FAIL: $sql";
trigger_error(mysqli_error($db), E_USER_ERROR);
}
}
I removed the quotes ' from 0 because it is defined as int in the schema and of-course added space right before VALUES ..try this:
$sql = "INSERT INTO `Betfairodds` (`Horse`,`Back`,`Lay`,`TimeformTR`) VALUES( '$horse','$back', '$lay', 0)";
Your statement is wrong. You should not put single quotes on the data fields. so it should be like:
$sql = "INSERT INTO `Betfairodds` (Horse,Back,Lay,TimeformTR)VALUES( '$horse','$back', '$lay', '0')";

how to fetch mysql_query error

I'm trying to do this query using mySQL inside PHP and it's working with all tables except one "program", this is my code:
$query = " INSERT INTO program (program_name )
VALUES ($programName) ";
$result = mysql_query($query);
is there anyway to know why $result is always giving a false result?
This is the "program" table
You're missing quotes around your string value:
$query = " INSERT INTO program (program_name )
VALUES ('$programName') ";
To check for errors, just use mysql_error() (this is not a production ready example of how to do this):
$query = " INSERT INTO program (program_name )
VALUES ($programName) ";
$result = mysql_query($query);
if (!$result) {
echo mysql_error();
}
FYI, mysql_* functions are deparacated. You should switch to mysqli or PDO instead.
2 Things:
Your trying to insert more than 25 characters while your column has a length of 25 characters -> VARCHAR(25)
Your missing the quotes around the value:
$query = " INSERT INTO program (program_name )
VALUES ('$programName') ";
Use or die( mysql_error() ) to check/debug the SQL error.
$query = " INSERT INTO program (program_name )
VALUES ($programName) ";
$result = mysql_query($query) or die( mysql_error() );

MySQL Syntax error on Insert Query from PHP

I'm getting a non-descriptive syntax error on a MYSQL query from PHP. If I "echo" the text of the query and paste it into a MySQL query window, the code works. Here is the SQL for the query, the error code, and the error message...
INSERT INTO ADVERTISEMENTS (`user_id`, `ad_name`, `click_url`, `img_url`, `bg_color`, `start_date`, `end_date`, `timer_delay`, `add_date`) VALUES (2, 'Test New Ad', 'http://www.google.com', 'red_arrow.png', '#000000', '1980-05-11 00:00:00', '2020-05-01 00:00:00', 5, '2013-07-14 22:21:59');
Error Code: 1064
Error Msg: 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 '' at line 1
Here is the PHP code I am using...
$link = mysqli_connect($UM_Settings["database_options"]["server_name"], $UM_Settings["database_options"]["username"], $UM_Settings["database_options"]["password"], $UM_Settings["database_options"]["database_name"]);
$advertisementNameNew = mysqli_real_escape_string($link, $_POST['advertisementNameNew']);
$destinationURLNew = mysqli_real_escape_string($link, $_POST['destinationURLNew']);
$dropboxUploadFile = mysqli_real_escape_string($link, $_POST['dropboxUploadFile']);
$backgroundColorNew = mysqli_real_escape_string($link, $_POST['backgroundColorNew']);
$bannerStartDateNew = DateStringToMySQL($_POST['bannerStartDateNew']);
$bannerEndDateNew = DateStringToMySQL($_POST['bannerEndDateNew']);
$bannerSetTimerNew = intval($_POST['bannerSetTimerNew']);
$tmpUserID = UM_GetCookie("UM_UserID");
$tmpAddDate = DateStringToMySQL('now');
echo "INSERT INTO ADVERTISEMENTS(`user_id`, `ad_name`, `click_url`, `img_url`, `bg_color`, `start_date`, `end_date`, `timer_delay`, `add_date`) VALUES ($tmpUserID, '$advertisementNameNew', '$destinationURLNew', '$dropboxUploadFile', '$backgroundColorNew', '$bannerStartDateNew', '$bannerEndDateNew', $bannerSetTimerNew, '$tmpAddDate');<br />";
if (!mysqli_query($link, "INSERT INTO ADVERTISEMENTS(`user_id`, `ad_name`, `click_url`, `img_url`, `bg_color`, `start_date`, `end_date`, `timer_delay`, `add_date`) VALUES ($tmpUserID, '$advertisementNameNew', '$destinationURLNew', '$dropboxUploadFile', '$backgroundColorNew', '$bannerStartDateNew', '$bannerEndDateNew', $bannerSetTimerNew, '$tmpAddDate');")) {
printf("Error Code: %s\n", mysqli_errno($link));
echo "<br />";
printf("Error Msg: %s\n", mysqli_error($link));
}
I know that the database connection is working. I am able to select and update tables. I can also insert into other tables with different queries.
I am open to any suggestions.
Thank you in advance for your help!
I see a few errors in your query strings.
First, all your variables are passed as literal strings: "... VALUES ($tmpUserID, '$advertisementNameNew', ..." should be "... VALUES (".$tmpUserID.", '".$advertisementNameNew."', ...".
Second, I see missing quotes around $bannerSetTimerNew.
Third, there is an extra ;.
here's how I would write the query:
if (!mysqli_query($link, "INSERT INTO ADVERTISEMENTS (user_id, ad_name, click_url, img_url, bg_color, start_date, end_date, timer_delay, add_date) VALUES (".$tmpUserID.", '".$advertisementNameNew."', '".$destinationURLNew."', '".$dropboxUploadFile."', '".$backgroundColorNew."', '".$bannerStartDateNew."', '".$bannerEndDateNew."', '".$bannerSetTimerNew."', '".$tmpAddDate."')")) { ...
I didnt test it though.
hope this helps.
I see a ; at the end of the query. Are you sure that should be there?
There are two things
1. Remove the ; from at the end of the query.
2. I hope timer_delay field has datatype "Int" if its a VARCHAR then you will have to include quotes for that field value.
I hope this will help.
Passerby, thank you for your comment. This was my first experience with using mysqli, I changed my query to use the "bind_param" method, and everything works now. For anyone else with a similar problem, here is the corrected code...
$mysqli = new mysqli($UM_Settings["database_options"]["server_name"], $UM_Settings["database_options"]["username"], $UM_Settings["database_options"]["password"], $UM_Settings["database_options"]["database_name"]);
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
$advertisementNameNew = $_POST['advertisementNameNew'];
$destinationURLNew = $_POST['destinationURLNew'];
$dropboxUploadFile = $_POST['dropboxUploadFile'];
$backgroundColorNew = $_POST['backgroundColorNew'];
$bannerStartDateNew = DateStringToMySQL($_POST['bannerStartDateNew']);
$bannerEndDateNew = DateStringToMySQL($_POST['bannerEndDateNew']);
$bannerSetTimerNew = intval($_POST['bannerSetTimerNew']);
$tmpUserID = UM_GetCookie("UM_UserID");
$tmpAddDate = DateStringToMySQL('now');
/* Prepared statement, stage 1: prepare */
if (!($stmt = $mysqli->prepare("INSERT INTO `ADVERTISEMENTS` (`user_id`, `ad_name`, `click_url`, `img_url`, `bg_color`, `start_date`, `end_date`, `timer_delay`, `add_date`) VALUES (?,?,?,?,?,?,?,?,?)"))) {
echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
if (!$stmt->bind_param("issssssis",$tmpUserID, $advertisementNameNew, $destinationURLNew, $dropboxUploadFile, $backgroundColorNew, $bannerStartDateNew, $bannerEndDateNew, $bannerSetTimerNew, $tmpAddDate)) {
echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
}
if (!$stmt->execute()) {
echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}
$_GET['ad_id'] = $stmt->insert_id;
$stmt->close();

php insert mysql not working

.I don't know if it's syntax or what. I've tried a variety of ways this is the simplest I thought would work.
I send info to the userData.php using:
http://mydomain.com/adverts/userStats.php?name=001EC946C2F4&adNum=1&playClick=1
On the userData.php I have:
<?php
$db = mysql_connect('localhost', 'username', 'password') or die('Could not connect: ' . mysql_error());
$db_selected = mysql_select_db('databaseName', $db) or die('Could not select database');
if (!$db_selected)
{
die ("Can\'t use test_db : " . mysql_error());
}
$name = mysql_real_escape_string($_GET['name']);
$date = date("d/m/Y");
$adClick = mysql_real_escape_string($_GET['adNum]);
$playN = mysql_real_escape_string($_GET['playClick']);
$query = mysql_query("INSERT INTO playerData VALUES ('$name', '$date','$adClick','$playN')");
$result = mysql_query($query) or die('Query failed: ' . mysql_error()));
mysql_close($db);
?>
I manually added 2 records to the table from phpMyAdmin, and I can display or update them just fine but adding a new record isn't working. I simply want to start a new record each time the link is called from another program, and store the mac address, date, adNum, and playClick.
EDIT2:: echo $query; for
http://simplehotkey.com/adverts/userStats.php?name=001EC946C2F4&adNum=1&playClick=1
outputs:
INSERT INTO playerData(mac,date,AdClick,PlayNum) VALUES ('001EC946C2F4', '26/07/2012','1','1')
Which is what I want it's just not adding it to the DB.
Correct syntax is --
mysql_select_db("databaseName", $db);
And its better if u use something like this for connection errors--
$db_selected= mysql_select_db("databaseName", $db);
if (!$db_selected)
{
die ("Can\'t use test_db : " . mysql_error());
}
EDIT
You are writing all wrong :(
$query = mysql_query("INSERT INTO playerData VALUES ('$name', '$date','$adClick','$playN')");
$result = mysql_query($query) <--------------WRONG
Try Something like this----
$query = "INSERT INTO playerData(CORRECT_COL_NAMES) VALUES ('$name', '$date','$adClick','$playN')";
$results = mysql_query($query, $connection);
NEW EDIT
AREA OF ERROR---- WRONG DATATYPE
','1','1' <--- this is passing as string while u have have this as an int in your db structure ..now run the same query as it is to figure out the error..also u can figure out using $result = mysql_query($query) or die(mysql_error());
It's pretty easy to see what's wrong here, especially with syntax highlighting.
$adClick = mysql_real_escape_string($_GET['adNum]);
This line is missing a single quote mark; it should be:
$adClick = mysql_real_escape_string($_GET['adNum']);
This is a syntax error that ruins everything else.
Not to mention that your database selection is missing your database handler, ie:
mysql_select_db('databasename',$db);
As pointed out by #swapnesh, and as noted here.
Edit
I have been unable to reproduce your lack of an error, what I have gotten however, are errors. Firstly, you have an extra ) at line 12:
$result = mysql_query($query) or die('Query failed: ' . mysql_error()));
Should be:
$result = mysql_query($query) or die('Query failed: ' . mysql_error());
Lastly, you actually improperly execute your query twice, so the second time, the query is empty. What you have:
$query = mysql_query("INSERT INTO playerData VALUES ('$name', '$date','$adClick','$playN')");
$result = mysql_query($query) or die('Query failed: ' . mysql_error()));
Should instead be:
$query = "INSERT INTO playerData VALUES ('$name', '$date','$adClick','$playN')";
$result = mysql_query($query) or die('Query failed: ' . mysql_error());
Instead of using the insert statement the way you do add the fields that will receive entries explicitly. The database table might have more fields and the insert statement does not explcitly state which fields will receive data.
$query = mysql_query("INSERT INTO playerData (Name,Date,AdClick,PlayN) VALUES ('$name', '$date','$adClick','$playN')");
You have the syntax error on this line
Wrong :
$adClick = mysql_real_escape_string($_GET['adNum]);
Correct :
$adClick = mysql_real_escape_string($_GET['adNum']);

Categories