I am trying to read in an XML file and compare it to fields in an existing database.
If the ID in the database doesn't exist in the XML file, then the whole row corresponding to the Id is no longer valid and will be deleted.
To do this I read in each line of the XML from start to finish in a while statement.
As step one I am trying to do a simple compare, and echo if it finds an Id in the database that doesn't exist in the XML.
I know there are some Ids in the database that don't exist in the XML, but the following code is not displaying them.
I've got three questions, firstly how would I display the Id that is pulled from the database, and secondly why isn't this code finding any ids that are not in the XML?
The final question is am I going about this completely the wrong way and is there a better way to do it!
$sql_result = mysql_query("SELECT id FROM `list` WHERE id = $id") or die(mysql_error());
if($sql_result)
{
// echo $id . " Id exists " . $sql_result["id"] . "\n";
}
else
{
echo "Id no longer exists" . $id . "\n";
}
Your code isn't finding what you expect because even though the id may not be found, $sql_result still holds a TRUE value because the query was successful. Instead, check if myqsl_num_rows() > 0
if($mysql_num_rows($sql_result) > 0)
{
// echo $id . " Id exists "\n";
//Now, to print the id, you need to fetch it from `$sql_result`,
//which is just a resource at this point:
$row = mysql_fetch_assoc($sql_result);
echo $row['id'];
}
This is the proper way to check:
$sql_result = mysql_query("SELECT `id` FROM `list` WHERE `id` = ".intval($id,10)." LIMIT 0,1");
if(is_resource($sql_result) && mysql_num_rows($sql_result) > 0 ){
$sql_result = mysql_fetch_assoc($sql_result);
echo $id . " Id exists " . $sql_result["id"] . "\n";
}
else{
echo "Id no longer exists" . $id . "\n";
}
You should check the number of rows returned using mysql_num_rows(). Otherwise, you are simply checking to see if the query executed without any error.
if($sql_result)
to
if(mysql_num_rows($sql_result))
You can use NOT IN() on your select with the IDs that exist on you XML like:
SELECT id FROM `list` WHERE id NOT IN($your_id_list)
With this you'll have a list of IDs that are not in the list.
Your IDs must be separated with a comma like:
SELECT id FROM `list` WHERE id NOT IN(123,654,987,45)
Question 1: how would I display the Id that is pulled from the database?
$sql_result = mysql_query("SELECT `id` FROM `list` WHERE `id` = $id") or die(mysql_error());
$sql_row = mysql_fetch_assoc($sql_result);
if(!empty($sql_row['id'])) {
echo "Id exists - " . $sql_row['id'] . "\n";
} else {
echo "Id no longer exists - " . $sql_row['id'] . "\n";
}
Question 2: why isn't this code finding any ids that are not in the XML?
I think in your code the if() condition will always return true irrespective if the Id exists in the database or not. And secondly as you might have guessed from my code above, you are missing to fetch the data from the SQL resultset
Question 3: am I going about this completely the wrong way and is there a better way to do it?
You are doing it the right way by browsing through the XML and checking each entry in the database for existence. A better way might be to first retrieve all IDs from the XML and then use them in the single SQL query:
SELECT `id` FROM `list` WHERE `id` NOT IN ($list);
Please note that this query might run slow if there are a very large number of IDs in the XML file, say a few hundreds.
mysql_num_rows()
Or
SELECT COUNT(*) [...]
Related
I am a novice when it comes to PHP but I don't understand if my syntax is wrong in this statement, or how would I grab an int from my MySQL server.
I know that my server credentials are working fine. How would I fix this statement to give me a returned integer of the number of reviews in the userinfo table?
$numberofpreviousreviews = mysql_query("SELECT `number_of_reviews` FROM `userinfo`") or die(mysql_error()); //Check to see how many reviews user has previously created
$amountofreviews = $numberofpreviousreviews + 1;
$query2 = mysql_query("ALTER TABLE userinfo ADD `amountofreviews` VARCHAR(10000)") or die(mysql_error()); //Make another column in database for the new review
You need to fetch your results after you run your query. There are several ways to do this but using mysql_fetch_assoc() will work for you.
$numberofpreviousreviews = mysql_query("SELECT `number_of_reviews` FROM `userinfo`") or die(mysql_error()); //Check to see how many reviews user has previously created
$row = mysql_fetch_assoc($numberofpreviousreviews);
$amountofreviews = $row['number_of_reviews'] + 1;
FYI, you shouldn't be using mysql_* functions anymore. They are deprecated and going away. You should use mysqli or PDO.
Assume you have a table userinfo which has the following structure and data :
Scenario #1 :
If you want to retrieve the all number_of_reviews, then do like this,
$query = "SELECT `number_of_reviews` FROM `userinfo`";
$result = mysqli_query($db,$query);
while ($row = mysqli_fetch_assoc($result)) {
echo "Number of reviews : " . $row['number_of_reviews'] . "<br/>";
}
It will give you,
Number of reviews : 20
Number of reviews : 40
Since, the result has many rows, it will display like above.
Scenario #2:
If you want to retrieve only the specific number_of_reviews for some user id (which is unique). I take id as 1 as a example here. Then do like,
$query2 = "SELECT `number_of_reviews` FROM `userinfo` WHERE `id` = 1";
$result2 = mysqli_query($db,$query2);
while ($row2 = mysqli_fetch_assoc($result2)) {
echo $row2['number_of_reviews'] . "<br/>";
}
This will print,
20.
Because, number_of_reviews is 20 for id 1.
I use this query to get username data table so if i write url index.php?user=username get user data base on username if index.php and data table redirect to admin table this my query
it's work if i write url index.php?user=username data display base on username but if write index.php data not display ..
what wrong with this query thanks
if(isset($_GET['user'])) {
$result = mysql_query("select * from content_table where username = '" . $_GET['user'] . "' limit 2 ;");
if(!empty($GET['user'])){
$result = mysql_query("select * from content_table order by content_id desc limit 1;");
}
I'll leave the SQL injection issue aside for now. First of all, you are missing a closing curly brace. The second problem is that you are not doing the second part correctly. You have:
if(isset($_GET['user'])) {
// query based on username
if(!empty($GET['user'])){
// query just first row
}
The second check is doing the same as the first one - there's no need for it. Your logic should be:
if(!empty($_GET['user'])) {
// query based on username
}
else {
// query just first row
}
Note that you will also need to deal with empty results somewhere.
Now, as for your SQL injection vulnerability, imagine for a second that the username passed in is myname'; drop table content_table -- - your code would simply put this in and execute it - dropping the table. Think about it.
Oh, and please do yourself a favour and stop using mysql_ functions - switch to PDO or at least mysqli_.
Try this
if(empty($GET['user'])){
$result = mysql_query("select * from content_table order by content_id desc limit 1;");
}
if(isset($_GET['user'])) {
$result = mysql_query("select * from content_table where username = '" . $_GET['user'] . "' limit 2 ;");
You have your empty test backwards. So when the parameter is empty, you never perform either query.
Do this:
if (empty($_GET['user'])) {
$result = mysql_query("select * from content_table order by content_id desc limit 1;");
} else {
$result = mysql_query("select * from content_table where username = '" . $_GET['user'] . "' limit 2 ;");
}
empty() performs an isset test first, so you don't need to do both.
I have this bit of code that doesn't produce anything, not even an error message. I'm trying to echo the result inside the while loop, but even that doesn't show anything. Any tips?
foreach($droppedStudentIds as $value){
$query3 = "select * from student_classlists where StudentId = '$value' and ClassListDate = (select max(ClassListDate) from student_classlists)";
if($result = mysqli_query($mysqli, $query3)) {
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
echo "Date: ".$row['ClassListDate'];
$droppedStudentIds[$value][] = $row['ClassListDate'];
}
mysqli_free_result($result);
} else die ("Could not execute query 3");
}
My goal is to look up a date information for each element inside the $droppedStudentIds array. I checked the MySQL query in itself and it produces that desired result.
Thanks!
You're assigning to the array you're looping through on this line:
$droppedStudentIds[$value][] = $row['ClassListDate'];
This could be causing your script to timeout, which would be why you're not seeing any output.
I'd add a second array to avoid conflicts and use that for storing results from the query, e.g.
$temp[$value] = $row['ClassListDate'];
Thanks all for the response, it helped pin down the mistake!
No need for a while loop when asking for a single record
The query was actually incorrect. The subselect was getting the maximum date in the database, regardless of whether the StudentId was present or not. The correct query is the following:
select ClassListDate from student_classlists where StudentId = '$value' and ClassListDate = (select max(ClassListDate) from student_classlists where StudentId = '$value')
Thanks again!
Some may know my script Basic Announce, I am trying to get the latest news entry that has been sent through so only the last know entry is called up.
In this code block is the news caller that I originally created but this decides to call all of the entries but thats for the Admin to see, but I need the last entry to be called in this file: news.php
<?php
// Connects to your Database
mysql_connect("$server","$usr","$pswd") or die(mysql_error());
mysql_select_db("$db") or die(mysql_error());
$data = mysql_query("SELECT * FROM announcements")
or die(mysql_error());
while($info = mysql_fetch_array( $data ))
{
Print "<tr>";
Print "<th>Announcement:</th><td>".$info['Announcement'] . "</td> ";
Print "<br>";
Print "<th>Submitted By:</th> <td>".$info['Submitted'] . "</td> ";
}
;
?>
How would I go about select the last know entry I also include my database tables sql code.
Here is the Basic Announce.sql code
CREATE TABLE IF NOT EXISTS `announcements` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`Announcement` text NOT NULL,
`Submitted` text NOT NULL,
`Date_time` date NOT NULL,
PRIMARY KEY (`id`)
);
Is it possible to pull the last record using my Primary Key "id"?
Any help on this troubling matter would be greatly appreciated as I am still learn PHP via self-taught and inspiration.
Many Thanks
Order it by the id descending:
$data = mysql_query("SELECT * FROM announcements ORDER BY id DESC LIMIT 1");
I also added LIMIT 1 because you only want to retrieve the first row in the set. Given you only want a single row, you don't need the while loop, just make a single call to fetch:
$data = mysql_query("SELECT * FROM announcements ORDER BY id DESC LIMIT 1");
if($data && mysql_num_rows($data) == 1) // check for success and a row found
{
$info = mysql_fetch_array( $data );
Print "<tr>";
Print "<th>Announcement:</th><td>".$info['Announcement'] . "</td> ";
Print "<br>";
Print "<th>Submitted By:</th> <td>".$info['Submitted'] . "</td> ";
}
else
{
// no rows or an error occurred
}
Side notes:
The mysql_* library is deprecated. For new code you should consider upgrading to PDO or MySQLi.
.. or die(mysql_error()) should be avoided. A better option is trigger_error(mysql_error()).
try out this.
SELECT Top 1 * FROM announcements order by id desc
I have a problem with integers in MySQL. I am trying to update a cell which stores an integer. However, I have problem with the type of that cell. Actually it is type is set to int but when I retrive the data I always get 0 and I belive it is because of the problem about how I am trying to get it. Here is my code sample;
function updateNumb($username) {
$query = "SELECT `num` FROM `profiles` WHERE `nick`='" . $username . "'";
$result = mysql_query($query, $this->conn) or die(mysql_error());
$row = mysql_fetch_array($result, MYSQL_ASSOC);
$row['num'] = $row['num'] + 1;
$numb = (int)$row['num'] + 1;
//here I update the data.
$query = "UPDATE `profiles` SET `num`=" . $numb . " WHERE `nick`='".$username."'";
mysql_query($query, $this->conn) or die(mysql_error());
return $numb;
}
Can it be because of mysql_fetch_array stuff? Or how could I overcome this problem?
replace partisayisi with num
There is nothing wrong with the code you provided, maybe it's not doing what you really need, for example num is incremented twice, but there are no visible mistakes that would make it return 0, at least not in what we can see.
Make sure you provide valid username, try to echo your query before sending to mysql to see what it really looks like, maybe try this query yourself in mysql client or phpmyadmin to see what's going on.
Also if the only thing you need is to increment num for some user you can do it in one update, you don't need to use select to get that number:
UPDATE profiles set num=num+1 WHERE nick='somenick'