Only first entry from loop being entered into MySQL table - php

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.

Related

Inserting multiple rows into database through a link

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);

How to insert multiple XML prices into SQL table with PHP

I've been trying to find the answer to the following question, but can't seem to find the solution. I've been able to insert one product price in my SQL table, but all the possibilities I try for multiple products aren't working. This is my working code for one product.
<html>
<head>
<meta charset="UTF-8">
<title>Test</title>
</head>
<body>
<?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);
}
$xml=simplexml_load_file("URL") or die("Error: Cannot create object");
foreach ($xml->product as $row) {
$price = $row -> price;
$sql = "INSERT INTO `tablename` (`price`)
VALUES ('$price')";
}
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
</body>
</html>
What should I add or change to make the query go through the whole XML file and look for all the prices of the products?
Thanks in advance!
You can do it with mysqli::multi_query. Only put the semicolon at end of sql and execute with multi_query:
$sql = "";
foreach ($xml->product as $row) {
$price = $row -> price;
$sql .= "INSERT INTO `product` (`price`)
VALUES ('$price');";
}
if ($conn->multi_query($sql) === TRUE) {
echo "News records created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}

php- get last insert id

I know this question has been answered many times. I tried a few of the solutions from here but nothing worked. I'm not using any PHP framework.
I have an insert operation taking place and I want to get the id of the inserted row.
Here's my code:
$qry="INSERT INTO tablename(content) VALUES('".$content."')";
setData($qry);
setData() is a user defined function which does insert operation.
//for data submit
function setData($qry)
{
$obj=new DBCon();
$res=$obj->submitQuery($qry);
return $res;
}
//fetches result
function getData($qry)
{
$obj=new DBCon();
$res=$obj->selectQuery($qry);
return $res;
}
This is the class I made for establishing database connectivity:
class DBCon
{
private function getConnection()
{
// hostname, username, password, database
$con=mysqli_connect("localhost","root","","dbname")OR die('Could not Connect the Database');
return $con;
}
public function closeCon()
{
mysqli_close($con);
}
public function submitQuery($qry)
{
$result=0;
$con=$this->getConnection();
$result=mysqli_query($con,$qry);
return $result;
}
public function selectQuery($qry)
{
$con=$this->getConnection();
$res=mysqli_query($con,$qry);
return $res;
}
}
To obtain the last inserted id, I wrote the following query but it did not yield any result:
SELECT LAST_INSERT_ID() FROM tablename
Is there any other method to get this?
LAST_INSERT_ID() only returns values that have been auto-generated by the MySQL server for an AUTO_INCREMENT column; when you insert a specific value, no auto-generation takes place and no value will be returned by LAST_INSERT_ID().
Try : $con->insert_id;
Try This way.
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('First Name', 'Last Name', 'first#example.com')";
if ($conn->query($sql) === TRUE) {
$last_id = $conn->insert_id;
echo "New record created successfully. Last inserted ID is: " . $last_id;
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
MySQLi Object-oriented
<?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 = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john#example.com')";
if ($conn->query($sql) === TRUE) {
$last_id = $conn->insert_id;
echo "New record created successfully. Last inserted ID is: " . $last_id;
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
MySQLi Procedural
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john#example.com')";
if (mysqli_query($conn, $sql)) {
$last_id = mysqli_insert_id($conn);
echo "New record created successfully. Last inserted ID is: " . $last_id;
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
PDO
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john#example.com')";
// use exec() because no results are returned
$conn->exec($sql);
$last_id = $conn->lastInsertId();
echo "New record created successfully. Last inserted ID is: " . $last_id;
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
$last_id = $conn->insert_id;

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);
}

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