basically, I have 3 tables; users and projects, then I have 'users_projects' to allow the one-to-many formation. When a user adds a project, I need the project information stored and then the 'userid' and 'projectid' stored in the usersprojects table. It sounds like its really straight forward but I'm having problems with the syntax I think!?
As it stands, I have this as my INSERT queries (values going into 2 different tables):
$projectid = $_POST['projectid'];
$pname = $_POST['pname'];
$pdeadline = $_POST['pdeadline'];
$pdetails = $_POST['pdetails'];
$userid = $_POST['userid'];
$sql = "INSERT INTO projects (projectid, pname, pdeadline, pdetails) VALUES
('{$projectid}','{$pname}','{$pdeadline}','{$pdetails}')";
$sql = "INSERT INTO users_projects (userid, projectid) VALUES
('{$userid}','{$projectid}')";
$result = mysql_query($sql, $connection)
or die("MySQL Error: ".mysql_error());
header("Location: frontview.php");
exit();
You simply forgot to execute the sql between each query. Add the
mysql_query($sql, $connection)
or die("MySQL Error: ".mysql_error());
between each query and you are supposed to be fine.
b.t.w (1) it always helpful to test with a console open with tail -f on the sql log (under /var/log/mysql/ )
b.t.w.(2) You are having heavy security issues in your code.
b.t.w (3) You might want to consider using PDO/Mysqli and not the old mysql extension.
b.t.w (4) It would make your life simpler to use some kind of wrapper (a good class) to approach the DB and not do it directly everywhere in your code.
Yeah, two things I would check would be
1) are the queries being executed? Like the other poster mentiond, are you executing the SQL queries in between setting the SQL?
2) if you print/debug/display somehow the variables that you are inserting, are they getting populated? If you're seeing things get inserted, but some of the data is blank then something might be blowing up before that and those variables would be blank.
I may be misunderstanding but are you putting header("Location: main.php"); in the middle of you script?
$projectid=mysql_insert_id($connection);
I called this after my first query, this will get the AutoIncrement value from your projects table and store it in $projectid, then the second query will use it.
so after execution of my first query, I put the above code there, without changing anything else!!
You seem to be trying to execute mysql_query() only once. You have two queries, so it needs to be used twice, once on each query:
$sql = "INSERT INTO projects (projectid, projectname, projectdeadline, projectdetails) VALUES
('{$projectid}','{$projectname}','{$projectdeadline}','{$projectdetails}')";
$result = mysql_query($sql, $connection)
or die("MySQL Error: ".mysql_error());
$sql = "INSERT INTO usersprojects (userid, projectid) VALUES
('{$userid}','{$projectid}')";
$result = mysql_query($sql, $connection)
or die("MySQL Error: ".mysql_error());
Alternatively, you could use mysqli_multi_query(), but that might require a significant rewrite of your code to use the mysqli interface.
Related
$query = "INSERT INTO users ". "(first_name,last_name,dob,mobile_number,landline_number,email) ". "VALUES('$fname','$sname','$dob','$mobile','$landline','$email', NOW())";
$query = "INSERT INTO address ". "(house_number,street_name,town/city,postcode,province/county) ". "VALUES('$hnumber','$addr','$town','$pcode','$county', NOW())";
$result = mysqli_query($conn, $query) or die("Invalid query 2"); // runs query using open connection
So I can create a connection to my database no problem and on my previous page I can send username and password to the database but then I come to the user details page to save the information and continually getting Invalid query 2 error. The table names are correct (users & address) and all variables are spelt correctly. Does anyone have a suggestion to fix the issue or a better alternative (I mean to just point me in the right direction of the research I should be looking at if I am way off target, if I have just mispelled something or have something in the wrong place then I would appreciate the heads up, have been at this quite a while now)
This is the code from the previous page and it works fine and sends the information to the database:
$query = "INSERT INTO login ". "(username,password) ". "VALUES('$uname','$epass', NOW())";// sets up sql query
$result = mysqli_query($conn, $query) or die("Invalid query 2"); // runs query using open connection
mysqli_close($conn); // close database connection
As far as I know all the database side of things is fine, all data types are varchar except for dob which is date (I have tried changing this to varchar to see if it fixed the problem but it didnt) and userID is int and is an autoincrement for the unique primary key. I have also tested the php file without the validation rules and still gives the same error.
Quite a few things wrong here.
First you are reassigning the variable $query; so the first insert will be getting overwritten by the second, you need to concat the variable.
Then you have 2 queries you are attempting to send at one time. However you never tell Sql you've finished your first before starting your second.
Try the following instead take note Of The semi colons ; at the end of each.
You are also putting slashes into your column names which is illegal.
Lastly, you've got more values to insert than you have columns. Remove the now() from the end.
$query = "INSERT INTO users ". "(first_name,last_name,dob,mobile_number,landline_number,email) ". "VALUES('$fname','$sname','$dob','$mobile','$landline','$email');";
$query .= "INSERT INTO address ". "(house_number,street_name,town_city,postcode,province_county) ". "VALUES('$hnumber','$addr','$town','$pcode','$county');";
Although this will now work, I highly recommend you do some research regarding safe practices with Sql.
Here would be a great starting point https://www.w3schools.com/php/php_mysql_prepared_statements.asp
On a side note, why are you concating your Strings? There's no need
$query = "INSERT INTO users (first_name,last_name,dob,mobile_number,landline_number,email) VALUES('$fname','$sname','$dob','$mobile','$landline','$email', NOW());";
Maybe it's the fact that you are closing the connection after your first call.
try or die(mysqli_error($conn));
EDIT:
Delete passing value "NOW()".
code:
$query = "INSERT INTO address ". "(house_number,street_name,town_city,postcode,province_county) ". "VALUES('$hnumber','$addr','$town','$pcode','$county')";
I have to insert data in two different database's table.
I have created database1 and table1 for database1,
also i have created database2 and table2 for database2.
For inserting data i have written code,
$connect = mysql_connect("localhost","root",""); //database connection
mysql_select_db("database1",$connect); // select database1
mysql_select_db("database2",$connect); // select database2
$sql = mysql_query("INSERT INTO database1.table1 (contact_first, contact_last, contact_email) VALUES('abc','xyz','abc#abc.com')"); //insert record to first table
$sql1 =mysql_query("INSERT INTO database2.table2 (contact_first, contact_last, contact_email) VALUES('abc','xyz','abc#abc.com')"); //insert record to second table
please suggest me corrections for above code to insert data.
Try the following code:
$connect1 = mysql_connect("localhost","root","");
mysql_select_db("database1", $connect1);
$res1 = mysql_query("query",$connect1);
$connect2 = mysql_connect("localhost","root","",true);
mysql_select_db("database2", $connect2);
$res2 = mysql_query("query",$connect2);
Note: So mysql_connect has another optional boolean parameter which
indicates whether a link will be created or not. as we connect to the
$connect2 with this optional parameter set to 'true', so both link will
remain live.
Simply connect to 1 database, insert new row, disconnect, connect to the other database, insert row into that one and disconnect.
Or you can use $connect1 and $connect2 to refer to each of them separately and do the insertion parallely.
EDIT: Btw you can select the database with the 4'th parameter of mysql_connect, no need to use mysql_select_db
And very important, you should write mysqli not mysql. Because mysql functions are not going to be supported for much longer.
first create two database connections
$connect1 = mysql_connect("localhost","root","");
$connect2 = mysql_connect("localhost","root","");
Then select the database for each connection.
mysql_select_db("database1",$connect1); // select database1
mysql_select_db("database2",$connect2); // select database2
Then pass in a second argument for mysql_query which is the respective connection for the query.
mysql_query("SELECT ... ", $connect1);
mysql_query("SELECT ... ", $connect2);
Well, if there's a pattern in db names, tables and queries are exactly the same, you can use a loop:
for ($i = 1; $i <=2; $i++) {
mysql_select_db("database".$i, $connect);
$sql = mysql_query("INSERT INTO table".$i." (contact_first, contact_last, contact_email) VALUES('abc','xyz','abc#abc.com')");
mysql_close;
}
However, using mysql_* is strongly NOT recommended, as it is deprecated from the last stable PHP release and is considered unsafe. Use PDO or MySQLi instead. PHP's official site suggests the article "Choosing an API": http://www.php.net/manual/en/mysqlinfo.api.choosing.php
Well, that's how i do it...
1 - connect --> that you are doing right
2 - check for errors
3 - USE a database (1) you want to put data in (and not 'SELECT')
4 - check for errors
5 - now INSERT items into the database THAT IS BEING USED - that is (1)
6 - check for errors
7 - USE the other database (2)
8 - check for errors
9 - INSERT the data into (2) - because that is the one in use now
10 - check for errors
Yes, be paranoid :P Hope this helps
I'm slowly progressing through PHP and SQL and have stumbled upon a small error, when trying to send a string into an SQL database. What I'm trying to do is insert a users's detail into one table (which currently works) and send the user name along with 5 blank entries into another table. The table examscore fields are username, exam, exam1, exam2, exam3, exam4 (it is these exam fields that I require blank for now).
The problem is that I receive the following message:
Parse error: syntax error, unexpected T_CONSTANT_ENCAPSED_STRING in C:\xampp\htdocs\E-LearningWebsite\addcustomertodb.php on line 11 (which line that starts $query1)
If possible could anyone explain what this error means and what i have done wrong?
<?php
require "dbconn.php";
$username = $_GET['username'];
$email = $_GET['email'];
$pass = $_GET['password'];
$query = "INSERT INTO customer VALUES ('".$username."','".$email."','".$pass."')";
$query1 = "INSERT INTO examscores VALUES ('".$username."','""','""','""','""','""')";
$results = mysql_query($query) or die (mysql_error());
$results1 = mysql_query($query1) or die (mysql_error());
?>
Kind regards Andy
change
$query1 = "INSERT INTO examscores VALUES ('".$username."','""','""','""','""','""')";
to
$query1 = "INSERT INTO examscores VALUES ('".$username."','','','','','')";
ps. you are inviting SQL injections but that is a different story...
The goggles! They do nothing! The sql injection vulnerabilities! And it's only Monday!
Why not just
$query ="INSERT INTO customer VALUES ('$username', '$email', '$pass');";
$query1 = "INSERT INTO examscores VALUES ('$username', '', '', '', etc...);";
PHP will happily replace $vars inside "" quoted strings for you. There's absolutely not need for all the concatentation you're doing. Any decent code editor will still highlight the vars for you.
you are missing dots to concatenate your strings
$query1 = "INSERT INTO examscores VALUES ('".$username."','"."','"."','"."','"."','"."')";
furthermore you dont need to have different strings
and still further more you dont need to include every column if you are not inserting them
Your immediate problem causing the errors is the missing .s from query1 from between the double-doublequotes, (or you should just delete the double-doublequotes altogether. Or even the unneeded columns...).
But there are way bigger issues in your code:
SQL injection: your code is vulnerable. You should at least escape th variables coming from the user...
mysql_* deprecation: as of PHP 5.5, these functions will be deprecated. Use either Mysqli or even ebtter PDO.
I was searching for a way to insert data into two database tables in a single query in such a way that if one failed, neither saved (I don't want orphaned data). I came across a Stack Overflow question that showed me how to use BEGIN...COMMIT to accomplish this, but it simply is not working.
Here's the query I've set up:
$query = "BEGIN;
INSERT INTO content_subpages (title, url_referer) VALUES ('$pagetitle','$url_referer');
INSERT INTO ccm_main_menu (sub_item, sub_item_link,sub_item_sort_order) VALUES ('$pagetitle','$url_referer','$newsort');
COMMIT;";
mysql_query($query) or die (mysql_error());
I get the following 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 'INSERT INTO content_subpages (title, url_referer) VALUES ('TESTING','testing'); ' at line 2
This is my first time using BEGIN...COMMIT, so it's reasonable that I might be doing something wrong, but I followed the syntax of the SQL Fiddle example given by the selected answer to the Stack Overflow question I mentioned (http://stackoverflow.com/questions/12649706/mysql-insert-into-multiple-tables-in-same-query-with-begincommit), but it still won't work.
If I can easily achieve the "all-or-nothing" multiple INSERT result without BEGIN...COMMIT, that would be an acceptable solution.
Thanks in advance
Try breaking the lines into multiple php statements:
$query = "BEGIN";
mysql_query($query) or die (mysql_error());
$query = "INSERT INTO content_subpages (title, url_referer) VALUES ('$pagetitle','$url_referer')";
mysql_query($query) or die (mysql_error());
$query = "INSERT INTO ccm_main_menu (sub_item, sub_item_link,sub_item_sort_order) VALUES ('$pagetitle','$url_referer','$newsort')";
mysql_query($query) or die (mysql_error())
$query = "COMMIT";
mysql_query($query) or die (mysql_error());
you need to use multi_query instead.
http://php.net/manual/en/mysqli.multi-query.php
Make sure you're using an InnoDB table and not a MyISAM table, as MyISAM is not transactional.
To use an InnoDB table, when you create it, after the closing paren, add ENGINE=InnoDB. By default, MyISAM is used.
Try:
$dbh->beginTransaction();
$query = "INSERT INTO content_subpages (title, url_referer) VALUES ('$pagetitle','$url_referer');
INSERT INTO ccm_main_menu (sub_item, sub_item_link,sub_item_sort_order) VALUES ('$pagetitle','$url_referer','$newsort')";
$dbh->exec($query);
$dbh->commit();
Btw, Simon Germain got a good point, Transaction will work with tables using InnoDB engine.
So i have php code to insert form data in a table. Here's the code:
$link = #mysql_connect("***", "***", "****");
if (!$link) {
echo "save_failed";
return;
}
mysql_select_db("***", $link);
$sql="INSERT INTO Conference (`First Name`, `Last Name`)
VALUES ('$_POST[fname]', '$_POST[lname]')";
mysql_close($link);
The *** are replaced with the actual values in the real code, obviously. But is there anything wrong with the above code? I tried to run it, it didn't have any errors with connection but it also didn't insert anything. Here's is what my mysql table looks like:
Also, I need the table to have an auto incremented number so that each entry is unique with it's own index value. Any ideas on either problem? Thanks
You haven't executed the query, which should be done as it follows:
mysql_query($sql, $link);
Also, please consider using mysqli or even better PDO as the mysql package is deprecated (see the red box), i.e. mysql_query().