MySQLi / PHP - Pulling data from one database. Inserting into another database - php

Trying to pull data out of a basic phpmyadmin database.
The code below pulls the data correctly (Commented out section verify).
I can write it to the screen and display it. (Not needed just testing)
Trying to insert it into another database however and it fails.
I've discovered that the while loops for inserting do not run. Although I can not find out why.
It's a basic localhost database (Testing right now) So the connect data is just temporary.
Any assistance is greatly appreciated
Thanks.
<?php
/*
Connect to database
*/
$webhost = 'localhost';
$webusername = 'root';
$webpassword = '';
$webdbname = 'transfertest';
$webcon = mysqli_connect($webhost, $webusername, $webpassword, $webdbname);
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
/*
*
*/
$questions = mysqli_query($webcon, "SELECT * FROM questions");
$scenarios = mysqli_query($webcon, "SELECT * FROM scenarios");
$results = mysqli_query($webcon, "SELECT * FROM results");
$employees = mysqli_query($webcon, "SELECT * FROM employees");
/*
* These while loops display the content being pulled from the database correctly.
while ($row = mysqli_fetch_array($questions)) {
echo $row['questionID'] . " : " . $row['question'] . " : " . $row['answers'];
echo "</br>";
}
while ($row = mysqli_fetch_array($scenarios)) {
echo $row['scenarioID'] . " : " . $row['scenarioTitle'] . " : " . $row['scenarioInformation'];
echo "</br>";
}
while ($row = mysqli_fetch_array($results)) {
echo $row['employeeID'] . " : " . $row['scenarioID'] . " : " . $row['questionID'] . " : " . $row['answers'] . " : " . $row['correct'];
echo "</br>";
}
while ($row = mysqli_fetch_array($employees)) {
echo $row['employeeID'] . " : " . $row['firstName'] . " : " . $row['lastName'] . " : " . $row['email'] . " : " . $row['password'];
echo "</br>";
}
*/
/* //////////////////////////////////////////////////////////////////////////
Connect to database
*/
$mobhost = 'localhost';
$mobusername = 'root';
$mobpassword = '';
$mobdbname = 'exampletransfer';
$mobcon = mysqli_connect($mobhost, $mobusername, $mobpassword, $mobdbname);
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
/*
*
*/
while ($row = mysqli_fetch_array($questions)) {
mysqli_query($mobcon, "INSERT INTO questions (questionID, question, answers) VALUES (" . $row['questionID'] . ", " . $row['question'] . ", " . $row['answers'] . ")");
}
while ($row = mysqli_fetch_array($scenarios)) {
mysqli_query($mobcon, "INSERT INTO scenarios (scenarioID, scenarioTitle, scenarioInformation) VALUES (" . $row['scenariosID'] . ", " . $row['scenarioTitle'] . ", " . $row['scenarioInformation'] . ")");
}
while ($row = mysqli_fetch_array($results)) {
mysqli_query($mobcon, "INSERT INTO results (employeeID, scenarioID, questionID, answers, correct) VALUES (" . $row['employeesID'] . ", " . $row['scenariosID'] . ", " . $row['questionID'] . ", " . $row['answers'] . ", " . $row['correct'] . ")");
}
while ($row = mysqli_fetch_array($employees)) {
mysqli_query($mobcon, "INSERT INTO employees (employeeID, firstName, lastName, email, password) VALUES (" . $row['employeesID'] . ", " . $row['firstName'] . ", " . $row['lastName'] . ", " . $row['email'] . ", " . $row['password'] . ")");
}
/*
Close Connections
*/
mysqli_close($webcon);
mysqli_close($mobcon);
/*
* Error code:
Notice: Undefined index: scenariosID on line 75
Notice: Undefined index: employeesID on line 78
Notice: Undefined index: scenariosID on line 78
Notice: Undefined index: employeesID on line 81
*/
?>

The problem is that you close your $webcon connection and then you try to read from it ^^
You try to do this... Thats not possible ;)
Prepare query mysqli_query($webcon, "SELECT * FROM questions");
Close connection <<< after that i cant read data
Read data
Try this please.
<?php
/**
* Connect to database
*/
$webhost = 'localhost';
$webusername = 'root';
$webpassword = '';
$webdbname = 'transfertest';
$webcon = mysqli_connect($webhost, $webusername, $webpassword, $webdbname);
if (mysqli_connect_errno())
{
echo 'Failed to connect to MySQL: ' . mysqli_connect_error();
}
/**
* Queries for reading
*/
$questions = mysqli_query($webcon, 'SELECT * FROM `questions`');
$scenarios = mysqli_query($webcon, 'SELECT * FROM `scenarios`');
$results = mysqli_query($webcon, 'SELECT * FROM `results`');
$employees = mysqli_query($webcon, 'SELECT * FROM `employees`');
/**
* Connect to database
*/
$mobhost = 'localhost';
$mobusername = 'root';
$mobpassword = '';
$mobdbname = 'exampletransfer';
$mobcon = mysqli_connect($mobhost, $mobusername, $mobpassword, $mobdbname);
if (mysqli_connect_errno())
{
echo 'Failed to connect to MySQL: ' . mysqli_connect_error();
}
/**
* Insert data from old database
*/
// questions
while ($row = mysqli_fetch_array($questions))
{
// escape your strings
foreach($row as $key => $val)
{
$row[$key] = mysqli_real_escape_string($mobcon, $row[$key]);
}
mysqli_query($mobcon, "INSERT INTO `questions` (`questionID`, `question`, `answers`) VALUES ('" . $row['questionID'] . "', '" . $row['question'] . "', '" . $row['answers'] . "');");
}
// scenarios
while ($row = mysqli_fetch_array($scenarios))
{
// escape your strings
foreach($row as $key => $val)
{
$row[$key] = mysqli_real_escape_string($mobcon, $row[$key]);
}
mysqli_query($mobcon, "INSERT INTO `scenarios` (`scenarioID`, `scenarioTitle`, `scenarioInformation`) VALUES ('" . $row['scenariosID'] . "', '" . $row['scenarioTitle'] . "', '" . $row['scenarioInformation'] . "');");
}
// results
while ($row = mysqli_fetch_array($results))
{
// escape your strings
foreach($row as $key => $val)
{
$row[$key] = mysqli_real_escape_string($mobcon, $row[$key]);
}
mysqli_query($mobcon, "INSERT INTO `results` (`employeeID`, `scenarioID`, `questionID`, `answers`, `correct`) VALUES ('" . $row['employeesID'] . "', '" . $row['scenariosID'] . "', '" . $row['questionID'] . "', '" . $row['answers'] . "', '" . $row['correct'] . "');");
}
// employees
while ($row = mysqli_fetch_array($employees))
{
// escape your strings
foreach($row as $key => $val)
{
$row[$key] = mysqli_real_escape_string($mobcon, $row[$key]);
}
mysqli_query($mobcon, "INSERT INTO `employees` (`employeeID`, `firstName`, `lastName`, `email`, `password`) VALUES ('" . $row['employeesID'] . "', '" . $row['firstName'] . "', '" . $row['lastName'] . "', '" . $row['email'] . "', '" . $row['password'] . "');");
}
/*
Close Connections
*/
mysqli_close($mobcon);
mysqli_close($webcon);

Pending it's on the same server and using the same username and password:
// Create a new MySQL database connection
if (!$con = mysql_connect('localhost', $username, $password)) {
die('An error occurred while connecting to the MySQL server!<br/>' . mysql_error());
}
if (!mysql_select_db($database)) {
die('An error occurred while connecting to the database!<br/>' . mysql_error());
}
// Create an array of MySQL queries to run
$sql = array(
'DROP TABLE IF EXISTS `exampletransfer.questions`;',
'CREATE TABLE `exampletransfer.questions` SELECT * FROM `transfertest.questions`'
);
// Run the MySQL queries
if (sizeof($sql) > 0) {
foreach ($sql as $query) {
if (!mysql_query($query)) {
die('A MySQL error has occurred!<br/>' . mysql_error());
}
}
}
If using MySQLi instead of MySQL:
// Create a new MySQL database connection
if (!$con = new mysqli('localhost', $username, $password, $database)) {
die('An error occurred while connecting to the MySQL server!<br/>' . $con->connect_error);
}
// Create an array of MySQL queries to run
$sql = array(
'DROP TABLE IF EXISTS `exampletransfer.questions`;',
'CREATE TABLE `exampletransfer.questions` SELECT * FROM `transfertest.questions`'
);
// Run the MySQL queries
if (sizeof($sql) > 0) {
foreach ($sql as $query) {
if (!$con->query($query)) {
die('A MySQL error has occurred!<br/>' . $con->error);
}
}
}
$con->close();

Related

Convert "INSERT" MySQL query to Postgresql query

I`m stuck for some time to fix this trouble. I followed this article https://www.sitepoint.com/creating-a-scrud-system-using-jquery-json-and-datatables/
to create SCRUD System. But I stuck when I need to add a new record to PostgreSQL.
The working MySQL part of the code is:
$db_server = 'localhost';
$db_username = 'root';
$db_password = '123456';
$db_name = 'test';
$db_connection = mysqli_connect($db_server, $db_username, $db_password, $db_name);
$query = "INSERT INTO it_companies SET ";
if (isset($_GET['rank'])) { $query .= "rank = '" . mysqli_real_escape_string($db_connection, $_GET['rank']) . "', "; }
if (isset($_GET['company_name'])) { $query .= "company_name = '" . mysqli_real_escape_string($db_connection, $_GET['company_name']) . "', "; }
if (isset($_GET['industries'])) { $query .= "industries = '" . mysqli_real_escape_string($db_connection, $_GET['industries']) . "', "; }
if (isset($_GET['revenue'])) { $query .= "revenue = '" . mysqli_real_escape_string($db_connection, $_GET['revenue']) . "', "; }
if (isset($_GET['fiscal_year'])) { $query .= "fiscal_year = '" . mysqli_real_escape_string($db_connection, $_GET['fiscal_year']) . "', "; }
if (isset($_GET['employees'])) { $query .= "employees = '" . mysqli_real_escape_string($db_connection, $_GET['employees']) . "', "; }
if (isset($_GET['market_cap'])) { $query .= "market_cap = '" . mysqli_real_escape_string($db_connection, $_GET['market_cap']) . "', "; }
if (isset($_GET['headquarters'])) { $query .= "headquarters = '" . mysqli_real_escape_string($db_connection, $_GET['headquarters']) . "'"; }
$query = mysqli_query($db_connection, $query);
I managed to write this and it fails to work for PostgreSQL:
$conn_string = "dbname=test user=postgres password=123456";
$query = "INSERT INTO it_companies VALUES ";
if (isset($_GET['rank'])) { $query .= "('" . pg_escape_string($db_connection, $_GET['rank']) . "', "; }
if (isset($_GET['company_name'])) { $query .= "'" . pg_escape_string($db_connection, $_GET['company_name']) . "', "; }
if (isset($_GET['industries'])) { $query .= "'" . pg_escape_string($db_connection, $_GET['industries']) . "', "; }
if (isset($_GET['revenue'])) { $query .= "'" . pg_escape_string($db_connection, $_GET['revenue']) . "', "; }
if (isset($_GET['fiscal_year'])) { $query .= "'" . pg_escape_string($db_connection, $_GET['fiscal_year']) . "', "; }
if (isset($_GET['employees'])) { $query .= "'" . pg_escape_string($db_connection, $_GET['employees']) . "', "; }
if (isset($_GET['market_cap'])) { $query .= "'" . pg_escape_string($db_connection, $_GET['market_cap']) . "', "; }
if (isset($_GET['headquarters'])) { $query .= "'" . pg_escape_string($db_connection, $_GET['headquarters']) . "');"; }
$query = pg_query($db_connection, $query);
The message I gets from the system is: "Add request failed: parsererror"
The Edit and remove functions are working well.
I follow to build this clause from the PGSQL site example:
INSERT INTO films VALUES
('UA502', 'Bananas', 105, '1971-07-13', 'Comedy', '82 minutes');
Any what I`m doing wrong? Thanks!
UPDATE
The echo of the query and the error was the id column. In Mysql code there was no problem with the ID colum. Why when i use pgsql it does?:
INSERT INTO it_companies (rank,company_name,industries,revenue,fiscal_year,employees,market_cap,headquarters)
VALUES ('1', 'asd', 'asd', '1', '2000', '2', '3', 'asdf');
Warning: pg_query(): Query failed: ERROR: duplicate key value violates unique constraint "it_companies_pkey" DETAIL: Key (company_id)=(2) already exists. in C:\WEB\Apache24\htdocs\datatableeditor\data.php on line 121
{"result":"error","message":"query error"
,"data":[]}
UPDATE2
The working code with one bug:
$query = "INSERT INTO it_companies (rank,company_name,industries,revenue,fiscal_year,employees,market_cap,headquarters) VALUES ";
if (isset($_GET['rank'])) { $query .= "('" . $_GET['rank'] . "', "; }
if (isset($_GET['company_name'])) { $query .= "'" . $_GET['company_name'] . "', "; }
if (isset($_GET['industries'])) { $query .= "'" . $_GET['industries'] . "', "; }
if (isset($_GET['revenue'])) { $query .= "'" . $_GET['revenue'] . "', "; }
if (isset($_GET['fiscal_year'])) { $query .= "'" . $_GET['fiscal_year'] . "', "; }
if (isset($_GET['employees'])) { $query .= "'" . $_GET['employees'] . "', "; }
if (isset($_GET['market_cap'])) { $query .= "'" . $_GET['market_cap'] . "', "; }
if (isset($_GET['headquarters'])) { $query .= "'" . $_GET['headquarters'] . "') RETURNING company_id;"; }
echo $query;
After this query, the message "Add request failed: parsererror" is still there. But after a manual refresh of the page, the new data is saved. Any idea why this message apears and not loading the data automatically?
UPDATE 3 - Success
I forgot to remove echo $query; from the code causing the error message.
All works now. Thanks for the help to all! :)
You need a little more work in your query string building.
You only add the open parenthesis ( if rank is present
You only add the closing parenthesis ) if headquarters is present.
Also you need specify what field column get which value, otherwise you end with headquarter name into the fiscal_year field. If columns are not specified the values are add it on the same order as define on the table.
INSERT INTO TABLE_NAME (column1, column2, column3,...columnN)
VALUES (value1, value2, value3,...valueN);
And as other have comment check the $query to see what you have.

Cant get table to update, delete and add with an extra code

So What Im trying to do is have the user add a code to a form, and fill the form out, A to add to the table, D to delete, U to update... The delete isnt working, neither is the insert, is it my logic? also I want to print the table only once, and sometimes it does it twice... any advice?
$Code=$_POST["Code"];
if ($Code == "A")
{
$sql = "INSERT INTO movieDATA values ('$idno', '$Name', '$Genre', '$Starring', '$Year', '$BoxOffice')";
$result= mysqli_query($link,$sql) or die(mysqli_error($link));
$showresult = mysqli_query($link,"SELECT * from movieDATA") or die("Invalid query: " . mysqli_error($link));
while ($row = mysqli_fetch_array($showresult))
{
echo ("<br> ID = ". $row["IDNO"] . "<br> NAME = " . $row["Name"] . "<br>");
echo("Genre = " . $row["Genre"] . "<br> Starring = " . $row["Starring"] . "<br>");
echo("Year = " . $row["Year"] . "<br> Box Office = " . $row["BoxOffice"] . "<br>");
}
}
elseif ($Code == "D")
{
$sql = "DELETE FROM movieDATA WHERE IDNO = '$idno'";
$result= mysqli_query($link,$sql) or die(mysqli_error($link));
$showresult = mysqli_query($link,"SELECT * from movieDATA") or die("Invalid query: " . mysqli_error($link));
while ($row = mysqli_fetch_array($showresult))
{
echo ("<br> ID = ". $row["IDNO"] . "<br> NAME = " . $row["Name"] . "<br>");
echo("Genre = " . $row["Genre"] . "<br> Starring = " . $row["Starring"] . "<br>");
echo("Year = " . $row["Year"] . "<br> Box Office = " . $row["BoxOffice"] . "<br>");
}
}
elseif ($Code == "U")
{
$sql = "UPDATE movieDATA SET Name = '$Name', Genre = '$Genre', Starring = '$Starring', Year = '$Year', BoxOffice = '$BoxOffice' where IDNO = '$idno'";
$result= mysqli_query($link,$sql) or die(mysqli_error($link));
$showresult = mysqli_query($link,"SELECT * from movieDATA") or die("Invalid query: " . mysqli_error($link));
while ($row = mysqli_fetch_array($showresult))
{
echo ("<br> ID = ". $row["IDNO"] . "<br> NAME = " . $row["Name"] . "<br>");
echo("Genre = " . $row["Genre"] . "<br> Starring = " . $row["Starring"] . "<br>");
echo("Year = " . $row["Year"] . "<br> Box Office = " . $row["BoxOffice"] . "<br>");
}
}
?>

mysqli::query(): Couldn't fetch mysqli after first line of foreach loop

I have created a foreach loop to add data to a MySQL database and I am receiving the error "mysqli::query(): Couldn't fetch mysqli" after the first line has been added to the database.
PHP DB CONNECTION
$db = new mysqli($db_hostname, $db_username, $db_password, $db_database);
if ($db->connect_error) {
die("Connection failed: " . $db->connect_error);
}
I then have another chunk of script which collects the data I require. The data is then added to the foreach insert loop
PHP FOREACH
foreach($RSS_DOC->channel->item as $RSSitem)
{
$item_id = md5($RSSitem->title);
$fetch_date = date("Y-m-j G:i:s");
$item_title = $RSSitem->title;
$item_date = date("Y-m-j G:i:s", strtotime($RSSitem->pubDate));
$item_url = $RSSitem->link;
echo "Processing item '" , $item_id , "' on " , $fetch_date , "<br/>";
echo $item_title, " - ";
echo $item_date, "<br/>";
echo $item_url, "<br/>";
$sql = "INSERT INTO rssingest (item_id, feed_url, item_title, item_date, item_url, fetch_date)
VALUES ('" . $item_id . "', '" . $feed_url . "', '" . $item_title . "', '" . $item_date . "', '" . $item_url . "', '" . $fetch_date . "')";
if ($db->query($sql) === TRUE) { // <- THIS IS LINE 170
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $db->error;
}
$db->close();
}
The first line is added to the database without a problem. The second line and every line after that one returns "mysqli::query(): Couldn't fetch mysqli on line 170".
Any ideas where I may be going wrong?
The problem may be the $db->close() inside the loop. Try closing the database after the loop.
foreach($RSS_DOC->channel->item as $RSSitem)
{
$item_id = md5($RSSitem->title);
$fetch_date = date("Y-m-j G:i:s");
$item_title = $RSSitem->title;
$item_date = date("Y-m-j G:i:s", strtotime($RSSitem->pubDate));
$item_url = $RSSitem->link;
echo "Processing item '" , $item_id , "' on " , $fetch_date , "<br/>";
echo $item_title, " - ";
echo $item_date, "<br/>";
echo $item_url, "<br/>";
$sql = "INSERT INTO rssingest (item_id, feed_url, item_title, item_date, item_url, fetch_date)
VALUES ('" . $item_id . "', '" . $feed_url . "', '" . $item_title . "', '" . $item_date . "', '" . $item_url . "', '" . $fetch_date . "')";
if ($db->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $db->error;
}
}
$db->close();

Variable not recognised in INSERT but working in SELECT

Basically I am using the variable $shopid to recognise which shop has been chosen. I am now trying to create a comment system to enable each shop page to be commented on. My SELECT query is recognising $shopid and enabling me to use it, when I try to use the same variable in my INSERT, it simply posts 0.
<?php
database connection
session_start();
if (isset($_SESSION['logged'])){
$s_userID = $_SESSION['userID'];
$shopid = $_GET['page_id'];
$str_shops = '';
//bring shop data
mysqli_select_db($db_server, $db_database);
$query = "SELECT * FROM shops WHERE shopID = '$shopid'";
$result = mysqli_query($db_server, $query);
if (!$result) die("Database access failed: " . mysqli_error($db_server));
while($row = mysqli_fetch_array($result)){
$str_shops .= "<div class='result'><strong>" .
$row['image1'] . "<br><br>" .
$row['name'] . "</strong><br><br>" .
$row['address'] . "<br><br>" .
$row['website'] . "<br><br>" .
$row['openinghours'] . "<br><div class='justifytext'>" .
$row['more'] . "<br><br></div><strong>What do they sell?</strong><br><br><div class='justifytext'>" .
$row['sold'] . "<br><br></div></div>";
}
//post comment
mysqli_select_db($db_server, $db_database);
$comment = $_POST['comment'];
if ($comment != '') {
$query = "INSERT INTO comments (userID,shopID,comment) VALUES ('$s_userID', '$shopid', '$comment')";
mysqli_query($db_server, $query) or
die("Insert failed: " . mysqli_error($db_server));
$commentmessage = "Thanks for your comment!";
}
mysqli_select_db($db_server, $db_database);
$query = "SELECT * FROM comments";
$result = mysqli_query($db_server, $query);
if (!$result) die("Database access failed: " . mysqli_error($db_server)); $i = 0;
while($row = mysqli_fetch_array($result)){ $i++;
$str_comments.= "<p><div id='displaycomments'>" . $row['username']. ", " .
$row['commdate'] . ": <br>" .
$row['comment'] . "</div>";
}
}
echo $str_shops;
echo $commentmessage;
echo $str_comments;
mysqli_close($db_server);
?>
Can anyone see why this isn't working? I'm not getting an error, it is simply adding 0 to the shopID column in my table.
My guess would be that your shopID column would be of INT datatype and you are passing a string to it in your insert statement, thats why 0 is being stored.Try again by removing the single quotes around $shopid, like this-
INSERT INTO comments (userID,shopID,comment) VALUES ('$s_userID', $shopid, '$comment')"
^^^^^^^ remove the single quotes

PHP json_encode() in while loop

I am trying to use json_encode() in a while loop while getting database results. Here is my code:
<?
$database = sqlite_open("thenew.db", 0999, $error);
if(!$database) die($error);
$query = "SELECT * FROM users";
$results = sqlite_query($database, $query);
if(!$results) die("Canot execute query");
while($row = sqlite_fetch_array($results)) {
$data = $row['uid'] . " " . $row['username'] . " " . $row['xPos'] . " " . $row['yPos'];
}
echo json_encode(array("response"=>$data));
sqlite_close($database);
?>
The output of this is
{"response":"lastUserID lastUser lastXPos lastYPos"}
I want it to be...
{"response":["1 Alex 10 12", "2 Fred 27 59", "3 Tom 47 19"]}
etc.
So I want the json_encode() function to put ALL users into the array rather than the last one. How would I do this? Thanks
Try:
<?
$database = sqlite_open("thenew.db", 0999, $error);
if(!$database) die($error);
$query = "SELECT * FROM users";
$results = sqlite_query($database, $query);
if(!$results) die("Canot execute query");
$data = array();
while($row = sqlite_fetch_array($results)) {
$data[] = $row['uid'] . " " . $row['username'] . " " . $row['xPos'] . " " . $row['yPos'];
}
echo json_encode(array("response"=>$data));
sqlite_close($database);
?>
Change this
while($row = sqlite_fetch_array($results)) {
$data = $row['uid'] . " " . $row['username'] . " " . $row['xPos'] . " " . $row['yPos'];
}
to
$data = array();
while($row = sqlite_fetch_array($results)) {
$data[] = $row['uid'] . " " . $row['username'] . " " . $row['xPos'] . " " . $row['yPos'];
}
Push each user to an array:
$data = array();
while($row = sqlite_fetch_array($results)) {
$data[] = $row['uid'] . " " . $row['username'] . " " . $row['xPos'] . " " . $row['yPos'];
}
echo json_encode(array("response"=>$data));

Categories