how to delete rows from mysql database not found in xml file - php

I have an xml file and now it's been inserted to MySQL database, but there was a problem in the xml file which meant some data may be deleted from the site, so I updated the xml file and I wrote code for deleting data from database table which deleted from xml but the records are still in the database.
from another way I want to compare between xml file and database and delete data not found.
<?php
ini_set('display_errors','On');
//connecting to database.
echo "connected to DB<br /><br />";
$url = "test.xml";
$xmlfgc = file_get_contents($url);
$xmlitem = new SimpleXMLElement($xmlfgc);
echo "xml loaded<br /><br />";
foreach ($xmlitem->property as $xml) {
//$id = mysql_real_escape_string($xml->id);
$mls_id = mysql_real_escape_string($xml->ref);
//echo "$mls_id";
echo "xml parsed<br /><br />";
$result = mysql_query("SELECT mls_id FROM ezrealty");
//$select = "SELECT mls_id FROM ezrealty";
//$storeArray = Array();
//while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
// $storeArray[] = $row['mls_id'];
//}
if ($result != $mls_id){
$query = "DELETE FROM ezrealty WHERE mls_id = '$mls_id'";
mysql_query($query) or die(mysql_error());
echo "DataBase deleted<br /><br />";
}else{
echo "There is no deleted properties from xml file.";
}
}
//show updated records
echo "<br /><br />";
printf ("Records updated: %d\n", mysql_affected_rows());
//close connection
mysql_close($con2);
?>

thanks for you, now i have the solution for my problem.
<?php
ini_set('display_errors','On');
//connecting to database.
echo "connected to DB<br /><br />";
$url = "test.xml";
$xmlfgc = file_get_contents($url);
$xmlitem = new SimpleXMLElement($xmlfgc);
echo "xml loaded<br /><br />";
$xmldata = array();
foreach ($xmlitem->property as $xml) {
$mls_id = mysql_real_escape_string($xml->ref);
// $xmldata[] = "$mls_id";
$xmldata[] = '("' . $mls_id. '")';
}
//Get all reference numbers from database in array
$result = mysql_query("SELECT mls_id FROM gitfd_ezrealty");
$storeArray = Array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$storeArray[] = $row['mls_id'];
}
//get difference between two arrays.
$result1 = array_diff($xmldata, $storeArray);
foreach ($result1 as $value) {
//echo "<strong>$value</strong> <br />";
//$value1 = '("' . $value. '")';
//$query = 'INSERT INTO gitfd_ezrealty (mls_id)
//VALUES' . implode(',', $value1);
//mysql_query($query) or die(mysql_error());
//echo "inserted into mysql<br /><br />";
}
echo "These properties are founded in target site and Not founded in our site.<br />";
echo "________________________________________________________________"."<br />";
print_r($result1);
echo "<br />"."_____________________________________________________________________"."<br />";
$result2 = array_diff($storeArray, $xmldata);
foreach ($result2 as $value) {
//echo "<strong>$value</strong> <br />";
$query = "DELETE FROM ezrealty WHERE mls_id = '$value'";
mysql_query($query) or die(mysql_error());
echo "DataBase deleted<br /><br />";
}
echo "_________________________________________________________________"."<br />";
print_r($result2);
echo "<br />"."______________________________________________________________________"."<br />";
echo "These properties were deleted .<br />";
//show updated records
echo "<br /><br />";
printf ("Records updated: %d\n", mysql_affected_rows());
//close connection
mysql_close($con2);
?>

Related

unexpected end of file error PHP & JSON Decode Multiple Files

Hi I am working on trying to get my app to load json files from a folder and decode to a database using the following code :
<?php
$con = mysqli_connect("localhost", "root", "", "json_map");
$response = array();
$res = array();
foreach(glob('C:\xampp\htdocs\laravel\awsconfig\app\JSON_Files') as $filename) {$json = file_get_contents($filename);
if ($json != null) {
$decoded = json_decode($json, true);
//$decode= var_dump($decoded);
//$ss=$decode["array"];
//echo $decoded['number'];
if (is_array($decoded["configurationItems"])) {
foreach ($decoded["configurationItems"] as $configurationItems)
//for($i=0;$i>sizeof($decoded["configurationItems"]);$i++)
{
$configurationItemVersion = $configurationItems["configurationItemVersion"];
echo "<br />", "configuration_Item_Version:", $configurationItemVersion, "<br />";
$configurationItemCaptureTime = $configurationItems["configurationItemCaptureTime"];
echo "configurationItemCaptureTime:", $configurationItemCaptureTime, "<br />";
$configurationStateId = $configurationItems["configurationStateId"];
echo "configurationStateId:", $configurationStateId, "<br />";
$awsAccountId = $configurationItems["awsAccountId"];
echo "awsAccountId:", $awsAccountId, "<br />";
$configurationItemStatus = $configurationItems["configurationItemStatus"];
echo "configurationItemStatus:", $configurationItemStatus, "<br />";
$resourceId = $configurationItems["resourceId"];
echo "resourceId:", $resourceId, "<br />";
$ARN = $configurationItems["ARN"];
echo "ARN:", $ARN, "<br />";
$awsRegion = $configurationItems["awsRegion"];
echo "awsRegion:", $awsRegion, "<br />";
$availabilityZone = $configurationItems["availabilityZone"];
echo "availabilityZone:", $availabilityZone, "<br />";
$configurationStateMd5Hash = $configurationItems["configurationStateMd5Hash"];
echo "configurationStateMd5Hash:", $configurationStateMd5Hash, "<br />";
$resourceType = $configurationItems["resourceType"];
echo "resourceType:", $resourceType, "<br />";
$resourceCreationTime = $configurationItems["resourceCreationTime"];
echo "resourceCreationTime:", $resourceCreationTime, "<br />";
$result = mysqli_query($con, "INSERT INTO configuration_item(configuration_item_version,configuration_item_capture_time,configuration_state_id, aws_account_id, configuration_item_status, resource_id, arn, aws_region, availability_zone,configuration_state_md5_hash, resource_type, resource_creation_time)
VALUES('$configurationItemVersion','$configurationItemCaptureTime','$configurationStateId','$awsAccountId','$configurationItemStatus','$resourceId','$ARN','$awsRegion','$availabilityZone','$configurationStateMd5Hash','$resourceType','$resourceCreationTime' )") or die("Insert Failed " . ((is_object($con)) ? mysqli_error($con) : (($___mysqli_res = mysqli_connect_error()) ? $___mysqli_res : false)));
;
}
// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["code"] = 1;
$response["message"] = "successfully stored configuration items ";
// echoing JSON response
echo json_encode($response);
} else {
// failed to insert row
$response["code"] = 2;
$response["message"] = "Oops! An error occurred.";
// echoing JSON response
echo json_encode($response);
}
}
}
?>
I know it will be something stupid like a bracket but even using an IDE I am still no seeing it
Other than the missing foreach on line 7 (I'm assuming a mistake, because it would give a different syntax error message).
Your actual syntax error is a missing closing brace. Add } to the end of your code before the closing ?> and you have valid syntax. Whether you have working code is another matter. Try formatting your code with better indentation and you will more easily see where the missing tokens should be.
As a side note: A closing ?> is not required in PHP and I recommend against it.

Single row repeating instead of displaying

I'm pretty new at PHP/MySQL, so please be patient with me.
I am trying to get a list of members in a table to show up on a page. Right now it's showing the first member about 10 times and not displaying anyone else's name. I DID have it working, but I don't know what happened. I just want it to display everyone's name once. Here is my code:
<?php $select = mysql_query("SELECT * FROM `member_staff` WHERE `username`='$_SESSION[USR_LOGIN]' AND `status`='Active'");
$row = mysql_fetch_array($select);
$rows = mysql_num_rows($select);
$teaching = $row[teaching];
if ($rows==0){echo "Sorry, you don't appear to be a professor.";}
else { ?>
<?php }
$select2 = mysql_query("SELECT * FROM `classes_enrolled` WHERE `course`='" . $teaching . "' ORDER BY `student_name`") or die(mysql_error());
$count = mysql_num_rows($select2);
$row2 = mysql_fetch_array($select2);
$student=$row2[student_name];
if($count==NULL) {
echo "<table width=\"80%\">\n";
echo "<tr><td><center>Nobody has registered for your class yet!</center></td></tr>\n";
echo "</table>\n";
echo "<br /><br />\n\n";
}
else {
echo "<center><font size=\"3\"><b>YEAR 1, TERM 2</b></font></center>";
echo "<table width=\"80%\" class=\"table-stripes\">\n";
echo "<tr><td width=\"50%\"><b>STUDENT</b></td></tr>\n";
$select3 = mysql_query("SELECT * FROM `members` WHERE `username`='" . $student . "'") or die(mysql_error());
$row3 = mysql_fetch_array($select3);
while($row2 = mysql_fetch_array($select2)) {
$house=$row3[house];
echo "<tr><td><strong class=\"$house\">$student</strong></td></tr>";
}
echo "</table>"; }
?>
I miss look on your code, since it is mess, but disregard the mysqli and mysql thing, you want to show how many student in the teacher's classes.
<?php $select = mysql_query("SELECT * FROM `member_staff` WHERE `username`='$_SESSION[USR_LOGIN]' AND `status`='Active'");
$row = mysql_fetch_array($select);
$rows = mysql_num_rows($select);
$teaching = $row[teaching]; <--- This only get first row of the course, if you want multiple course under same username, you need to loop it.
if ($rows==0){echo "Sorry, you don't appear to be a professor.";}
else { ?>
<?php }
$select2 = mysql_query("SELECT * FROM `classes_enrolled` WHERE `course`='" . $teaching . "' ORDER BY `student_name`") or die(mysql_error());
$count = mysql_num_rows($select2);
$row2 = mysql_fetch_array($select2);
$student=$row2[student_name]; <----- This only get the first row of the student name, if you want multiple student under a course, you need to loop it.
if($count==NULL) {
echo "<table width=\"80%\">\n";
echo "<tr><td><center>Nobody has registered for your class yet!</center></td></tr>\n";
echo "</table>\n";
echo "<br /><br />\n\n";
}
else {
echo "<center><font size=\"3\"><b>YEAR 1, TERM 2</b></font></center>";
echo "<table width=\"80%\" class=\"table-stripes\">\n";
echo "<tr><td width=\"50%\"><b>STUDENT</b></td></tr>\n";
$select3 = mysql_query("SELECT * FROM `members` WHERE `username`='" . $student . "'") or die(mysql_error());
$row3 = mysql_fetch_array($select3);
while($row2 = mysql_fetch_array($select2)) {
$house=$row3[house]; <----This only show the first row of $house under same student, so you need to loop it too.
echo "<tr><td><strong class=\"$house\">$student</strong></td></tr>";
}
echo "</table>"; }
?>
So what you really want to do is
<?php
$select = mysql_query("SELECT * FROM `member_staff` WHERE `username`='$_SESSION[USR_LOGIN]' AND `status`='Active'");
$rows = mysql_num_rows($select);
if ($rows==0){echo "Sorry, you don't appear to be a professor.";}
else { ?>
<?php }
while( $row = mysqli_fetch_array( $select ) ) {
$teaching = $row[teaching];
$select2 = mysql_query("SELECT * FROM `classes_enrolled` WHERE `course`='" . $teaching . "' ORDER BY `student_name`") or die(mysql_error());
$count = mysql_num_rows($select2);
if($count==NULL) {
echo "<table width=\"80%\">\n";
echo "<tr><td><center>Nobody has registered for your class yet!</center></td></tr>\n";
echo "</table>\n";
echo "<br /><br />\n\n";
} else {
while( $row2 = mysql_fetch_array($select2) ) {
$student=$row2[student_name];
echo "<center><font size=\"3\"><b>YEAR 1, TERM 2</b></font></center>";
echo "<table width=\"80%\" class=\"table-stripes\">\n";
echo "<tr><td width=\"50%\"><b>STUDENT</b></td></tr>\n";
$select3 = mysql_query("SELECT * FROM `members` WHERE `username`='" . $student . "'") or die(mysql_error());
while($row3 = mysql_fetch_array($select3)) {
$house=$row3[house];
echo "<tr><td><strong class=\"$house\">$student</strong></td></tr>";
}
echo "</table>";
}
} // END ELSE
}
} // END ELSE
?>

mysql_fetch_array not fetching complete data?

I have a code which fetches data from a mysql table and converts it into pdf document, the code is working fine except it is skipping row 1.
Here is the code from which i have removed the pdf generation process since the problem is in the loop which is fetching data.
Please help.
<?php
session_start();
if(isset($_SESSION['user']))
{
$cr = $_POST['cour'];
$s = $_POST['sem'];
require('fpdf.php');
include('../includes/connection.php');
$sql = "SELECT * FROM `student` WHERE AppliedCourse ='$cr'";
$rs = mysql_query($sql) or die($sql. "<br/>".mysql_error());
if(!mysql_fetch_array($rs))
{
$_SESSION['db_error'] = "<h2><font color = 'RED'>No such course found! Pease select again.</font></h2>";
header('Location: prinrepo.php');
}
else {
for($i = 0;$i <= $row = mysql_fetch_array($rs);$i++)
{
$formno[$i] = $row ['FormNo'];
$rno[$i] = $row ['rollno'];
$snm[$i] = $row ['StudentNm'];
$fnm[$i] = $row ['FathersNm'];
$mnm[$i] = $row ['MothersNm'];
$addr[$i] = $row['Address'];
$pic[$i] = $row['imagenm'];
$comm[$i] = $row['SocialCat'];
echo $formno[$i]."<br />";
echo $rno[$i]."<br />";
echo $snm[$i]."<br />";
echo $fnm[$i]."<br />";
echo $mnm[$i]."<br />";
echo $addr[$i]."<br />";
echo $pic[$i]."<br />";
echo $comm[$i]."<br />";
echo "<br />";
}
}
mysql_close($con);
}
?>
You are fetching the first row outside of your for() loop then you miss it.
After mysql_query() your should use mysql_num_rows() to check if there are any rows in your result and then fetch them in the for loop.
More info here : http://php.net/manual/fr/function.mysql-num-rows.php
Your code would look like this :
$sql = "SELECT * FROM `student` WHERE AppliedCourse ='$cr'";
$rs = mysql_query($sql) or die($sql. "<br/>".mysql_error());
if(0 == mysql_num_rows($rs)) {
$_SESSION['db_error'] = "<h2><font color = 'RED'>No such course found! Pease select again.</font></h2>";
header('Location: prinrepo.php');
} else {
for($i = 0;$i <= $row = mysql_fetch_array($rs);$i++)
{
// Your code
}
}

Display current logged in user's profile

I've been working on code for student registration. I finished coding for my log in.
What I'm having a problem with is showing the user's profile: student fname, lname, program, gender and year level in textboxes. I'm using MySQL as my back end.
My code is like this:
<?php
// connects to the database
$mysqli = new mysqli("localhost", "root", "");
$query = 'SELECT fname, lname, program, gender, year FROM students WHERE fname = '.$_SESSION['myusername'];
$mysqli->query($query);
echo "<div align=\"center\">";
echo "<br />Your <b><i>Profile</i></b> is as follows:<br />";
echo "<b>First name:</b> ". $_POST['fname'];
echo "<br /><b>Last name:</b> ".$_POST['lname'];
echo "<br /><b>Program:</b> ".$_POST['program'];
echo "<br /><b>Year:</b> ".$_POST['year'];
echo "<br /><b>Gender:</b> ".$_POST['gender'];
echo "</div>";
?>
This is my code for mainstudent.php and checklogin.php.
Here you go:
<?php
session_start();
// connects to the database
$mysqli = new mysqli("localhost", "root", "");
$query = "SELECT fname, lname, program, gender, year FROM students WHERE fname = '".$_SESSION['myusername']."'";
if($result = $mysqli->query($query))
{
while($row = $result->fetch_assoc())
{
echo "<div align=\"center\">";
echo "<br />Your <b><i>Profile</i></b> is as follows:<br />";
echo "<b>First name:</b> ". $row['fname'];
echo "<br /><b>Last name:</b> ".$row['lname'];
echo "<br /><b>Program:</b> ".$row['program'];
echo "<br /><b>Year:</b> ".$row['year'];
echo "<br /><b>Gender:</b> ".$row['gender'];
echo "</div>"
}
$result->free();
}
else
{
echo "No results found";
}
?>
please add your password in session as well

MySQL return result if 0 rows returned

I have this PHP code:
$query = "SELECT name, COUNT(message) FROM guestbook_message WHERE name='".$req_user_info['username']."' GROUP BY name";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result))
{
echo "Messages posted: ". $row['COUNT(message)'] ."";
echo "<br />";
}
Which will show the amount of comments a user has posted.
How do I make it return a value if there is no messages posted from that user? Currently is displays nothing at all. But I want it to show "Messages posted: 0"
Any ideas?
Check the number of results returned in result using mysql_num_rows.
$query = "SELECT name, COUNT(message) FROM guestbook_message WHERE name='".$req_user_info['username']."' GROUP BY name";
$result = mysql_query($query) or die(mysql_error());
if(mysql_num_rows($result) > 0)
while($row = mysql_fetch_array($result))
{
echo "Messages posted: ". $row['COUNT(message)'] ."";
echo "<br />";
}
else
echo "NO Messages posted. <br />";
if ($row = mysql_fetch_array($result)) {
echo "Messages posted: ". $row['COUNT(message)'] . "";
echo "<br />";
}
else {
echo "Messages posted: 0";
echo "<br />";
}
Replace $row['COUNT(message)'] with the tertiary operator:
( $row['COUNT(message)'] > 0 ? $row['COUNT(message)'] : 0 )
This is basically a compacted if... else... statement.

Categories