Inserting multiple rows into database through a link - php

I am quite new in php and mysql.
I was trying to insert multiple (unknown ) number of rows into mysql database. The data is posted into the table through a link -
http://localhost:81/logdata.php?CtrlID=3842&DateTime=2017-05-18+11%3A45%3A23&Bat=50.2&LVSD=1&Indt=29.4&Outdt=32.8&submit
The following code works perfect as long as a single row is posted. But I have no idea how to insert several rows together and how
the link should look like. Actually rows containing data are formed and stored in a Microcontroller.
I am sending the data with the help of GPRS. The controller successfully sending one row at a time, the data is correctly recorded in
mysql database. But I am struggling to send several rows together. I would highly appreciate any suggestion.
<?php
$servername = "localhost";
$username = "root";
$password = ""; //your pwd
$dbname = "mirzu";
// Create connection
$conn = new mysqli($servername, $username, $password,$dbname);
if($conn){
echo 'Successfully Connected database.';
}
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
//if(isset($_GET['submit'])){ //
$ID = $_GET['CtrlID'];
$DateTime = $_GET['DateTime'];
$battery = $_GET['Bat'];
$LVSD = $_GET['LVSD'];
$IndoorT = $_GET['Indt'];
$OutdoorT = $_GET['Outdt'];
$totalCtrlID = sizeof($ID);
for($i=0;$i<$totalCtrlID;$i++) {
$InsCtrlID = [$ID][$i];
$InsDateTime = [$DateTime][$i];
$Insbattery = [$battery][$i];
$InsLVSD = [$LVSD][$i];
$InsIndoorT = [$IndoorT][$i];
$InsOutdoorT = [$OutdoorT][$i];
$query = "INSERT INTO btsdata (CtrlID,DateTime,Batt,LVSD,IndT,OutdT)".
"VALUES ('$InsCtrlID','$InsDateTime','$Insbattery','$InsLVSD','$InsIndoorT','$InsOutdoorT');";
}
if (mysqli_query($conn, $query)) {
echo "New record created successfully into database";
} else {
echo "Error: " . $query . "<br>" . mysqli_error($conn);
}
//}
mysqli_close($conn);
?>

Two records the query will become:
INSERT INTO TABLE (column1, column2) VALUES ('data', 'data'), ('data', 'data')
Same as a more than two record.
INSERT INTO tbl_name
(a,b,c)
VALUES
(1,2,3),
(4,5,6),
(7,8,9);

Related

How to execute multiple mySQL queries in one PHP script

Currently, I have the following structure in my PHP script, I would like one query to execute and if successful the next one should execute.
The following is my current code, but how can I add a simple
conditional that would allow the second query to execute after the
delete query?
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "dbname";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "DELETE FROM Table1" ;
$sql = " INSERT INTO Table1 (tbcolm, , tbcolm2, tbcolm3)
SELECT `column1`, `column2`,`column3` FROM Table3 ";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
You can use mysqli multi_query, as stated in PHP Manual:
https://secure.php.net/manual/en/mysqli.quickstart.multiple-statement.php
Be sure to add a ; at the end of your strings, and use the concatenating assignment operator (.=) on the second $sql variable.
It should look like this:
$sql = "DELETE FROM Table1;";
$sql .= "INSERT INTO Table1 (tbcolm, , tbcolm2, tbcolm3)
SELECT 'column1', 'column2','column3' FROM Table3;";
if ($mysqli->multi_query($sql)) {
/* success code here */
}
If the first argument fails, the next one won't be queried, as stated in:
https://www.php.net/manual/en/mysqli.multi-query.php

Only first entry from loop being entered into MySQL table

I am trying to insert data into a MySQL table using information from a form. For some reason, only the first entry is being inserted into the table.
How can I resolve this issue? Thanks
MySQL table screenshot
....
// Create connection
$conn = mysqli_connect($servername, $username, $password, $database);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
if(isset($_POST['submit'])){
$makeArr = $_POST['make'];
$modelArr = $_POST['model'];
$yearArr = $_POST['year'];
$regoArr = $_POST['rego'];
if(!empty($makeArr)){
for($i = 0; $i < count($makeArr); $i++){
if(!empty($makeArr[$i])){
$make = $makeArr[$i];
$model = $modelArr[$i];
$year = $yearArr[$i];
$rego = $regoArr[$i];
//database insert query goes here
$sql = "INSERT INTO test (`make`, `model`, `year`, `rego`) VALUES ('$make', '$model', '$year', '$rego')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
}
}
}
You are closing $conn within your for loop. You should take it and put it outside the for loop.
$conn->close() will close the sql connection.
This means it can't be used again.

Php to MySQL database

I have problem with MySQL database, I can't insert the information into the table. My php code seems to work, but when I run it nothing happens.
<?php
$servername = "localhost";
$fname = "fname";
$lname = "lname";
$klas = "klas";
$nomer = "nomer";
$file = "dom";
$dbname = "homeworks";
$conn = new mysqli($servername, $fname, $lname,$klas,$file,$dbname);
$sql = "INSERT INTO student (fname, lname,klas,file)
VALUES ($servername, $fname, $lname,$klas,$file,)";
?>
You have three main problems in your code:
You're still not connected to the database
Only constructing and not executing
Having not matched parameters in the insert values
Solution :
1. Make a connection first
$conn = new mysqli($servername, $username, $password, $dbname);
The Parameter $servername, $username, $password, $dbname is obviously your hostname, Database Username, Password and the Database name
You should not have your table name or column names in the connection parameters
2. Construct the parameters which matches the coloumn name and variables correctly
$sql = "INSERT INTO student (fname, lname,klas,file)
VALUES ($fname, $lname,$klas,$file)";
3. Execute Your Query :
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
Note :
Also it's good practice to close your connection once you are done
$conn->close();
So, you should be having something like this
<?php
$servername = "localhost";
$username = "YourDBUsername";
$password = "YourDBPassword";
$fname = "fname";
$lname = "lname";
$klas = "klas";
$nomer = "nomer";
$file = "dom";
$dbname = "homeworks"; //Hope you will have your db name here
$conn = new mysqli($servername, $username, $password, $dbname);
$sql = "
INSERT INTO student (fname, lname,klas,file) VALUES
('$fname'
,'$lname'
,'$klas'
,'$file');
";
if ($conn->query($sql) === TRUE) {
echo "New record inserted successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
Advice :
Always use prepared statements else clean your inputs before you insert.
Your connection should look something like this. link
<?php
//change the data into your connection data
$conn = mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
You made your query but didn't execute it.
if (mysqli_query($conn, $sql)) {
echo 'records created successfully<br>';
} else {
echo $sql . '"<br>"' . mysqli_error($conn);
}

HTTP Post to MySQL inserting Blank Rows

I'm trying to setup a post string to enter data directly into the database from a remote system.
Post string example: http://www.domainname.com/insert.php?Phone=07000888888
This returns my expected success message however when I check the database the phone field is blank.
My PHP insert script looks like:
<?php
$servername = "localhost";
$username = "XXXX";
$password = "XXXX";
$dbname = "Client1";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$phone = mysql_real_escape_string($_POST['phone']);
$sql = "INSERT INTO LiveFeed (phone)
VALUES ('$_POST[Phone]')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
Can anyone figure out why it's inserting a blank row with this?
There are a few problems with the code that as a server admin make me slightly uncomfortable. Hopefully we can fix that and your problem at the same time.
This is what I picked up on.
(I have removed empty lines for brevity)
<?php
// ...
$phone = mysql_real_escape_string($_POST['phone']);
$sql = "INSERT INTO LiveFeed (phone)
VALUES ('$_POST[Phone]')";
// ...
The first thing is you are correctly escaping the string and then not using the escaped string
<?php
// ...
$phone = mysql_real_escape_string($_POST['phone']);
$sql = "INSERT INTO LiveFeed (phone)
VALUES ('$phone')";
// ...
However you never inspect the value to see if you have anything.
<?php
// ...
if(isset($_POST['phone'])){
$phone = mysql_real_escape_string($_POST['phone']);
$sql = "INSERT INTO LiveFeed (phone)
VALUES ('$phone')";
// ...
}else{
echo '<p><b>Error:</b> "Phone" not given.</p>';
exit(0); // stop and do no more
}
// ...
Finally (just in case): If you are sending the data this way http://example.com/example.php?phone=123456789 that is $_GET.
<?php
// ...
if(isset($_GET['phone'])){
$phone = mysql_real_escape_string($_GET['phone']);
$sql = "INSERT INTO LiveFeed (phone)
VALUES ('$phone')";
// ...
}
// ...
One way or another you should now have safe, clean and functional code that does not add empty rows and cannot so readily be abused.
You code should be like this
<?php
$servername = "localhost";
$username = "XXXX";
$password = "XXXX";
$dbname = "Client1";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$phone = mysqli_real_escape_string($conn, $_GET['phone']);
$sql = "INSERT INTO LiveFeed (phone)
VALUES ('".$phone."')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
Without seeing your form, which would help I am assuming you are using GET not POST.
So you need to get your values with GET not POST if the following is the result of the form submission:
http://www.domainname.com/insert.php?Phone=07000888888
change:
$phone = mysql_real_escape_string($_POST['phone']);
$sql = "INSERT INTO LiveFeed (phone) VALUES ('$_POST[Phone]')";
to
$phone = mysql_real_escape_string($_GET['Phone']);
$sql = "INSERT INTO LiveFeed (phone) VALUES ('$phone')";
Additionally for some extra input validation you could do something like:
$phone = mysql_real_escape_string($_GET['Phone']);
if(!ctype_digit($phone)){
echo "Incorrect Phone Number format";
}
$sql = "INSERT INTO LiveFeed (phone) VALUES ('$phone')";
That would make sure the phone number only has numbers in it (if that is indeed what you want and don't have +445498390 type numbers)
I finally figured it out.
The code itself was fine, it was the post string URL had an uppercase P in Phone.
once I changed it to phone it's now started working properly.
Thanks for all the help.
I was having this issue and it no matter what filtering I tried in PHP I could not stop the blank line from being inserted into my database records. What finally fixed the issue for me was adding .trim(); to my javascript variable. Hopefully, this will help someone else having similar issue!

Simple insert into database doesn't work

I have a very simple bit of code to insert data into database.
It doesn't work. I do not get any error except cannot insert. I could connect to the database so that is not the issue.
The database has 3 fields, emailadd is the 2nd field. The other 2 are auto increment id and creation date, so also a field that on add, it will add current timestamp.
$inquiry = "INSERT INTO subscribe (emailadd) VALUES ('$myemail')";
$res = mysql_query($inquiry) or die("cannot insert");
$inquiry = "INSERT INTO `subscribe` (`emailadd`) VALUES ('$myemail')";
$res = mysql_query($inquiry,$con) or die('Not Inserted : ' . mysql_error());
Some time we need $con variable to identify the database connection, let see more check here
the mysql_query is deprecated, you need to use mysqli like so :
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "UPDATE MyGuests SET lastname='Doe' WHERE id=2";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
$conn->close();
?>

Categories