I've been inserting entries into a database using PHP for about a year now, then all of a sudden today they stop inserting. I can't work out why. Nothing has changed (as far as I know anyway!) Can anyone tell me what's wrong please:
include('db_functions.php');
connect_to_db();
$query="insert into mixtable (date, djname, title, description, music, tracklist, deleted) values ('".$date."','".$djname."','".$title."','".$description."','".$music."','".$tracklist."', 0)";
$result=mysql_query($query);
if(mysql_affected_rows()==1){
Header("Location:admin.php?op=admin&mix=added&news=null");
}
else{
die("there was a problem");
}
The db_functions work fine, I know this because on another page I call up the database info using the db_functions and it works fine. All of the variables exist as do the table entries. Like I said, this has been working fine for about a year now.
The problem I get is the "there was a problem" error. I've tried showing all errors, but that doesn't show anything either. I can't work out what it is. Any ideas?
Thanks in advance.
try to put "date" in single-quotes because date is a keyword in the current version of MySQL. The error might have happened because of database version upgrade (probably from 4 to 5).
If your table has an auto-increment ID, have you got to the maximum number allowed in that field?
There are few things which you need see.
-> See the below query
"insert into mixtable (date, djname, title, description, music, tracklist, deleted) values ('{$date}','{$djname}','{$title}','{$description}','{$music}','{$tracklist}', 0)";
When you are using double quote you need not use "." to append strings.
-> From the above explanation its quite clear that your query is not executing, try echoing the query and check it in sql editor you should be able to debug it quickly.
Related
Firstly, I know that this system shouldn't be using mysql_ functions anymore, but it does.
The system is connecting to two databases. Before running a query, it is selecting the correct database on which to run the query using mysql_select_db(). The correct database is 'database2'. The connection to the database itself works, and the mysql_select_db function is returning true/1.
The code works locally but does not work on the server...
Here is an example of a failing query...
global $DBtwo;
mysql_select_db('database2', $DBtwo);
$sql = "INSERT INTO table
(Column1, Column2, Column3)
VALUES
('Value1', 'Value2', 'Value3')";
$result = mysql_query($sql, $DBtwo);
die(mysql_error());
This script returns the following output...
Table 'database1.table' doesn't exist
The error suggests that the query is being executed on database1, not database2. However database2 is being successfully selected before the query is run.
As mentioned, this error only occurs on the server. Running locally the queries work and the correct databases are used.
Any suggestions or pointers would be very welcome. Cheers.
The comment from Marc B solved my problem so credit goes to him.
The mysql_error function was returning misleading info as it was not being passed a resource.
The mysql_select_db was actually working. It gave the impression of not working via a combination of not passing the correct resource to mysql_error. On top of that a mysql_insert_id() was not working for the same reason, leading the function overall to return false.
I now feel stupid, but far less annoyed. Many thanks!
I'm learning PHP and MySQL and made a small website to help me learn. While I was implementing MySQLi, I kept getting an error with the code. I tried various things like trying to query all the tables contents but I get 0 rows even though I have a few already there. I'm using WAMP Server 2.5 and The connection is successful but anything else seems to not work.
When I use the code:
$sql = "USE mydb
INSERT INTO persons (Name, User, Pass)
VALUES ('John', 'Doe', 'johnexample');";
if ($conn->query($sql) === TRUE){
echo "Success";
}else{
echo "Error, Please Try Again Later<br>".$conn->error;
}
$conn->close();
I'm surprised this doesnt work because it's almost the exact same as the example on the W3 Schools webiste. I've seen other posts with this error but their solutions dont work. The error I get is:
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 'INSERT INTO
persons (Name, User, Pass) VALUES ('John', 'Doe', 'johnexample')' at line 2
Any help is appreciated! Thank You!
The issue is mysqli::query doesn't support multiple queries, and even if it did, it would require the ; terminator. This is causing your SQL syntax error.
If you want to change the current database for the connection, you can use:
$conn->select_db('mydb');
Then you can do your INSERT query without the USE part, which will be applied to mydb.
Be aware that the fieldnames are case-sensitive! please check if Name, User, Pass are really start with a capital.
mysql_query("INSERT INTO new_emails (from,subject,message,to,filename,fileurl) VALUES ('$id','$stripsubj','$content','$toids','$upload_name','$att')");
Firstly, I am aware that mysql_query is depreciated, and I will be re-doing the whole script at some point in the near future to accommodate this.
My main problem is that this query is not currently inserting anything into the database, and I haven't the faintest clue why. Unfortunately I don't have access to any phpMyAdmin logs/SQL logs that can help me debug this problem.
I have been working on this for a while so I am hoping I have something pretty stupid and not noticed.
The columns inside "new_emails" are: id,from,savedtodb,subject,message,to,filename,fileurl
The ID is auto_increment, and savedtodb is CURRENT_TIMESTAMP, which is why I am leaving them out.
Have I done anything particularly stupid or is there a deeper reason why this isn't working?
Cheers in advance!
from and to are reserved words. You need backticks for them:
INSERT INTO new_emails (`from`, subject, message, `to`, filename, fileurl)
VALUES ('$id', '$stripsubj', '$content', '$toids', '$upload_name', '$att')
There are some possible errors:
1) You may not have selected the database using mysql_selct_db or while declaring the connection.
2) Maybe you didn't escape the single quotes. MySQL hates single quotes, and would make an error if it finds any in the input.
I am experiencing something so basic, yet so annoying that I thought I had to put it out to the wider community to save my sanity.
I am using a table within a database to store some very basic data. There is only two columns, Id and Campaign. I only want to use a single row of the table, however, campaign will be updated at various points. I have set up the table as follows:
$sql = "CREATE TABLE IF NOT EXISTS TestCampaign(id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
Campaign CHAR(20))";
Initially I write to the table to insert a null CHAR in campaign:
$sql = "INSERT INTO TestCampaign (Campaign) VALUES ('None')";
The based on a specific text field being filled in on an html form followed by a submit button press I intended to do the update of the campaign field:
$sql = "UPDATE TestCampaign SET Campaign = '$Test' WHERE id = '1'";
$Test is the POSTED campaign name from the form. Unfortunately although the INSERT works fine the UPDATE doesn't. I have checked the permissions and I have ALL on this database. I have also checked the syntax with various sites and it seems that it is fine.
Interestingly I do not get an error when I echo:
echo " ".mysqli_error($con);
I'm sure I have made some basic error somewhere but I have been looking at it for so long and changing the syntax that I can't seem to spot it.
Any help would be appreciated.
UPDATE:
I have played around with the code and it seems as though the UPDATE code does work, however, It only works when it is the next line of code after the INSERT. In fact I have found that it works as long as it is not where I need it to be. I have it placed in 'if' statement that is run only on a specific button press on the form:
if(isset($_POST['TestID']))
{
Some Code;
$sql = "UPDATE TestCampaign SET Campaign = '$Test' WHERE id = '1'";
Some More Code;
}
I have checked the rest of the code in the 'if' statement and it seems solid.
Is this odd behaviour or have I missed something?
SOLVED
Finally found out what the problem was, it ended up that when exiting the first 'if' statement as expected the html form code was revisited which must have closed the connection to the database, when the button was pressed to run the second 'if' statement there was a connection to MySQL but no connection to the database I needed access to. A quick fix to re-connect and all works fine.
$sql = "UPDATE TestCampaign SET Campaign = '$Test' WHERE id = 1";
Is the only thing I think is wrong... What do you get with :
Select * from TestCampaign
have you set up any triggers based on this table name? After update, before update triggers may prevent you from storing the required data on the table.
Also, MySQL may use 0 as id value if you don't specify the value of the id at sending insert command. Are you sure the value of your id is 1 in the record you want to update? If you have run insert statements before on your table, the id may be a larger number than 1, because of the MySQL indices (I guess this may be the problem).
I don't know how exactly PHP statements are processed when sending them to MySQL, but I would recommend you to use PDO statements, the PHP syntax would look something like this:
$sql = $pdo->prepare("UPDATE TestCampaign SET Campaign = ? WHERE id = ?");
$sql->bindParam(1, $Test);
$sql->bindParam(2, 1);
$sql->execute();
Tutorial: http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers
I would also echo your $Test variable to check what is stored in it.
Hope it helps...
Finally found out what the problem was, it ended up that when exiting the first 'if' statement as expected the html form code was revisited which must have closed the connection to the database, when the button was pressed to run the second 'if' statement there was a connection to MySQL but no connection to the database I needed access to. A quick fix to re-connect and all works fine.
Ok. So right now, my line of code for inserting looks like this:
$query=mysqli_query($con,"insert into orders values (".$user_index.",".$order_date.",".$_POST['item_number'].",".$_POST['price'].",".$_POST['tax'].",'".$_POST['pay_method']."')");
$order_date is a date. $user_index and $_POST['item_number'] are INTs. $_POST['price'] and $_POST['tax'] are doubles. $_POST['pay_method'] is an enum. At the moment, I really couldn't care less about SQL-injection. I just want a working page for now. I'll secure it before it goes live on my website.
My virtual server throws exceptions whether I put in "die(mysqli_error($con))" or not. However, in this case, it is definitely reaching the code that's in the same if statement after the insert statement. Yet, when I run this code, everything looks fine but nothing has changed in the database.
I have tried:
insert into orders (user_index,order_date,item_number,...) values (...)
but it doesn't work that way either.
Finally, yes, I have asked a similar question before. But as I am new to this website, didn't know if there was a way to edit my old question, and figured this would just be easier since I have more details now and I could possibly get the same people as before to answer this with their questions and troubleshooting steps answered; I just went ahead and posted a new question.
You're not adding ' around your string variables. :
If you knew what the values where you'd add them like this:
insert into orders values ('value1','value2' //etc
Your code:
"insert into orders values (".$user_index.".$value2." //etc
Is equivalent to:
"insert into orders values (value1,value2 //etc
Which is wrong, to fix this add in the ' marks like so:
$query=mysqli_query($con,"insert into orders values ('".$user_index."','".$order_date."','".$_POST['item_number']."','".$_POST['price']."','".$_POST['tax']."','".$_POST['pay_method']."')");
For future reference a good way to debug dynamically created SQL statements is to assign them to a variable, named something like $sql, then run your mysqli_query($con,$sql). That way if it's not working you can var_dump or echo your $sql variable and see what's really being queried.
if order_date is a date you need to pad the string with ' on both sides.
$query=mysqli_query($con,"insert into orders values (".$user_index.",'".$order_date."',".$_POST['item_number'].",".$_POST['price'].",".$_POST['tax'].",'".$_POST['pay_method']."')");