I have used SimpleXML to get XML data from a source that required authenticiation. Using cURL I have been able to get back a result. However when I have tried to get the data into a MySQL database nothing is inserted.
Now I think it's because I have not done something to the XML data. However I am a newbie to XML data and have always worked with database stuff so could do with some help.
I have had a look around and I'm probably duplicating another question on here, but my confusion is over what I am looking at. If I can figure out the "why", I'll get to the "how"!.
Here is the output I get:
SimpleXMLElement Object
(
[bookingDataResponse] => SimpleXMLElement Object
(
[bookingDataResult] => <Bookings><SupplierCode>ABCD</SupplierCode><ServiceName>Service 1</ServiceName><UnitCode>ABC123</UnitCode></Bookings><Bookings><SupplierCode>XYZ</SupplierCode><ServiceName>Service 2</ServiceName><UnitCode>XYZ123</UnitCode></Bookings>
)
)
I presume that I need to transform the result of the above and then get that data to insert into the database. However this is where I am stuck.
I'll use PDO and a foreach to get the data into the database, but any help on getting to that point would be very useful guys.
Cheers
UPDATE # 11:18GMT:
This update covers the database insert I have coded:
$servername = "xxx.xxx.xxx.xxx";
$username = "username";
$password = "password";
$dbname = "myDatabase";
$db_cstr = "mysql:host=" . $servername . "; dbname=" . $dbname;
$conn=new PDO($db_cstr, $username,$password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
foreach ($parser->bookingDataResponse->bookingDataResult->Bookings as $row)
{
$SupplierCode = ($row->SupplierCode);
$UnitCode = ($row->UnitCode);
$stmt = $conn->prepare("INSERT INTO `bookingData` (`SupplierCode`, 'UnitCode') VALUES (?,?)");
$stmt->execute(array($SupplierCode,$UnitCode));
}
Related
MySQL is not using the variables as it should. it is not taking any value from them it is incrementing the auto-increment numbers in the MYSQL table, however the row is not saved. I am not given any errors.
I have tried like this:
$sql = "INSERT INTO `tbl_bike` (`userID`, `ManuPartNo`, `BikeManufacturer`, `BikeModel`, `BikeType`, `BikeWheel`, `BikeColour`, `BikeSpeed`, `BrakeType`, `FrameGender`, `AgeGroup`, `DistFeatures`)
VALUES (“.$userID.”, “.$PartNo.”, “.$BikeManufacturer.”, “.$BikeModel.”, “.$BikeType.”, “.$BikeWheel.”, “.$BikeColour.”, “.$BikeSpeed.”, “.$BrakeType.”, “.$FrameGender.”, “.$AgeGroup.”, “.$DistFeatures.”)";
I have also tried replacing the " with ', Removing the . and even completely removing the ". Nothing has helped with this issue. When I use this query but remove the variables and instead put string, int etc in the correct places the query will function perfectly and put the results into the table. My variables are normally as follows:
$PartNo = $_POST['ManuPartNo’];
$BikeManufacturer = $_POST['BikeManufacturer’];
$BikeModel = $_POST['BikeModel’];
$BikeType = $_POST['BikeType’];
$BikeWheel = $_POST['BikeWheel’];
$BikeColour = $_POST['BikeColour’];
$BikeSpeed = $_POST['BikeSpeed’];
$BrakeType = $_POST['BrakeType’];
$FrameGender = $_POST['FrameGender’];
$AgeGroup = $_POST['AgeGroup’];
$DistFeatures = $_POST['DistFeatures’];
These variables normally take input from a separate PHP/HTML file with the '$_POST['DistFeatures’];'
I have tried removing the $_POST['DistFeatures’]; from the ends of each of them and just replacing the values with normal string or int values but still nothing helps. I am completely stuck and would appreciate any help with this.
This is all running on a plesk server.
Please stop using deprecated MySQL. I will suggest an answer using PDO. You can use this to frame your other queries using PDO.
// Establish a connection in db.php (or your connection file)
$dbname = "dbname"; // your database name
$username = "root"; // your database username
$password = ""; // your database password or leave blank if none
$dbhost = "localhost";
$dbport = "10832";
$dsn = "mysql:dbname=$dbname;host=$dbhost";
$pdo = new PDO($dsn, $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
// Include db.php on every page where queries are executed and perform queries the following way
// Take Inputs this way (your method is obsolete and will return "Undefined Index" error)
$userId = (!empty($_SESSION['sessionname']))?$_SESSION['sessionname']:null; // If session is empty it will be set to Null else the session value will be set
$PartNo = (!empty($_POST['ManuPartNo']))?$_POST['ManuPartNo']:null; // If post value is empty it will be set to Null else the posted value will be set
$BikeManufacturer = (!empty($_POST['BikeManufacturer']))?$_POST['BikeManufacturer']:null;
$BikeModel = (!empty($_POST['BikeModel']))?$_POST['BikeModel']:null;
$BikeType = (!empty($_POST['BikeType']))?$_POST['BikeType']:null;
$BikeWheel = (!empty($_POST['BikeWheel']))?$_POST['BikeWheel']:null;
// Query like this
$stmt = $pdo->prepare("INSERT INTO(`userID`, `ManuPartNo`, `BikeManufacturer`, `BikeModel`, `BikeType`)VALUES(:uid, :manuptno, :bkman, :bkmodel, :bktype)");
$stmt-> bindValue(':uid', $userId);
$stmt-> bindValue(':manuptno', $PartNo);
$stmt-> bindValue(':bkman', $BikeManufacturer);
$stmt-> bindValue(':bkmodel', $BikeModel);
$stmt-> bindValue(':bktype', $BikeType);
$stmt-> execute();
if($stmt){
echo "Row inserted";
}else{
echo "Error!";
}
See, it's that simple. Use PDO from now on. It's more secured. To try this, just copy the whole code in a blank PHP file and and run it. Your database will receive an entry. Make sure to change your database values here.
You should try this
$sql = "INSERT INTO tbl_bike (userID, ManuPartNo, BikeManufacturer, BikeModel, BikeType, BikeWheel, BikeColour, BikeSpeed, BrakeType, FrameGender, AgeGroup, DistFeatures) VALUES ('$userID', '$PartNo', '$BikeManufacturer', '$BikeModel', '$BikeType', '$BikeWheel', '$BikeColour', '$BikeSpeed', '$BrakeType', '$FrameGender', '$AgeGroup', '$DistFeatures')";
If this doesn't work, enable the null property in sql values. So you can find out where the error originated.
i would really appreciate if anyone can help me out with this mysql php problem of which i have no idea how to do it.
I Have a column named = 'x'
The text of that column 'x' is = "yz,zz,zy"
I want to edit the value of the column 'x' to = "yz,zyz,zy".
Now how do i add that 'y' in the middle term between yz and zy using CONCAT.
Regards.
You haven't provided any code or an attempt for us to go off of something so I'll give you a brief way of doing it. Look up PDO here This is a really easy to follow and secure way to manipulate data in your database using php. Again as you haven't given me much to go off i'm unsure if you want to just set something at specific count of characters along OR if you want to just update the entire thing, SO i'll help you with the latter as it will help give you some base understanding.
Please read into PDO further as this is just an example further down the line and will not run if you just blindly copy and paste it in.
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "test";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "UPDATE table SET x='yz,zyz,zy' WHERE id= 1"; // No clue if you've even given anything IDs
$stmt = $conn->prepare($sql);
$stmt->execute();
echo $stmt->rowCount() . " records UPDATED";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
As you haven't really provided any Schema of the table you are updating this is the best I could provide based off of what you have given me.. try to include as much information as possible as I'm unsure if this is what you even want
Hy everyone, I can't wrap my head around this. I'm trying to get some data from a table using PDO. this is my code:
//in db.php I have the connection:
$host = 'localhost';
$db = 'APL';
$dbuser = '';
$pass = ' ';
try{
$conn = new PDO("mysql:host=$host;dbname=$db", $dbuser, $pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
//in my file I have this:
$id = $_GET['id'];
$sel_sql = "SELECT * FROM users WHERE id =:id";
$stmt = $conn ->prepare($sel_sql);
$stmt -> bindParam(':id', $id);
$stmt -> execute();
$result = $stmt -> fetchAll(PDO::FETCH_ASSOC);
The problem is that print_r($result) returns '1' (just the value 1, therefore I can't access any data stored in the table) as long as $_SESSION['user'] is set.
The whole data-retrieving worked just fine if the $_SESSION['user'] is not set.
Can someone please explain why this is happening? (I'm fairly new to all this and I'm really trying to understand why some issues occur).
Thank you!
The fetchAll function should be returning either an array, or a boolean FALSE.
You report that print_r($result) is displaying an integer value of 1.
I don't see how that's possible, unless you are assigning a different value to $result. Try relocating print_r($result) to immediately follow the assignment from fetchAll.
(My suspicion is that $result is being assigned a value of 1 elsewhere in your code, before you do the print_r. If there were "Issues with php connection to MySQL database", we'd be expecting to see a PDO error of some sort.)
NOTE: I don't think PDO::FETCH_ASSOC is a defined fetch style for the fetchAll function. (fetchAll has different fetch styles than fetch.)
Just in case someone else stumbles upon this, between the $result variable and the print_r($result) I had an include_once(); statement (which was wrongly put there in the first place).
Thank you everyone for your answers.
I've got this code with PHP PDO and I've got an INSERT query that runs twice. This code should insert the value 'Hello World' into the database. However, my code inserts the value twice into the database.
How do I fix this? I've stumbled upon other people with the same problem, but they have problems with a loop or they've used the explode function that messed something up. I don't have any of that, just one connection block and an insert query, and yet it does this weird thing.
The code:
// DB connect configuration
$user = 'user';
$pass = 'password';
// Database connection
$dsn = "mysql:host=localhost;dbname=pdotest;charset=utf8";
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
);
$conn = new PDO($dsn, $user, $pass, $opt);
// Data to insert
$data = 'Test and test and test';
// Insert data into database
$sql = "INSERT INTO tabletwo (rowTwo) VALUES (?)";
$q = $conn->prepare($sql);
$q->execute(array($data));
It's happening because of some Javascript code for page transitions. The code can be found here: http://www.fasw.ws/faswwp/non-jquery-page-transitions-lightweight/. I have no idea how to fix this though.
I'm making chat in flash as3 with php and mysql database.
However I don't know php at all, and got problem with updating messages.
for now my php file looks like this:
$caster = $_POST['caster'];
$msgText = $_POST['msgText'];
$sendTime = $_POST['sendTime'];
$query = "INSERT INTO chat VALUES ('','$sendTime','$caster','$msgText')"
mysql_query($query);
$query="SELECT * FROM chat";
$result=mysql_query($query);
$cast=mysql_result($result,1,"caster");
mysql_close();
$returnVars = array();
$returnVars['success'] = $success;
$returnVars['caster'] = $cast;
$returnString = http_build_query($returnVars);
echo $returnString;
And my question is how to loop for all already sent chat messages to send them to flash.
I can only do it with one, but I need whole bunch of them to be loaded.
Thanks
What you are looking for is "fetchAll". Note that your code is open to SQL injection, it is very easy to drop your database by passing evil values to the PHP script. I have changed the code therefore from the deprecated Mysql extension to PDO. PDO will to the escaping of the values for you.
Read more on PDO in the PHP manual (Lots of examples over there).
Also note that you have to adapt the following code snipped as I could not guess how the field names of the chat table in your database are named. So you have to adapt the insert statement below.
// database config parameters
$dbhost = "localhost";
$dbname = "test";
$dbuser = "root";
$dbpass = "";
try {
// try to set up a db connection
$db = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
// insert the data using PDO's prepared statements
// you have to adapt this line to the field names of your chat table!!
$sql = "INSERT INTO chat (sendtime,caster,msg) VALUES (:sendtime,:caster,:msg)";
$sth = $db->prepare($sql);
$sth->execute(array(
':caster' => $_POST['caster'],
':sendtime' => $_POST['sendTime'],
':msg' => $_POST['msgText']
));
// Get everything
$sth = $db->prepare("SELECT * FROM chat");
$sth->execute();
$result = $sth->fetchAll(PDO::FETCH_ASSOC);
// your code to format and return the data goes here
print json_encode($result);
}
catch (PDOException $e) {
// if anything related to the database goes wrong, catch the exceptions
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
$db = null;
The Actionscript will receive a JSON object looking similar to this:
[
{
"sendtime":"2013-04-14",
"caster":"person1",
"msg":"Message 1"
},
{
"sendtime":"2013-04-15",
"caster":"person2",
"msg":"Message 2"
}
]
As you can see the JSON has no specific variable name like in the version with GET used in the question (the method used in the question does not work for large result lists).
So how do you work with the JSON document in Actionscript? I am not an actionscript programmer, but this Stackoverflow post looks like a reasonable answer to this problem:
Get and parse JSON in Actionscript