PHP Insert into mysql - php

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().

Related

SQL Query works well, but now when I try to use it with PHP the query fails

I am attempting to add data across multiple tables using foreign keys. I am using SQL transaction for the first time because I've read good things about it.
I have the below SQL query that works great in phpmyadmin:
BEGIN;
INSERT INTO `webInfo` (`id`, `webItem`, `webDescription`, `webText`)
VALUES(NULL,'tagheuer Watch','Watch','Watch');
INSERT INTO `valuationNotepad` (`id` ,`valuationNotepad1`, `valuationNotepad2`, `valuationNotepad3`, `valuationNotepad4`)
VALUES(LAST_INSERT_ID(),'Watch', 'Watch', 'Watch', 'Watch');
INSERT INTO stock (`id`,`listCost`,`productName`,`totalCost`,`rsp`,`rspDate`,`rspPrev1`,`rspPrev1Date`,`rspPrev2`,`rspPrev2Date`,`rspPrev3`,`rspPrev3Date`,`rspPrev4`,`rspPrev4Date`,`webID`,`valuationNotepadID`,`ringSizeID`,`addedBy`,`dateAdded`,`stockLevel`) VALUES (NULL,30000,'Tagheur Watch',3000,4000,'2020-04-15',50000,'2020-04-15',50000,'2020-04-15',60000,'2020-04-15',65000,'2020-04-15',LAST_INSERT_ID(),LAST_INSERT_ID(),2,'JD',CURRENT_TIMESTAMP,60);
COMMIT;
As said previously, this works great in phpmyadmin. However, when I try to use it with PHP and with PHP variables the query fails. The query with PHP variables is seen below.
$addStock = "BEGIN;
INSERT INTO `webInfo` (`id`, `webItem`, `webDescription`, `webText`)
VALUES(NULL,'$webItem','$webDescription','$webText');
INSERT INTO `valuationNotepad` (`id` ,`valuationNotepad1`, `valuationNotepad2`, `valuationNotepad3`, `valuationNotepad4`)
VALUES(LAST_INSERT_ID(),'$valuationNotepad1', '$valuationNotepad2', '$valuationNotepad3', '$valuationNotepad4');
INSERT INTO stock (`id`,`listCost`,`productName`,`totalCost`,`rsp`,`rspDate`,`rspPrev1`,`rspPrev1Date`,`rspPrev2`,`rspPrev2Date`,`rspPrev3`,`rspPrev3Date`,`rspPrev4`,`rspPrev4Date`,`webID`,`valuationNotepadID`,`ringSizeID`,`addedBy`,`dateAdded`,`stockLevel`) VALUES (NULL,$listCost,$productName,$totalCost,$rsp,$rspDate,$prevRSP1,$prevRSP1Date,$prevRSP2,$prevRSP2Date,$prevRSP3,$prevRSP3Date,$prevRSP4,$prevRSP4Date,LAST_INSERT_ID(),LAST_INSERT_ID(),2,'JD',CURRENT_TIMESTAMP,$stockAdded);
COMMIT;";
$stockAddedResult = mysqli_query($conn, $addStock);
I get the error check the manual that corresponds to your MySQL server version for the right syntax to use near 'INSERT INTO webInfo in my browser.
I've been trying to solve the error on the basis that it is some kind of SQL keyword error in my query, but now I am unconvinced that this is the issue.
If anyone has any thoughts on what the issue might be please let me know.
Thanks
mysqli_query does not support multiple query
You should either use mysqli_mutli_query() function or change your implementation to explicitly open a transaction , send your 3 inserts and commit it at the end or rollback if one query fails
Example :
<?php
$link = mysqli_connect("localhost", "user1", "datasoft123", "hr");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
mysqli_begin_transaction($link, MYSQLI_TRANS_START_READ_ONLY);
mysqli_query($link, "SELECT first_name, last_name FROM actor LIMIT 1");
mysqli_commit($link);
mysqli_close($link);

Inserting JSON data into MySQL table

I have been following a solution (How to insert json array into mysql database) into how to insert JSON data into a MySQL table. The code seems to run okay but it is still returning an empty data set.
I'm currently testing a hypothesis and my JSON file has 100,000 records in it. I have created a similar JSON file with just three records thinking that the size of the file may have been impeding it but that didn't work either.
I have checked my database name, table name and row names but is correct with the code shown. Any pointers?
<?php
$json = file_get_contents('E:\xampp\htdocs\MOCK_DATA.json');
$obj = json_decode($json, true);
$connection = mysqli_connect("localhost", "root", "");
mysqli_select_db($connection, "et_test") or die('Couldnt connect database');
foreach($obj as $item)
{
mysqli_query($connection, "INSERT INTO 'et_test'.'test' (first_name, last_name, colour, country, city)
VALUES ('".$item['first_name']."','".$item['last_name']."','".$item['colour']."','".$item['country']."','".$item['city']."')");
}
mysqli_close($connection);
?>
As per OP's wish to close the question and be marked as solved:
This is the problematic piece of code'et_test'.'test'
Use backticks, because using quotes around table names are the wrong identifiders:
http://dev.mysql.com/doc/refman/5.0/en/identifier-qualifiers.html
SQL
mysqli_query($connection, "INSERT INTO `et_test`.`test` ...
Use or die(mysqli_error($connection)) to mysqli_query(), in order to get the "real" error.
Consider getting into using prepared statements, or PDO with prepared statements.
As it stands, your present code is open to SQL injection.

How to insert data in two different tables of two different database in php

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

PHP MySQL INSERT not inserting nor any error is displayed

I have got this code so insert values into a table in MySQL through PHP. I have tried all the possible Insert syntax, it does not insert the data... this are the codes that i used.
$param = "xyzxyz";
$param1 = "sdfdfg";
$sql = "INSERT INTO trail (User_Name, Quiz_ID) VALUES ('".$param."','".$param1."')";
$result = $mysql->query($sql);
if($result)
echo "successful";
else
echo mysql->error;
if(mysql->errno==0)
echo "successful"
else
echo mysql->error;
I even tried the following sql syntax
"INSERT INTO trail (User_Name, Quiz_ID) VALUES ('$param1','$param1')";
"INSERT INTO `trail` (`User_Name`, `Quiz_ID`) VALUES ('$param1','$param1')";
and i tried several other none of them inserts anything into the table. and this is the table in MySQL;
trail
User_Name varchar(35)
Quiz_ID varchar(35)
It does not insert anything nor does it display any error. And I have the correct DB connection because i am able to Select from the table. Its just the insert that is tricky.
Any help would be much appreciated.
Thanks
Just a note if someone is running on similar problems:
I had a similar issue --- Insert query working on PHPMyAdmin but not working on PHP and not issuing any errors (result was true all the time).
The reason is that I was starting a transaction but forgetting to commit it...
$mysqli->autocommit(FALSE);
$mysqli->query( "START TRANSACTION" );
Never forget this:
$mysqli->commit();
It is a silly error, I know, but I was so focused on the query mistery that I forgot the transaction statements a few lines above.
Check the mysqli::$errno first.
if(mysql->errno==0)
echo "successful"
else
echo mysql->error;
What I have done is if you don't have a debugger installed, just have it email you the query. This way you can see what the final query is and if you have access to something like phpMyAdmin try manually running the query and see what happens. Another thing, make sure that you are searching for your inserted record correctly, if you are using a search query because of the number of records make sure the WHERE condition is right, that has burned me a few times.
EDIT
Missing symbol around names maybe. I have to run all my MySQL queries like
`nameOfThing`
instead of just nameOfThing
$param = "xyzxyz";
$param1 = "sdfdfg";
$sql = "INSERT INTO `trail` (`User_Name`, `Quiz_ID`) VALUES ('".$param."','".$param1."')";
$result = $mysql->query($sql);
if($result)
echo "successful";
else
echo mysql->error;
if(mysql->errno==0)
echo "successful"
else
echo mysql->error;
FYI, you are inserting $param1 twice.
You also don't have a ';' after echo "successful".
I'd suggest you clean up the code example, and try things again, and let us know.
Things to clean up
$sql = "INSERT INTO trail (User_Name, Quiz_ID) VALUES ('$param','$param1')";
You don't need to concatenate the variables in a string concatenate, you can interpolate. However, you actually should use PDO with a prepared statement to avoid the potential for SQL injection.
Add that missing ;
put that first check of if(mysql->errno==0) in (unless you are going to switch to PDO for this stuff).
Fix mysql->error to be mysql->error()
Maybe some other things from the comments.
Well, if the following code produce no error and shows 1 affected row, most likely you are looking for the result in the wrong database.
ini_set('display_errors', 1);
error_reporting(E_ALL);
$sql = "INSERT INTO trail (User_Name, Quiz_ID) VALUES ('testing','1')";
$mysql->query($sql);
var_dump($mysql->error,$mysql->affected_rows);
My tables were InnoDB tables and when i changed my tables to MyISAM the insert worked fine. Well i have never encountered this problem before. Well that did the trick for the time being.
If i want to use InnoDB engine for transactions? How can i get php to be able to insert values in InnoDB table? Any one got any suggestion? And i am using WAMP server and the MySQL is version 5.5.24. And i did change the InnoDB conf in my.ini but that did not seem to work either?
try this
$param = "xyzxyz";
$param1 = "sdfdfg";
$sql = "INSERT INTO trail (User_Name, Quiz_ID) VALUES ('".$param."','".$param1."')"; $result = $mysql_query($sql); if($result){ echo "successful";} else { echo " not successful;}

Run MySQL INSERT Query multiple times (insert values into multiple tables)

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.

Categories