Adding XML to a column with MySQL LOAD_FILE() - php

I want to load an xml file into a table column with MySQL. How do I do this with an INSERT statement instead of an UPDATE statement?
This code does an INSERT to create a new row, gets the id for the last inserted row, then attempts to do the update to load the xml file. But it doesn't update the row with the xml info.
I would like to know what to fix to put the xml in the database column. I also want to streamline the code and do the LOAD_FILE in one INSERT statement.
MySQL database table structure
Field Datatype Attributes Extra
userid INT(6) unsigned auto_increment
user_events LONGTEXT
PHP code to add xml file
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
$con = mysql_connect("hostname","adminuser","adminpassword");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("test_db", $con);
$qinsert = "INSERT INTO load_xml (`user_events`) VALUES ('user events')";
$result_insert = mysql_query($qinsert);
$qtext = "SELECT * FROM load_xml";
$result = mysql_query($qtext);
$numrows = mysql_num_rows ( $result );
while ($row = mysql_fetch_row($result)) {
echo 'user id '.$row[0].' user_events '.$row[1].'<br/>';
}
$insert_id = "SELECT LAST_INSERT_ID()";
$rin_id = mysql_query($insert_id);
$row = mysql_fetch_row($rin_id);
$userid = $row[0];
echo 'last added id '.$userid.'<br/>';
$update_xml = "UPDATE load_xml SET user_events=LOAD_FILE('my_events.xml') WHERE userid='$userid'";
$result_update = mysql_query($update_xml);
$qtext = "SELECT * FROM load_xml";
$result = mysql_query($qtext);
$numrows = mysql_num_rows ( $result );
echo $numrows.'<br/>';
while ($row = mysql_fetch_row($result)) {
echo 'user_id '.$row[0].' user_events '.$row[1].'<br/>';
}
mysql_close($con);
?>

Just add the file in the original insert. The file path is that of a file on the server. The mysql user used to connect must have the file privilege. It must be the full path. On windows you need to replace back slashes with forward slashes -
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
$con = mysql_connect("hostname","adminuser","adminpassword");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("test_db", $con);
$qinsert = "INSERT INTO load_xml (`user_events`) VALUES (LOAD_FILE('/full/path/to/my_events.xml'))";
$result_insert = mysql_query($qinsert);
$userid = mysql_insert_id();
echo 'last added id '.$userid.'<br/>';
$qtext = "SELECT * FROM load_xml";
$result = mysql_query($qtext);
$numrows = mysql_num_rows ( $result );
while ($row = mysql_fetch_row($result)) {
echo 'user id '.$row[0].' user_events '.$row[1].'<br/>';
}
mysql_close($con);
?>
UPDATE - here is another version using PDO prepared statement and file_get_contents() -
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
$db = new PDO('mysql:dbname=test_db;host=hostname', 'adminuser', 'adminpassword');
$qinsert = "INSERT INTO load_xml (`user_events`) VALUES (?)";
$stmt = $db->prepare($qinsert);
$stmt->execute(array(file_get_contents('my_events.xml')));
?>

Related

How can I get the UserID of a person from a split version of their First/Last Name from FullName in PHP?

I'm trying to make a Check-in/out system.
So far I have a dropdown that get the list of active events.
<select name="events">
<?php
$conn = new mysqli('localhost:3306', 'user', 'pw', 'database') or die ('Cannot connect to db');
$eveny = $conn->query("select event_title from events_event where inactive=0");
while ($row=mysqli_fetch_array($eveny)) {
unset($event);
$event = $row['event_title'];
echo '<option value="'.$event.'">'.$event.'</option>';
}
?>
</select>
And a textbox that searches users based on first name, but it auto displays results (like a Google search) and then fills out the info with both First Name and Last name. Source.
The only change in the php is the echo to show both first and last names as follows:
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
echo "<p>" . $row["per_FirstName"] . " " . $row["per_LastName"] . "</p>";
}
NOW FOR THE PROBLEM
I have made the frontend into a form, and a submit button using method="post".
But something in my php is not functioning/lacking.
<?php
$db = new mysqli('localhost:3306', 'user', 'pw', 'database') or die ('Cannot connect to db');
session_start();
if($_SERVER["REQUEST_METHOD"] == "POST") {
$myname = mysqli_real_escape_string($db,$_POST['fullname']);
$eventy = mysqli_real_escape_string($db,$_POST['events']);
//$checktime = mysqli_real_escape_string($db,date("Y-m-d H:i:s"));
$evid = "SELECT event_id from events_event where event_title = '$eventy'";
$revvy = mysqli_query($db,$evid);
$nameParts = explode(' ', $myname);
$firstName = trim($nameParts[0]);
$lastName = trim($nameParts[1]);
$sql = "SELECT per_ID FROM person_per WHERE per_FirstName = '$firstName' AND per_LastName = '$lastName'";
$result = mysqli_query($db,$sql);
//$row = mysqli_fetch_row($result);
//$result = $result->fetch_all();
while($row = mysqli_fetch_assoc($result)){
$perID = $row['per_ID'];
}
while($row2 = mysqli_fetch_assoc($revvy)){
$evvy = $row['event_ID'];
}
$count = mysqli_num_rows($result);
// table row must be 1 row if it succeeded
if($count == 1) {
//session_register("myname");
//$_SESSION['login_user'] = $myname;
$checkin = "insert into event_attend (attend_id, event_id, person_id, checkin_date) values (DEFAULT, '$evvy', '$perID', now())" or die(mysqli_error());;
mysqli_query($db,$checkin);
header("location: checkedin.php");
}else {
$error = "An error occurred.";
}
}
?>
The $myname, is the result of both first name and last name, I need just First Name based on the filled out text field which uses both first and last names.
I also can't get the Event_ID from the dropdown.
If user's first and last name are separated by space:
$nameParts = explode(' ', $myname);
$firstName = trim($nameParts[0]);

Php mysql insert/update from json

hello i have a problem insert data to mysql working but i need if not exist data create if exist update all row.
Now after each refresh page add same data but not updating.
$conn = mysql_connect("127.0.0.1", "root","") or die(mysql_error());
mysql_select_db("youtuberiai", $conn);
echo "Connected successfully <br /><br />";
$url = 'https://www.googleapis.com/youtube/v3/channels?id=ID&part=snippet%2Cstatistics&key=KEY';
$content = file_get_contents($url);
$json = json_decode($content, true);
foreach($json as $row);
foreach($json['items'] as $row)
{
$idd = $row['id'];
$title = $row['snippet']['title'];
$description = $row['snippet']['description'];
$viewCount = $row['statistics']['viewCount'];
$subscriberCount = $row['statistics']['subscriberCount'];
$sql = "INSERT INTO vartotojai(idd, title, description, viewCount, subscriberCount) VALUES('$idd', '$title','$description','$viewCount','$subscriberCount')
ON DUPLICATE KEY UPDATE idd='$idd', title='$title', description='$description', viewCount='$viewCount', subscriberCount='$subscriberCount';
";
mysql_query("SET NAMES utf8");
if(!mysql_query($sql,$conn))
{
die('Error : ' . mysql_error());
}
}
make the id as unique. Then only duplicate query gets the role. If the value in that filed already exist, then then that field will be updated.

Not getting correct value in return

The idea of the task is to allow the user to add and withdraw "money" to and from their account. The problem is I can add money, but I can't withdraw it
$funds = $_POST['funds'];
$withdraw_or_add = $_POST['list'];
if($withdraw_or_add == "add")
{
$sql = "UPDATE users SET userFunds = '".$funds."' WHERE userId = 1";
}
else
{
$info = mysql_query("SELECT * FROM users WHERE userId = '1'");
$info = mysql_fetch_assoc($info);
$new_fund = $info['userFunds'] - $funds;
$sql = "UPDATE users SET userFunds = '".$new_fund."' WHERE userId = 1";
}
mysql_select_db('details_db');
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not update data: ' . mysql_error());
}
echo "Updated data successfully\n";
mysql_close($conn);
So for example, let's say $fund = 5 and $info['userFunds'] = 20 then the variable $new_fund should be 15. But instead it equals -5. If anyone can help it would be much appreciated.
Firstly page of top you put used db connection related code :
$conn = mysql_connect('localhost', 'user', 'pass');
mysql_select_db('details_db');
and then bellow and removed mysql_select_db('details_db'); line after mysql_
$funds = $_POST['funds'];
$withdraw_or_add = $_POST['list'];
if($withdraw_or_add == "add")
{
$sql = "UPDATE users SET userFunds = '".$funds."' WHERE userId = 1";
}
else
{
$info = mysql_query("SELECT * FROM users WHERE userId = '1'");
$info = mysql_fetch_assoc($info);
$new_fund = $info['userFunds'] - $funds;
$sql = "UPDATE users SET userFunds = '".$new_fund."' WHERE userId = 1";
}
//mysql_select_db('details_db');
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not update data: ' . mysql_error());
}
echo "Updated data successfully\n";
mysql_close($conn);
Note: Please stop using mysql_* functions. mysql_* extensions have been removed in PHP 7. Please used PDO and MySQLi.

Half of PHP script not submitting

I have made a php script to pull from two different tables within the same database. After the data is pulled, it is put into another table that will hold that specific information for later use. Right now, it will submit the userid and username but will not submit the puid variable I have stated.
Here is the script
include('data.php');
//Database Connection
$con=#mysql_connect("$ip", "$guser", "$gpass")
or die(mysql_error());
//Select Database
$dbcon=#mysql_select_db($forums, $con)
or die(mysql_error());
$search = $_POST['term'];
$sql = mysql_query("select userid, usergroupid, username from $users where username like '%$search%'");
while ($row = mysql_fetch_array($sql)) {
$id = $row['userid'];
$name = $row['username'];
$ugid = $row['usergroupid'];
}
if ($ugid == '21') {
$sql4 = "INSERT INTO $vip (fuid, username) VALUES ('$id', '$name')";
$res2 = #mysql_query($sql4, $con) or die(mysql_error());
$sql2 = mysql_query("SELECT $id, field5 FROM $userfield");
while ($row = mysql_fetch_array($sql2)) {
$puid = $row['field5'];
}
$sql3 = "INSERT INTO $vip (puid) VALUES ('$puid')";
$res = #mysql_query($sql3, $con) or die(mysql_error());
echo 'Completed';
} else {
echo 'User is not VIP';
}
you are not doing those queries for all retrieved rows.you should get those queries inside foreach loop otherwise only the last row will be effected!

Cant get included file to connect to database

I must be missing something simple but I don't see it. The following code works great.
<?php
$res = mysql_connect("localhost", "newuser", "");
mysql_select_db("supplydb");
function filter($data)
{
$data = trim(htmlentities(strip_tags($data)));
if (get_magic_quotes_gpc())
$data = stripslashes($data);
$data = mysql_real_escape_string($data);
return $data;
}
error_reporting(0);
require("../codebase/grid_connector.php");
$mask5 = filter($_GET["var1"]);
//Get Category ID
$cat = mysql_query("SELECT category FROM submissions WHERE submissions.submission_id='$mask5'");
$rows = mysql_fetch_array($cat, MYSQL_ASSOC);
$array = filter($rows['category']);
//Get Manufactuer ID
$man = mysql_query("SELECT manufacturer_id FROM submissions WHERE submissions.submission_id='$mask5'");
$arows = mysql_fetch_array($man, MYSQL_ASSOC);
$array1 = filter($arows['manufacturer_id']);
function formatting($row)
{
$data = $row->get_value("fda_approved");
if ($data == 1)
$row->set_value("fda_approved", Yes);
else
$row->set_value("fda_approved", No);
}
$gridConn = new GridConnector($res, "MySQL");
function myUpdate($action)
{
$data6 = $action->get_id();
$cat_id = mysql_query("SELECT category FROM submissions WHERE submissions.submission_id ='{$data6}'") or die("Error in query: $query. " . mysql_error());
$rows56 = mysql_fetch_array($cat_id, MYSQL_ASSOC);
$array = filter($rows56['category']);
$status = $action->get_value("approval_status");
$gridConn = new GridConnector($res, "MySQL");
mysql_query("UPDATE submissions SET approval_status='{$status}' WHERE submissions.submission_id='{$data6}'") or die("Error in query: $query. " . mysql_error());
$action->success;
}
$gridConn->event->attach("beforeUpdate", "myUpdate");
$gridConn->event->attach("beforeRender", "formatting");
$gridConn->render_sql("SELECT * FROM submissions JOIN products ON products.product_id = submissions.product_id and submissions.category='$array' and submissions.manufacturer_id='$array1' and submissions.approval_status='0'", "submission_id", "item_number,description,list_price,sugg_price,quantity_per_unit,fda_approved,gpo_contract_number, approval_status");
?>
This code does not
<?php
require("../site_globals/dbc_simple.php");
//$res = mysql_connect("localhost", "newuser", "");
//mysql_select_db("supplydb");
error_reporting(0);
require("../codebase/grid_connector.php");
$mask5 = filter($_GET["var1"]);
//Get Category ID
$cat = mysql_query("SELECT category FROM submissions WHERE submissions.submission_id='$mask5'");
$rows = mysql_fetch_array($cat, MYSQL_ASSOC);
$array = filter($rows['category']);
//Get Manufactuer ID
$man = mysql_query("SELECT manufacturer_id FROM submissions WHERE submissions.submission_id='$mask5'");
$arows = mysql_fetch_array($man, MYSQL_ASSOC);
$array1 = filter($arows['manufacturer_id']);
function formatting($row)
{
$data = $row->get_value("fda_approved");
if ($data == 1)
$row->set_value("fda_approved", Yes);
else
$row->set_value("fda_approved", No);
}
$gridConn = new GridConnector($res, "MySQL");
function myUpdate($action)
{
$data6 = $action->get_id();
$cat_id = mysql_query("SELECT category FROM submissions WHERE submissions.submission_id ='{$data6}'") or die("Error in query: $query. " . mysql_error());
$rows56 = mysql_fetch_array($cat_id, MYSQL_ASSOC);
$array = filter($rows56['category']);
$status = $action->get_value("approval_status");
$gridConn = new GridConnector($res, "MySQL");
mysql_query("UPDATE submissions SET approval_status='{$status}' WHERE submissions.submission_id='{$data6}'") or die("Error in query: $query. " . mysql_error());
$action->success;
}
$gridConn->event->attach("beforeUpdate", "myUpdate");
$gridConn->event->attach("beforeRender", "formatting");
$gridConn->render_sql("SELECT * FROM submissions JOIN products ON products.product_id = submissions.product_id and submissions.category='$array' and submissions.manufacturer_id='$array1' and submissions.approval_status='0'", "submission_id", "item_number,description,list_price,sugg_price,quantity_per_unit,fda_approved,gpo_contract_number, approval_status");
?>
The only difference is the include file at the top and all the include file is is:
<?php
$res = mysql_connect("localhost", "newuser", "");
mysql_select_db("supplydb");
?>
Im fairly new to php but this seems simple and I'm not sure what is getting lost in translation. This works fine on other pages by the way so it must have something to do with the $gridConn = new GridConnector($res, "MySQL"); but I dont know enough to see what. I'm using the DHTMLX javascript library. Could it have something to do with that? Ive tried everything here. Ideas?
Im getting: XML Parsing Error: XML or text declaration not at start of entity Location
Problem is not in the database connection itself, it works correctly and generates data, but result xml corrupted, because some output was started before connector's code.
Check ../site_globals/dbc_simple.php - probably it have some whitespaces|newlines after closing "?>" tag - delete them and it will fix the problem.
Such whitespaces|newlines will not cause harm for HTML pages, but for XML data any extra char at start of document can cause a problem.

Categories