I'm trying to run a PDO update statement, but none of the fields are being updated. Here is my PDO query. I've gone through and tried to find where the values were being changed and found that where being assigned nothing. I found the problem right when the values are escaped (You'll see my comment placed there). I know it probably something I'm overlooking but I haven't been able to figure out yet.
if(isset($_POST['submit']))
{
if(isset($_POST['name'])){ $name = $_POST['name'];}else{ $name = '';}
if(isset($_POST['city'])){ $city = $_POST['city'];}else{ $city = '';}
if(isset($_POST['state'])){ $state = $_POST['state'];}else{ $state = '';}
if(isset($_POST['address_line1'])){ $address_line1 = $_POST['address_line1'];}else{ $address_line1 = '';}
if(isset($_POST['address_line2'])){ $address_line2 = $_POST['address_line2'];}else{ $address_line2 = '';}
if(isset($_POST['city'])){ $city = $_POST['city'];}else{ $city = '';}
if(isset($_POST['state'])){ $state = $_POST['state'];}else{ $state = '';}
if(isset($_POST['zip_code'])){ $zip_code = $_POST['zip_code'];}else{ $zip_code = '';}
if(isset($_POST['last_modified_by'])){ $last_modified_by = $_POST['last_modified_by'];}else{ $last_modified_by = 'admin';}
$last_modified_date = date('Y-m-d H:i:s');
$confirmcode = 'y';
if(isset($_POST['bitactive'])){ $bitactive = $_POST['bitactive'];}else{ $bitactive = '';}
//Test portion 1 = Values are correct
// echo $address_line1 . "<p>";
// echo $city . "<p>";
// echo $zip_code . "<p>";
// exit;
$support_broker_id = $_GET['id'];
$user_exists = "SELECT * FROM lu_agency WHERE agency_id =". $support_broker_id;
$statement = $conn->query($sql);
$result = $statement->fetch();
$count = $statement->rowCount();
$name = $row['name'];
$address_line1 = $row['address_line1'];
$address_line2 = $row['address_line2'];
$city = $row['city'];
$state = $row['state'];
$zip_code = $row['zip_code'];
$last_modified_by = $row['last_modified_by'];
$last_modified_date = $row['last_modified_date'];
$bitactive = $row['bitactive'];
//Test portion two: Values are correct
// echo $address_line1 . "<p>";
// echo $city . "<p>";
// echo $zip_code . "<p>";
// exit;
if($count > 0)
{
$sqlupdate = "UPDATE lu_agency
SET name = :name,
address_line1 = :address_line1,
address_line2 = :address_line2,
city = :city,
state = :state,
zip_code = :zip_code,
last_modified_by = :last_modified_by,
last_modified_date = :last_modified_date,
bitactive = :bitactive
WHERE agency_id= ". $support_broker_id;
//Here is where only $city and $support_broker_id have values, the others don't show up
echo $address_line1 . "<p>";
echo $city . "<p>";
echo $zip_code . "<p>";
echo $support_broker_id . "<p>";
exit;
$preparedstmt = $conn->prepare($sqlupdate);
$preparedstmt->execute(
array(
':name'=>$name,
':address_line1'=>$address_line1,
':address_line2'=>$address_line2,
':city'=>$city,
':state'=>$state,
':zip_code'=>$zip_code,
':last_modified_by'=>$last_modified_by,
':last_modified_date'=>$last_modified_date,
':bitactive'=>$bitactive
)
);
header("Location: http://173.254.127.52/~avenuet7/supporttables.php?msg=1");
}
}
$row is undefined. It should be $result:
$result = $statement->fetch(PDO::FETCH_ASSOC); // you declared `$result` not `$row`
And why not use prepared statements all through out:
$user_exists = "SELECT * FROM lu_agency WHERE agency_id =". $support_broker_id; // still directly injecting?
Final look:
$support_broker_id = $_GET['id'];
$user_exists = "SELECT * FROM lu_agency WHERE agency_id = :support_broker_id ";
// not `$sql` use `$user_exists`!
$statement = $conn->prepare($user_exists);
$statement->bindParam(':support_broker_id', $support_broker_id);
$statement->execute();
$count = $statement->rowCount();
if($count > 0) {
$result = $statement->fetch(PDO::FETCH_ASSOC);
$sqlupdate = "
UPDATE lu_agency SET
name = :name,
address_line1 = :address_line1,
address_line2 = :address_line2,
city = :city,
state = :state,
zip_code = :zip_code,
last_modified_by = :last_modified_by,
last_modified_date = :last_modified_date,
bitactive = :bitactive
WHERE agency_id = :support_broker_id
";
$preparedstmt = $conn->prepare($sqlupdate);
$preparedstmt->execute(
array(
':name' => $result['name'],
':address_line1' => $result['address_line1'],
':address_line2' => $result['address_line2'],
':city' => $result['city'],
':state' => $result['state'],
':zip_code' => $result['zip_code'],
':last_modified_by' => $result['last_modified_by'],
':last_modified_date' => $result['last_modified_date'],
':bitactive' => $result['bitactive'],
':support_broker_id' => $support_broker_id,
));
header("Location: http://173.254.127.52/~avenuet7/supporttables.php?msg=1");
}
Sidenote: Always add this after making a connection:
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
Related
What is the best way to stop the script if there are no results????
The Upload the file that is created to a vender but I don't need to creat a file if there is no results,
I have a second question what is the best way to run this every hour between 8 am and 6 pm Monday through Friday?
I found a lot of information on this if using MySQL but we are using Microsoft SQL Server.
Thanks for the help!
<?php
$connect = odbc_connect("removed");
if (!$connect) {
exit("Connection Failed: " . $connect);
}
$gr_total = 0;
$gr_count = 0;
$sql = "
SELECT distinct
ltrim(rtrim(SO.ompCustomerOrganizationID))as customer
,ltrim(rtrim(left(cmoName,30))) as name
,left(ltrim(rtrim(cmoAddressLine2)),30) as address1
,ltrim(rtrim(cmoCity)) as city
,ltrim(rtrim(cmoState)) as state
,ltrim(rtrim(cmoPostCode)) as postal
, ltrim(rtrim(REPLACE(REPLACE(REPLACE(cmoPhoneNumber, '(', ''), ')', ''), '-', ''))) as phone
FROM m1_kf.dbo.SalesOrders SO
LEFT JOIN m1_kf.dbo.Organizations ON cmoOrganizationID = SO.ompCustomerOrganizationID
WHERE ompCreatedDate >='06-11-2017' and ompPaymentTermID in ('CN30','CTN30')
and UOMPSCHEDULENUMBER !=1 and ompOrderTotalBase > 1
";
$sql2 = "
select
ltrim(rtrim(ompCustomerOrganizationID)) as cust
,ltrim(rtrim(ompSalesOrderID)) as orderid
, right('00000000'+cast(cast(round(ompOrderTotalBase,0)as int) as varchar(8)),8) as num
,REPLACE(CONVERT(VARCHAR(10), ompRequestedShipDate, 1), '/', '') as reqship
,'030' as terms
,REPLACE(CONVERT(VARCHAR(10), ompRequestedShipDate, 1), '/', '') as ship
FROM m1_kf.dbo.SalesOrders SO
WHERE ompCreatedDate >='06-11-2017' and ompPaymentTermID in ('CN30','CTN30')
and UOMPSCHEDULENUMBER !=1 and ompOrderTotalBase > 1
order by SO.ompCustomerOrganizationID
";
$result = odbc_exec($connect, $sql);
if (!$result) {
exit("Error in SQL");
}
$mycount = 0;
$tradestyle = ' ';
$address2 = ' ';
$my_file = 'cit_order_upload.co';
$handle = fopen($my_file, 'w+') or die('Cannot open file: ' . $my_file);
while ($row = odbc_fetch_array($result)) {
$record_type = 'A';
$cit_cust_id = '1234';
$cust_num = $row['customer'];
$name = $row['name'];
$address = $row['address1'];
$city = $row['city'];
$state = $row['state'];
$postal = $row['postal'];
$phone = $row['phone'];
fprintf($handle, "%-4s%-2s%-1s%-15s%-30s%-30s%-30s%-17s%-2s%-9s%-10s", $cit_cust_id, $tradestyle, $record_type, $cust_num, $name, $address, $address2, $city, $state, $postal, $phone . "\n");
$mycount = $mycount + 1;
}
$results = odbc_exec($connect, $sql2);
if (!$results) {
exit("Error in SQL");
}
$mycount2 = 0;
$space1 = ' ';
$space6 = ' ';If the first while loop does not have any results then stop the script
$space12 = ' ';
$today = date("mdy");
echo "<table><tr>";
echo "<th>CustID</th>";
echo "<th>OrderId</th>";
echo "<th>Amount</th>";
echo "<th>TotalAmount</th>";
while ($row = odbc_fetch_array($results)) {
$client = '1234';
$trade = ' ';
$record_ty = 'R';
$cust = $row['cust'];
$orderid = $row['orderid'];
$num = $row['num'];
$reqship = $row['reqship'];
$terms = $row['terms'];
$ship = $row['ship'];
$mycount2 = $mycount2 + 1;
$gr_total = $gr_total + $row['num'];
$tradestyle = '99';
$custnum = '999999999999999';
$record = 'S';
$recordtype = '999999T999999999999999';
fprintf($handle, "%-4s%-1s%-1s%-15s%-22s%-8s%-1s%-6s%-3s%-6s", $client, $trade, $record_ty, $cust, $orderid, $num, $space1, $reqship, $terms, $ship . "\n");
echo "<tr><td>$cust </td>";
echo "<td> $orderid </td>";
echo "<td> $num </td>";
echo "<td> $gr_total </td></tr>";
}
fprintf($handle, "%-4s%-2s%-1s%-15s%06d%06d%-6s%012d", $client, $tradestyle, $record, $custnum, $mycount, $mycount2, $space6, $gr_total);
fprintf($handle, "\n");
fprintf($handle, "%-22s%06d%06d%-6s%012d%-12s%-6s", $recordtype, $mycount, $mycount2, $space6, $gr_total, $space12, $today);
fclose($handle);
?>
You already have this stop condition if query is unsuccessful, for handling case with no results modify it like below:
if (!$result) {
exit("Error in SQL");
}
if (0 === odbc_num_rows($result)) {
exit("No results");
}
Check the docs for OBDC_num_rows.
About your secondary question - cron utility is probably the most popular way to schedule jobs. Your crontab string should be like this:
* 8-18/1 * * 2,3,4,5 yourscript.php
Somebody solve my problem. Update query not work.
Error in Update query this step... Array to string conversion $query .= "image = '{$image}' "; ------------------------------------------------------------------------------------------------------------------------------------
if (isset($_POST['submit'])) {
$file = rand(1000,100000)."-".$_FILES['image']['name'];
$file_loc = $_FILES['image']['tmp_name'];
$folder="uploads/";
$new_file_name = strtolower($file);
$image =str_replace(' ','-',$new_file_name);
move_uploaded_file($file_loc,$folder.$image);
$firstname = $_POST["firstname"];
$lastname = $_POST["lastname"];
$address1 = $_POST["address1"];
$address2 = $_POST["address2"];
$city = $_POST["city"];
$state = $_POST["state"];
$zipcode = $_POST["zipcode"];
$email = $_POST["email"];
$country = $_POST["country"];
$phone = $_POST["phone"];
$image = $_FILES["image"];
$username = $_POST["username"];
$passwordold = $_POST["oldpassword"];
$passwordone = $_POST["passwordone"];
$passwordtwo = $_POST["passwordtwo"];
$sessions = $_SESSION['admin_id'];
$query = "UPDATE user SET ";
$query .= "firstname = '{$firstname}', ";
$query .= "lastname = '{$lastname}', ";
$query .= "addressone = '{$address1}', ";
$query .= "addresstwo = '{$address2}', ";
$query .= "city = '{$city}', ";
$query .= "state = '{$state}', ";
$query .= "zipcode = '{$zipcode}', ";
$query .= "email = '{$email}', ";
$query .= "country = '{$country}', ";
$query .= "phone = '{$phone}', ";
$query .= "image = {$image} ";
$query .= "WHERE id = {$sessions} ";
$query .= "LIMIT 1";
$result = mysqli_query($connection, $query);
echo "<pre>";
print_r($_FILES);
print_r($_POST);
echo "</pre>";
}
$_FILES["image"] is an array. You can only pass string in sql queries. May be you need to serialize the array and then store it in the database.
I'm using this query in my php file:
<?php
require_once("database/config.php");
$customerNr = $_POST['customer_nr'];
$customerUuid = '';
$name = '';
$query = "SELECT HEX(uuid) AS customer_uuid, name FROM customers
WHERE customer_number = :customerNr";
$sql = $db->prepare($query);
$sql->bindValue(":customerNr", $customerNr);
$sql->execute();
if ($row = $sql->fetch()) {
$name .= $row["name"];
$customerUuid .= $row["customer_uuid"];
}
When I use echo "$customerNr<br>$name<br>$customerUuid"; I can see all these data.Now I want to use $customerUuid in another query in the same php file but it's not working.
$addressUuid = '';
$street = '';
$zipCode = '';
$city = '';
$query = "SELECT HEX(uuid) AS address_uuid, street, zip_code, city
FROM addresses WHERE customer_uuid = UNHEX(:customerUuid)";
$sql = $db->prepare($query);
$sql->bindValue(":customerUuid", $customerUuid);
$sql->execute();
if ($row = $sql->fetch()) {
$street .= $row["street"];
$zipCode .= $row["zip_code"];
$city .= $row["city"];
$addressUuid .= $row["address_uuid"];
}
Could anybody help me how to prepare this query?
In my flex application, I have a form which retrieves data from an SQL table and displays it in the textinput:
<s:Form id="form" includeIn="ShoppingList" x="223" y="353"
creationComplete="form_creationCompleteHandler(event)" defaultButton="{button}">
<s:FormItem label="Name">
<s:TextInput id="textInput" text="{getAllShoppinglistResult.lastResult[0].name}"/>
<s:TextInput id="textInput1" text="{getAllShoppinglistResult.lastResult[1].name}"/>
<s:TextInput id="textInput2" text="{getAllShoppinglistResult.lastResult[2].name}"/>
<s:TextInput id="textInput3" text="{getAllShoppinglistResult.lastResult[3].name}"/>
</s:FormItem>
<s:Button id="button" label="Submit" click="button_clickHandler(event)"/>
</s:Form>
In this case, there is just 2 items in the SQL table, the other 2 text input fields of free.
I want to be able to type text into the textinput and it saves it to the server.
protected function button_clickHandler(event:MouseEvent):void
{
items.name = textInput.text;
createShoppinglistResult.token = shoppinglistService1.createShoppinglist(name);
}
protected function createShoppinglistResult_resultHandler(event:ResultEvent):void
{
}
I'm unsure as to what goes into the createShoppinglist..* function.
I know that the PHP service is correct as currently it does save it to the server but it just saves NULL, I want it to save the textinput. I know that if it were a datagrid I could use AddItem() for an Array Collection, but I don't know what I could use for a form?
Maybe that will help! regards aktell
Unfortunately looks a bit like a mess! Here is a Link were you can see it much better - just towards the bottom!
http://board.flashkit.com/board/showthread.php?828493-php-gt-gt-mySQL-not-returning-data-as-XML
<?php
// init.php
// Script:
// Connecting to the MySQL DataBase Server & a DataBase.
/* ------------------------------------------------------------------------------------------------------------------ */
// MySQL DataBase Server Variables.
$mysql_host = "localhost";
$mysql_user = "root";
$mysql_pass = "";
// DataBase Variable.
$db = 'webflash_createcartdb';
// Connect to MySQL DataBase Server.
$con = # mysql_connect("$mysql_host", "$mysql_user", "$mysql_pass")
or exit("Could not connect to MySQL DataBase Server! \n Select DB Error: " . # mysql_error());
$con = # mysql_select_db($db)
or exit( 'Can\'t select the Database is unavailable.' . # mysql_error());
return $con;
/* ------------------------------------------------------------------------------------------------------------------ */
?>
READ & WRITE:
// custInfoDetails.php
/* ------------------------------------------------------------------------------------------------------------------ */
header('Content-Type: text/xml');
/* ------------------------------------------------------------------------------------------------------------------ */
include("../Conn/init.php");
/* ------------------------------------------------------------------------------------------------------------------ /
// MAIN TABLE.
/ ------------------------------------------------------------------------------------------------------------------ */
if (isset($_POST['lastName'])) {
$title = $_POST['title'];
$firstName = $_POST['firstName'];
$middleName = $_POST['middleName'];
$lastName = $_POST['lastName'];
$fullName = $_POST['fullName'];
$no = $_POST['no'];
$street1 = $_POST['street1'];
$street2 = $_POST['street2'];
$zip = $_POST['zip'];
$suburb = $_POST['suburb'];
$city = $_POST['city'];
$state = $_POST['state'];
$country = $_POST['country'];
$email = $_POST['email'];
$userName = $_POST['userName'];
$password = $_POST['password'];
$userNameCopy = mysql_real_escape_string($_POST["userNameCopy"]);
$sql = 'INSERT INTO ' . $userNameCopy . '
(title, firstName, middleName, lastName, fullName, no, street1, street2, zip, suburb, city,
state, country, email, userName, password, now)
VALUES
("' . $title . '", "' . $firstName . '", "' . $middleName . '", "' . $lastName . '", "' . $fullName . '",
"' . $no . '", "' . $street1 . '", "' . $street2 . '", "' . $zip . '", "' . $suburb . '",
"' . $city . '", "' . $state . '", "' . $country . '", "' . $email . '",
"' . $userName . '", "' . $password . '", NOW() )';
$result = # mysql_query($sql);
if (!$result) { exit('Error performing the MAIN INSERT query.' . # mysql_error());
}
}
/* ------------------------------------------------------------------------------------------------------------------ */
$sql = "SELECT custcartinfoID, title, firstName, middleName, lastName, fullName, no, street1, street2,
zip, suburb, city, state, country, email, userName, password, now FROM ' . $userNameCopy . ' ";
$result = # mysql_query($sql);
if (!$result) {
$message = 'Invalid query: ' . # mysql_errno() . " : " . # mysql_error() . "\n";
$message .= 'Whole query: ' . $sql;
exit($message);
}
/* ------------------------------------------------------------------------------------------------------------------ /
// XML READOUT.
/ ------------------------------------------------------------------------------------------------------------------ */
$xml = new DomDocument('1.0', 'UTF-8');
$root = $xml->createElement('allMessages');
$root = $xml->appendChild($root);
$result = # mysql_query($sql);
if ($result) {
if ( # mysql_num_rows($result) > 0) {
while ($row = # mysql_fetch_array($result)) {
$custcartinfoID = $row['custcartinfoID'];
$title = $row['title'];
$firstName = $row['firstName'];
$middleName = $row['middleName'];
$lastName = $row['lastName'];
$fullName = $row['fullName'];
$no = $row['no'];
$street1 = $row['street1'];
$street2 = $row['street2'];
$zip = $row['zip'];
$suburb = $row['suburb'];
$city = $row['city'];
$state = $row['state'];
$country = $row['country'];
$email = $row['email'];
$userName = $row['userName'];
$password = $row['password'];
$now = $row['now'];
// Message Element OPEN Node.
$itemElement = $xml->createElement('message');
$itemElement = $root->appendChild($itemElement);
// First Field.
$idElement = $xml->createElement('custcartinfoID', $custcartinfoID);
$idElement = $itemElement->appendChild($idElement);
$titleElement = $xml->createElement('title', $title);
$titleElement = $itemElement->appendChild($titleElement);
$firstNameElement = $xml->createElement('firstName', $firstName);
$firstNameElement = $itemElement->appendChild($firstNameElement);
$middleNameElement = $xml->createElement('middleName', $middleName);
$middleNameElement = $itemElement->appendChild($middleNameElement);
$lastNameElement = $xml->createElement('lastName', $lastName);
$lastNameElement = $itemElement->appendChild($lastNameElement);
$fullNameElement = $xml->createElement('fullName', $fullName);
$fullNameElement = $itemElement->appendChild($fullNameElement);
$noElement = $xml->createElement('no', $no);
$noElement = $itemElement->appendChild($noElement);
$street1Element = $xml->createElement('street1', $street1);
$street1Element = $itemElement->appendChild($street1Element);
$street2Element = $xml->createElement('street2', $street2);
$street2Element = $itemElement->appendChild($street2Element);
$zipElement = $xml->createElement('zip', $zip);
$zipElement = $itemElement->appendChild($zipElement);
$suburbElement = $xml->createElement('suburb', $suburb);
$suburbElement = $itemElement->appendChild($suburbElement);
$cityElement = $xml->createElement('city', $city);
$cityElement = $itemElement->appendChild($cityElement);
$stateElement = $xml->createElement('state', $state);
$stateElement = $itemElement->appendChild($stateElement);
$countryElement = $xml->createElement('country', $country);
$countryElement = $itemElement->appendChild($countryElement);
$emailElement = $xml->createElement('email', $email);
$emailElement = $itemElement->appendChild($emailElement);
$userNameElement = $xml->createElement('userName', $userName);
$userNameElement = $itemElement->appendChild($userNameElement);
$passwordElement = $xml->createElement('password', $password);
$passwordElement = $itemElement->appendChild($passwordElement);
// Last Field.
$nowElement = $xml->createElement('now', $now);
$nowElement = $itemElement->appendChild($nowElement);
}
}
// Message Element CLOSING Node.
else {
$messageElement = $xml->createElement('message','There are no posts.');
$messageElement = $root->appendChild($messageElement);
}
}
else {
$messageElement = $xml->createElement('message', #mysql_error());
$messageElement = $root->appendChild($messageElement);
}
// Return the XML Document.
echo $xml->saveXML();
/* ------------------------------------------------------------------------------------------------------------------ */
// CLOSE DATABSE.
// Close DataBase Server Connection!
# mysql_close($con);
/* ------------------------------------------------------------------------------------------------------------------ */
?>
READ ONLY:
// select.php
/* ------------------------------------------------------------------------------------------------------------------ */
// First, this script uses the header() function to tell the web server that the return is going to be XML.
header('Content-Type: text/xml');
/* ------------------------------------------------------------------------------------------------------------------ */
// Connecting with MySQL DataBase Server & a DataBase.
include("init.php");
/* ------------------------------------------------------------------------------------------------------------------ /
// MAIN TABLE.
/ ------------------------------------------------------------------------------------------------------------------ */
// SELECT more than one Table !
/* $query="SELECT movie.movie_name, movietype.movietype_label FROM movie, movietype
WHERE movie.movie_type = movietype.movietype_id
AND movie.movie_year>1990
ORDER BY movie_type"; */
$sql = 'SELECT customerID, title, firstname, middlename, lastname, no, street1, street2, zip, suburb, city,
state, country, email, emailpriv, emailbus, url1, url2, note, now FROM customerdetails';
$result = # mysql_query($sql);
if (!$result) {
$message = 'Invalid query: ' . # mysql_errno() . " : " . # mysql_error() . "\n";
$message .= 'Whole query: ' . $sql;
exit($message);
}
/* ------------------------------------------------------------------------------------------------------------------ /
// XML READOUT.
/ ------------------------------------------------------------------------------------------------------------------ */
$xml = new DomDocument('1.0', 'UTF-8');
$root = $xml->createElement('customerDetails');
$root = $xml->appendChild($root);
$result = # mysql_query($sql);
if ($result) {
if ( # mysql_num_rows($result) > 0) {
while ($row = # mysql_fetch_array($result)) {
$customerID = $row['customerID'];
$title = $row['title'];
$firstname = $row['firstname'];
$middlename = $row['middlename'];
$lastname = $row['lastname'];
$no = $row['no'];
$street1 = $row['street1'];
$street2 = $row['street2'];
$zip = $row['zip'];
$suburb = $row['suburb'];
$city = $row['city'];
$state = $row['state'];
$country = $row['country'];
$email = $row['email'];
$emailpriv = $row['emailpriv'];
$emailbus = $row['emailbus'];
$url1 = $row['url1'];
$url2 = $row['url2'];
$note = $row['note'];
$now = $row['now'];
// Message Element OPEN Node.
$itemElement = $xml->createElement('information');
$itemElement = $root->appendChild($itemElement);
// First Field.
$idElement = $xml->createElement('customerID', $customerID);
$idElement = $itemElement->appendChild($idElement);
$titleElement = $xml->createElement('title', $title);
$titleElement = $itemElement->appendChild($titleElement);
$firstnameElement = $xml->createElement('firstname', $firstname);
$firstnameElement = $itemElement->appendChild($firstnameElement);
$middlenameElement = $xml->createElement('middlename', $middlename);
$middlenameElement = $itemElement->appendChild($middlenameElement);
$lastnameElement = $xml->createElement('lastname', $lastname);
$lastnameElement = $itemElement->appendChild($lastnameElement);
$noElement = $xml->createElement('no', $no);
$noElement = $itemElement->appendChild($noElement);
$street1Element = $xml->createElement('street1', $street1);
$street1Element = $itemElement->appendChild($street1Element);
$street2Element = $xml->createElement('street2', $street2);
$street2Element = $itemElement->appendChild($street2Element);
$zipElement = $xml->createElement('zip', $zip);
$zipElement = $itemElement->appendChild($zipElement);
$suburbElement = $xml->createElement('suburb', $suburb);
$suburbElement = $itemElement->appendChild($suburbElement);
$cityElement = $xml->createElement('city', $city);
$cityElement = $itemElement->appendChild($cityElement);
$stateElement = $xml->createElement('state', $state);
$stateElement = $itemElement->appendChild($stateElement);
$countryElement = $xml->createElement('country', $country);
$countryElement = $itemElement->appendChild($countryElement);
$emailElement = $xml->createElement('email', $email);
$emailElement = $itemElement->appendChild($emailElement);
$emailprivElement = $xml->createElement('emailpriv', $emailpriv);
$emailprivElement = $itemElement->appendChild($emailprivElement);
$emailbusElement = $xml->createElement('emailbus', $emailbus);
$emailbusElement = $itemElement->appendChild($emailbusElement);
$url1Element = $xml->createElement('url1', $url1);
$url1Element = $itemElement->appendChild($url1Element);
$url2Element = $xml->createElement('url2', $url2);
$url2Element = $itemElement->appendChild($url2Element);
$noteElement = $xml->createElement('note', $note);
$noteElement = $itemElement->appendChild($noteElement);
// Last Field.
$nowElement = $xml->createElement('now', $now);
$nowElement = $itemElement->appendChild($nowElement);
}
}
// Message Element CLOSING Node.
else {
$messageElement = $xml->createElement('information','There are no posts.');
$messageElement = $root>appendChild($messageElement);
}
}
else {
$messageElement = $xml->createElement('information', #mysql_error());
$messageElement = $root>appendChild($messageElement);
}
echo $xml->saveXML();
?>
I asked this question in http://codereview.stackexchange.com and they wanted me to post it here. I couldn't get this code to work at all. I switched from regular mysql to pdo which is more safer. Could someone tell me what I'm missing here. I've been struggling with it for couple of day, and I could find exact answer when I first searched this site.
$input = $_POST['input'];
$categories = $_POST['category'];
$state = $_POST['state'];
$zipcode = $_POST['zipcode'];
$qq = $db->prepare(" SELECT * FROM classified ")or die(print_r($qq->errorInfo(), true));
/*** execute the prepared statement ***/
$qq->execute();
/*** echo number of columns ***/
$rows = $qq->fetch(PDO::FETCH_NUM);
if ($rows>0){
$query = (" SELECT * FROM classified ");
$cond = array();
$params = array();
if (!empty($input)) {
$cond[] = "title = ?";
$params[] = $input;
}
if (!empty($categories)) {
$cond[] = "id_cat = ?";
$params[] = $categories;
}
if (!empty($state)) {
$cond[] = "id_state = ?";
$params[] = $state;
}
if (!empty($zipcode)) {
$cond[] = "zipcode = ?";
$params[] = $zipcode;
}
if (count($cond)) {
$query .= ' WHERE ' . implode(' AND ', $cond)or
die(print_r($query->errorInfo(),true));
}
$stmt = $db->prepare($query);
$stmt->execute($params);
$ro = $stmt->fetch(PDO::FETCH_NUM);
}
if ($ro > 0) {
foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row)
{
echo $row['title'];
echo $row['categories'];
echo $row['state'];
echo $row['zipcode'];
}
}
I think it's a good idea to post an answer here rather than posting a link. I'm sure it will be useful for some people.
$input = $_POST['input'];
$categories = $_POST['category'];
$state = $_POST['state'];
$zipcode = $_POST['zipcode'];
$qq = $db->prepare(" SELECT * FROM classified ")or die(print_r($qq->errorInfo(),
true));
/*** execute the prepared statement ***/
$qq->execute();
/*** echo number of columns ***/
$rows = $qq->fetch(PDO::FETCH_NUM);
if ($rows>0){
$query = " SELECT * FROM classified where confirm='0' ";
if(!empty( $_POST['input'])) {
$query .= "AND title LIKE '%".$input."%' ";
}
if (!empty($_POST['category']) )
{
$query .= "AND id_cat = ".$categories." ";
}
if (!empty($_POST['state']) )
{
$query .= "AND id_state = ".$state." ";
}
if(!empty($_POST['zipcode'])) {
$query .= "AND zipcode = ".$zipcode." ";
}
$query .= "ORDER BY date ";
}
$stmt = $db->prepare($query);
$stmt->execute($params);
$result = $stmt->fetchAll();
// $ro = $stmt->fetch(PDO::FETCH_NUM);
// it didn't work when I tried to count rows
if ($result > 0) {
foreach ($result as $row)
{
echo $row['title'];
echo $row['categories'];
echo $row['state'];
echo $row['zipcode'];
}
}else{
echo " No data available";
}