INSERT IGNORE In mySQL - php

I wonder whether someone can help me please.
I'm trying to put together a PHP script that takes data from an xml file and places the data in a mySQL data. I've been working on this for a few days and I'm still can't seem to get this right.
This is the code that I've managed to put together:
<?
$objDOM = new DOMDocument();
$objDOM->load("xmlfile.xml");
$Details = $objDOM->getElementsByTagName("Details");
foreach( $Details as $value )
{
$listentry = $value->getElementsByTagName("listentry");
$listentrys = $listentry->item(0)->nodeValue;
$sitetype = $value->getElementsByTagName("sitetype");
$sitetypes = $sitetype->item(0)->nodeValue;
$sitedescription = $value->getElementsByTagName("sitedescription");
$sitedescriptions = $sitedescription->item(0)->nodeValue;
$siteosgb36lat = $value->getElementsByTagName("siteosgb36lat");
$siteosgb36lats = $siteosgb36lat->item(0)->nodeValue;
$siteosgb36lon = $value->getElementsByTagName("siteosgb36lon");
$siteosgb36lons = $siteosgb36lon->item(0)->nodeValue;
//echo "$listentrys :: $sitetypes :: $sitedescriptions :: $siteosgb36lats :: $siteosgb36lons <br>";
}
require("phpfile.php");
//Opens a connection to a MySQL server
$connection = mysql_connect ("hostname", $username, $password);
if (!$connection) {
die('Not connected : ' . mysql_error());
}
// Set the active MySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
die ('Can\'t use db : ' . mysql_error());
}
mysql_query("INSERT IGNORE INTO scheduledsites (listentry, sitetype, sitedescription, siteosgb36lat, siteosgb36lon) VALUES('$listentrys','$sitetypes','$sitedescriptions','$siteosgb36lats','$siteosgb36lons') ")
or die(mysql_error());
echo "Data Inserted!";
?>
I can pull the data from the xml file, but it's the part of the script that sends the data to my database table that I'm having trouble with.
The script runs but only the last record is saved to the database.
I can parse the fields from the xml file without any problems and the check I'm trying to put in place is, if there is a 'listentry' number in the new data that is matched to one already in the table then I don't want that record to be added to the table, i.e. ignore it.
I just wondered whether someone could perhaps take a look at this please and let me know where I'm going wrong.
Many thanks

You are only calling mysql_query once. So it will only insert one row.
The sql needs to be inside the loop.

Related

Why won't my JSON array query work?

Can anyone see what the problem with my code is / where im going wrong?
I know i have the correct host,database,user and password.
This is the code in the php file, it should get all the details available on the players from my sql database, however if i go on the page it just gives me a white page. Im using go daddy as a host and my database is also on there.
Any ideas? thanks
<?php
$host = "abc12345"; //Your database host server
$db = "abc12345"; //Your database name
$user = "abc12345"; //Your database user
$pass = "abc12345"; //Your password
$connection = mysql_connect($host, $user, $pass);
//Check to see if we can connect to the server
if (!$connection) {
die("Database server connection failed.");
} else {
//Attempt to select the database
$dbconnect = mysql_select_db($db, $connection);
//Check to see if we could select the database
if (!$dbconnect) {
die("Unable to connect to the specified database!");
} else {
$query = "SELECT * FROM Player";
$resultset = mysql_query($query);
$records = array();
//Loop through all our records and add them to our array
while ($r = mysql_fetch_assoc($resultset)) {
$records[] = $r;
}
//Output the data as JSON
echo json_encode($records);
}
}
?>
The script is all right, I checked it with a different query.
Assuming that the table Player is not empty, the error can be either with your raw sql query (as pointed by #Sharikov in comments), otherwise the error is with the way you have configured your godaddy server.
For debugging that, I would suggest inserting dummy print_r or echo statements before you execute the query, and going through your apache logs at /var/log/apache2/access.log.
Also make sure that you don't have any core php package missing on your server (like php5-mysql if you use mysql).

Basic MySQL help? - submitting data

I've been getting better at PHP - but I have NO idea what I'm doing when it comes to MySQL.
I have a code
<IMG>
I need to grab the "for", "affi" and "reff" and input them into a database
//Start the DB Call
$mysqli = mysqli_init();
//Log in to the DB
if (!$mysqli) {
die('mysqli_init failed');
}
if (!$mysqli->options(MYSQLI_INIT_COMMAND, 'SET AUTOCOMMIT = 0')) {
die('Setting MYSQLI_INIT_COMMAND failed');
}
if (!$mysqli->options(MYSQLI_OPT_CONNECT_TIMEOUT, 5)) {
die('Setting MYSQLI_OPT_CONNECT_TIMEOUT failed');
}
if (!$mysqli->real_connect('localhost', 'USERNAME', 'PASSWORD', 'DATABASE')) {
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
That's what I'm using to create a connection. It works. I've also got a table created, call it "table", with rows for "for", "affi", and "reff".
So my question is... someone gets directed to http://www.example.com/test.php?for=abcde&affi=12345&reff=foo
Now that I've got a DB connection open - how do I SEND that data to the DB before redirecting them to their destination site? They click - pass across this page - get redirected to destination.
BONUS KARMA - I also need a separate PHP file that I can create that PULLS from that data base. If you could point me at some instructions or show me a simple "how to pull this rows values from this table" I would be greatly appreciative :)
If I understand correctly, you'll want to use $_GET to get the URL parameters.
Then you want to run an insert query on the db with the values you got, which should be something like:
INSERT INTO table VALUES(x, y, z)
Then you need to change the page using a location header.
For the bonus question you just need the code you have now with a select query like:
SELECT * FROM table WHERE 1;
and then fetch the query results.
If this does not answer your questions please provide some clarifications.
Mysqli is the deprecated function and now PDO is recommended to connect to database. You could do following.
<?php
$conn = new PDO('dblib:host=your_hostname;dbname=your_db;charset=UTF-8', $user, $pass);
$sql = "SELECT * FROM users WHERE username = '$username'";
$result = $conn->query($sql);
?>
Read more here.

Display MySQL Database as an array

I have a MySQL database full of user information, like their username, password, email, etc.
I want a PHP script that allows me to pull JUST their username and display it like so:
"username1","username2","username3"
Literally exactly like that, the quotes and all.
EDIT: Sorry for not supplying enough information.
The table is named "users" the field I want to pull off it is "username" I can get it to pull and display all the information, my only problem is imploding it.
OK dude, read the comments
<?php // open a php tag
$dbc = mysql_connect("host", "username", "password"); // connect to database
mysql_select_db("db_name", $dbc) // select the database
$sql = "SELECT `username` FROM `users_table`"; // select only the username field from the table "users_table"
$result = mysql_query($sql); // process the query
$username_array = array(); // start an array
while($row = mysql_fetch_array($result)){ // cycle through each record returned
$username_array[] = "\"".$row['username']."\""; // get the username field and add to the array above with surrounding quotes
}
$username_string = implode(",", $username_array); // implode the array to "stick together" all the usernames with a comma inbetween each
echo $username_string; // output the string to the display
?>
I've seen all the other answers, however have you considered using PDO instead of mysql_query functions? It's a much nicer way to work with the database.
Here's what you want to achieve in a few lines of code (using lamba functions):
$dbh = new PDO("mysql:host=localhost;dbname=test", "yourusername", "yourpassword");
$results = $dbh->prepare("SELECT u.username FROM users u");
$results->execute();
$results = $results->fetchAll();
echo implode(", ", array_map(function(&$r) { return $r['username']; }, $results));
Output: Jamie, Bob, Chris
Nice and clean. Also, you should check if you have any results that have been returned and if the query was successful.
Just another approach.
EDIT: I've just realised you're a beginner so my answer may be a bit too advanced. However, i'll leave it for others to see as a solution, and perhaps you might look into using PDO an lamba functions when you learn a bit more. Best of luck.
Let's assume that you have a 'mydb' database and 'users' table in it.
SQL needed:
USE mydb;
SELECT username from users;
Short version:
Wrap it in PHP calls to mysql PHP library
Get result as an array then implode it with comma symbol.
Long version:
First we need to connect to database:
$db = mysql_connect('DATABASE_HOST', 'USER', 'PASSWORD');
if (!$db) {
die('Not connected : ' . mysql_error());
}
$db_selected = mysql_select_db('mydb', $db);
if (!$db_selected) {
die ('Can\'t use mydb: ' . mysql_error());
}
Remember to always check the return values of functions.
Then we query the database:
$result = mysql_query('select username from users', $db);
...and fetch results in flat array (we need only usernames):
while ($row = mysql_fetch_array($result, MYSQLI_ASSOC))
{
$data[] = $row['login'];
}
Then we format the returned data according to your specs:
$string_result = '"'. implode('", "', $data) . '"';
You can do with $string_result anything you want, just close the database connection immediately after use:
mysql_close($db);
Good luck with learning PHP, BTW. ;)
You could using PHP's implode, but it's probably easier just do it in SQL assuming that the list won't be too long:
SELECT GROUP_CONCAT(CONCAT('"', username, '"')) AS usernames
FROM your_table

Stack Out Of Space Error

I'm having a little trouble with a query I've written (please see below).
<?php
require("phpfile.php");
// Start XML file, create parent node
$dom = new DOMDocument("1.0");
$node = $dom->createElement("markers");
$parnode = $dom->appendChild($node);
// Opens a connection to a MySQL server
$connection=mysql_connect ("hostname", $username, $password);
if (!$connection) { die('Not connected : ' . mysql_error());}
// Set the active MySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
die ('Can\'t use db : ' . mysql_error());
}
$query = "SELECT userdetails.userid
, detectinglocations.locationid
, detectinglocations.locationname
, finds.findid
, finds.locationid
, finds.findosgb36lat
, finds.findosgb36lon
, finds.dateoftrip
, finds.findcategory
, finds.findname
,finds.finddescription
, finds.detectorsettings
, finds.pasref
, finds.additionalcomments
, detectors.detectorname
, searchheads.searchheadname
FROM userdetails, detectinglocations, finds, detectors, searchheads
WHERE finds.userid=userdetails.userid
AND finds.locationid=detectinglocations.locationid
AND finds.detectorid=detectors.detectorid
AND searchheads.detectorid=detectors.detectorid";
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
header("Content-type: text/xml");
// Iterate through the rows, adding XML nodes for each
while ($row = #mysql_fetch_assoc($result)){
// ADD TO XML DOCUMENT NODE
$node = $dom->createElement("marker");
$newnode = $parnode->appendChild($node);
$newnode->setAttribute("findid",$row['findid']);
$newnode->setAttribute("locationid",$row['locationid']);
$newnode->setAttribute("locationname",$row['locationname']);
$newnode->setAttribute("dateoftrip",$row['dateoftrip']);
$newnode->setAttribute("findcategory",$row['findcategory']);
$newnode->setAttribute("findname",$row['findname']);
$newnode->setAttribute("finddescription",$row['finddescription']);
$newnode->setAttribute("detectorname",$row['detectorname']);
$newnode->setAttribute("searchheadname",$row['searchheadname']);
$newnode->setAttribute("detectorsettings",$row['detectorsettings']);
$newnode->setAttribute("pasref",$row['pasref']);
$newnode->setAttribute("additionalcomments",$row['additionalcomments']);
}
echo $dom->saveXML();
?>
When I run the php script through my web browser it retrieves the correct data, but when I run this through the HTML page I get an 'Out of Stack' error. From what I've read on the web, I think it may be because the SQL query is too complex.
Could you tell me please can an overly complex SQL query cause this type of error?
There's something wrong/unexpected with your data.
1) Do a file_put_contents("somedumpfile", var_export($row, true)) at the top of each loop, and see what's in the file after the process dies.
2) If that didn't help, then systematically remove one field at a time from being added as a node, from top to bottom. When you stop getting the error, you found the culprit.
3) If that still didn't help, start re-adding the fields as nodes, from top to bottom.
Make sure the PHP error-log is fully enabled and see if PHP is complaining about anything else. Also think about dumping the row index and PHP's current memory consumption (memory_get_usage) into that same file.
Good luck. Share your results.
(Vote me up if you like/accept this answer.)
Dustin

how to connect mysql Db through loops

hi i am using mysql for my database. just i try to connect mysql db through looping but it failed , i cannot , Is there is any otherway to do this
my trial code is this
while($row = mysql_fetch_array($query)) {
$temp = "db".$row["listid"];
$temp = mysql_connect("localhost","root","", true);
mysql_select_db($row["databasename"],$temp);
}
is it any other way to do this.
Try with:
$res = mysql_query($query);
while($row = mysql_fetch_array($res)) {
$name = "db".$row["listid"];
$temp = mysql_connect("localhost","root","", true) or die('Could not connect: ' . mysql_error());
mysql_select_db($row["databasename"],$temp);
$res = mysql_query($query, $temp);
}
and tell us your error - but, as the first comment, this is highly NOT recommended
You only require ONE database connection.
Once you connect to a database it is available for the life of that page (request).
If you require to switch databases that will also use the same connection (unless different credentials are required.
If it's for cross database queries if they are on the same MySQL server and the user for the initial connection has sufficient privileges, then you can prefix database tables with the database name.

Categories