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);
Related
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;
}
I have resolved the issue. The following code now works perfectly.
Thank you all.
Please the relevant section of dbcontroller.php file as follows:
<?php
class DBController {
function runQuery2($query) {
$result = mysql_query($query);
return $result;
}
}
In addition, I have amended my original MySQL statements in my main html/php file to look like this:
<?php
session_start();
require_once("dbcontroller.php");
$db_handle = new DBController();
if(!empty($_POST["submit"])) {
if ($db_handle->runQuery2("INSERT INTO cquestionstable
(postid, ccode, nick, queries) VALUES ( 1,'cc-001', 'james', 'what
could be the problem?')") === TRUE) {
echo "New record created successfully";
} else {
echo "Error in posting question, pls try again." . "<br>";
}
?>
Thanks n cheers.
Your Code:
<?php
session_start();
require_once("dbcontroller.php");
$db_handle = new DBController();
if(!empty($_POST["submit"])) {
$sql = "INSERT INTO cquestionstable (postid, ccode, nick, queries) VALUES ( 1,'cc-001', 'james', 'what could be the problem?')";
if ($db_handle->runQuery($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $**sql . "<br>" . $db_handle->error;
}
}
?>
I see the errors already.
First if (!empty($_POST["submit"])) { should be if (isset($_POST["submit"])) {
Then you used if ($db_handle->runQuery($sql) === TRUE) { which should actually be if ($conn->query($sql) === TRUE) {
Then in your echo you used $**sql which should be $sql
Then i did not know what dbcontroller.php was but the final code should be
<?php
// session_start(); You do not need this when inserting into database
include "dbcontroller.php";
if (isset($_POST["submit"])) {
$sql = "INSERT INTO cquestionstable (postid, ccode, nick, queries) VALUES (1, 'cc-001', 'james', 'what could be the problem?')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $connn->error;
}
}
?>
dbcontroller.php
<?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);
}
?>
If you still do not understand why it is not working please look at w3Schools
Hope this is the answer you we're looking for.
im trying to do a post to a php and save in a mysql database
this is the ION.with command:
Ion.with(this)
.load("http_my_page/test.php")
.setBodyParameter("text", "não")
.asString(Charset.defaultCharset())//default=UTF-8
.setCallback(new FutureCallback<String>() {
#Override
public void onCompleted(Exception e, String result) {
}
});
my test.php page:
<?php
$test = $_POST["text"];
$servername = ...;
$username = "..";
$password = "...";
$dbname = "...";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO test (my_test) VALUES ('$test')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
and my MYSQL database has a column called my_test and collation is UTF8_unicode_ci
what im specting to store: "não"
what it really store: "não"
any reason? since im setting all the econdings =(
That was a PHP/MYSQL encoding issue and nothing related to Ion
$conn->set_charset("utf8");
I have wrote a script to update a MySql DB from a form.
After the DB has been updated I want the page to auto redirect to another page.
This has been working fine however since switching hosting provider non of my sites re-directs work.
Here is the code:
<?php
$servername = "localhost";
$username = "XXX";
$password = "XXX";
$dbname = "XXX";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$id= $_POST[id];
$dob=$_POST[dob];
$sql=("update users set dob='$dob' where id='$id'")or die('Error 23 ' . mysql_error());
if ($conn->query($sql) === TRUE) {
echo "Updated successfully<br /><br />";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
?>
<?php
header("location:index.php?action=updated"); ?>
When I run the code the DB updates but the page just displays Updated successfully?
try using javascript to redirect like below:
if ($conn->query($sql) === TRUE) {
echo "<script>
alert('Updated successfully');
window.location.href = 'index.php?action=updated';
</script>";
}
Don't echo anything and try to redirect afterwards. Instead simply redirect without any echoing.
if ($conn->query($sql) === TRUE) {
header("location:index.php?action=updated");
exit;
} else
echo "Error: " . $sql . "<br>" . $conn->error;
try this :
<?php
ob_start();
header('Location: http://www.example.com/index.php?action=updated', true);
?>
On my website, a user's background URL is stored with their data in a database. I need to get this value and store it in a variable.
However, I am having trouble doing so, the code I have right now gives me an error but doesnt tell me what the error is.
My code:
<?php
error_reporting(E_ALL);
include 'config.php';
$pin = $_COOKIE["UID"];
// Create connection
$conn = new mysqli($db_servername, $db_username, $db_password, $db_name);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$query = "SELECT * from users where pin ='$pin'";
$result = $conn->query($query);
if ($conn->query($query) === TRUE) {
$bg_url = $row[bg_url];
} else {
echo "Error: " . $query . "<br>" . $conn->error;
}
echo $bg_url;
mysqli_close($conn);
?>
$query = "SELECT * from users where pin ='$pin'";
$result = $conn->query($query);
Actually yes, the John's answer is correct, you're not using the return values properly, but you are neither accesing the variables properly, for example, I don't see where $row comes from. Try this and change it for array mode if you need to. I'm not very used to mysqli_* API, because I use PDO mostly.
if ($result) {
while($row = $result->fetch_object()) {
$bg_url = $row->bg_url;
}
} else {
echo "Error: " . $query . "<br>" . $conn->error;
}
echo $bg_url;