How to insert multiple XML prices into SQL table with PHP - 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;
}

Related

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.

Deleting a data in Database using php

I need to delete a data on database by using PHP code, i have written the code but there is some error message.
here is the php code(del.php):-
<!DOCTYPE html>
<html>
<body>
<?php
$conn = mysql_connect('localhost', 'root','');
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "DELETE FROM register WHERE name='' ";
if ($conn->query($sql) === TRUE)
{
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . $conn->error;
}
$conn->close();
?>
</body>
</html>
The database name is 'selva' and the table name is 'register', in database the file names are "Name,Email,Contact,Address", i need to delete the name or email or contact . how to delete!!
//this will delete the whole row:
<!DOCTYPE html>
<html>
<body>
<?php
$servername = "localhost";
$username = "root";
$password = "your_password"; // add your pw from the here
$dbname = "selva";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//this will delete the whole row
$sql = "DELETE FROM register WHERE 1 ";
if ($conn->query($sql) === TRUE)
{
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . $conn->error;
}
$conn->close();
?>
</body>
</html>
//this will delete only the COLUMNS you set here:
<!DOCTYPE html>
<html>
<body>
<?php
$servername = "localhost";
$username = "root";
$password = "your_password"; // add your pw from the here
$dbname = "selva";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "ALTER TABLE register DROP Name, DROP Email; DROP Contact; ";
if ($conn->query($sql) === TRUE)
{
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . $conn->error;
}
$conn->close();
?>
</body>
</html>
hope it will help you :)

Why is my PHP / SQL generating duplicate database entries?

I'm quite new to PHP and an absolute beginner when it comes to SQL. I'm just learning the basics and I can't get my head around why my code is generating a duplicate entry every time the form is submitted, e.g.
Name: Joe Blogs Email: info#email.co.uk
Name: Joe Blogs Email: info#email.co.uk
The database has a table called user and two columns, name and email.
My index file looks like this, it has a simple form for name and email, and inserts the data on submit:
<form method="post" action="insert.php">
<input name="name" type="text">
<input name="email" type="email">
<input type="submit" value="Submit Form">
</form>
<?php
$servername = "localhost";
$username = "DB_USER";
$password = "PASSWORD";
$dbname = "DB_NAME";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sqlout = "SELECT name, email FROM user";
$result = $conn->query($sqlout);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<b>Name:</b> " . $row["name"]. " <b>Email:</b> " . $row["email"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
<form method="post" action="wipe.php">
<input type="submit" value="Wipe ALL Data">
</form>
This insert.php file is called when the form is submitted:
<?php
$servername = "localhost";
$username = "DB_USER";
$password = "PASSWORD";
$dbname = "DB_NAME";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO user ( name, email ) VALUES ( '{$conn->real_escape_string($_POST['name'])}', '{$conn->real_escape_string($_POST['email'])}' )";
$insert = $conn->query($sql);
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Back
I've probably made some basic mistakes but I'm not sure why it is adding duplicates. Is it something to do with connecting twice to the database in each file? Is there a better way to connect only once? Or is it caused by the form submission itself?
Because you call query twice:
$insert = $conn->query($sql);
if ($conn->query($sql) === TRUE) {
You should rewrite is as
$insert = $conn->query($sql);
if ($insert === TRUE) {
Also, you should really be using prepared statements.
Your code Call $conn->query twice
$insert = $conn->query($sql);// first time
if ($conn->query($sql) === TRUE) {// second time
if ($insert === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
You need change:
$sql = "INSERT INTO user ( name, email ) VALUES ( '{$conn->real_escape_string($_POST['name'])}', '{$conn->real_escape_string($_POST['email'])}' )";
$insert = $conn->query($sql);
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
to
$sql = "INSERT INTO user ( name, email ) VALUES ( '{$conn->real_escape_string($_POST['name'])}', '{$conn->real_escape_string($_POST['email'])}' )";
$status = $conn->query($sql);
if ($status === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}

PHP MySQL database insert issue

I am building a MySQL database using PHP to bring in JSON data from the NYTimes API. I have it all built and have included the script below but for some reason when I go to insert the records into the database, it doesn't seem to complete the insert function all the way through or actually insert the records into the database and I am really confused why. Any insight as to why this is happening or how to adjust it would be greatly appreciated.
MakeDatabase.php-
<?php
function PullData($url,$adx_keywords,$title,$abstract)
{
$json = file_get_contents("http://api.nytimes.com/svc/mostpopular/v2/mostviewed/arts,sports/30.json?api-key=1a8bc0eb977b14db91dea9318942608b%3A14%3A72549166");
$json_decoded= json_decode($json,true);
foreach ($json_decoded['results'] as $articles){
array_push($url,$articles['url']);
array_push($adx_keywords,$articles['adx_keywords']);
array_push($title,$articles['title']);
array_push($abstract,$articles['abstract']);
}
}
function MakeDatabase($conn,$db_NAME)
{
// Create database
$sql_createDB = "CREATE DATABASE IF NOT EXISTS " . $db_NAME;
if ($conn->query($sql_createDB) === TRUE) {
echo "Database linked successfully <br>";
} else {
echo "Error creating database: " . $conn->error;
}
}
function createTable($tablename, $db_NAME, $conn, $fields)
{
mysqli_select_db($conn, $db_NAME);
$sql_create = "CREATE TABLE IF NOT EXISTS $tablename (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
$fields[0] TEXT,
$fields[1] TEXT,
$fields[2] TEXT,
$fields[3] TEXT
)";
if ($conn->query($sql_create) === TRUE) {
echo "Table Articles created successfully <br>";
} else {
echo "Error creating table: " . $conn->error . "<br>";
}
}
function insertRecords($array,$fieldname, $conn, $db_NAME)
{
mysqli_select_db($conn, $db_NAME);
foreach ($array as $records)
{
$sql_insert="INSERT INTO tbl_articles('$fieldname')"
. "VALUES('$records')";
echo $sql_insert . "<br>";
if(mysqli_query($conn, $sql_insert))
{
echo "Records Inserted.";
}
else
{
die('Error : ' . mysqli_error($conn) . "<br>");
}
}
}
?>
index.php-
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<?php
require 'MakeDatabase.php';
$db_NAME="nytimesnews";
$tblName="tbl_articles";
$fields=array('url','adx_keywords','title','abstract');
$servername = "localhost";
$username = "root";
$password = "";
$url=array();
$adx_keywords=array();
$title=array();
$abstract=array();
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
MakeDatabase($conn,$db_NAME);
PullData($url,$adx_keywords,$title,$abstract);
createTable($tblName, $db_NAME, $conn, $fields);
insertRecords($url, 'url', $conn, $db_NAME);
insertRecords($adx_keywords, 'keywords', $conn, $db_NAME);
$conn->close();
?>
</body>
</html>
I'm not sure if this will fix the issue, however there is an error in your insert query.
Your query,
$sql_insert="INSERT INTO tbl_articles('$fieldname')" . "VALUES('$records')";
What it should be,
$sql_insert = "INSERT INTO `tbl_articles` (`" . $fieldname . "`) VALUES ('" . $records . "')";
I reformatted it too to make it clearer.
Also, turn on error reporting if it is not on alreasdy to make debugging easier for you and us, that way you know what errors are being thrown and can either fix them or tell us so we know where abouts in the code it is going wrong.
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(-1);

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

Categories