when I use $_POST, both the if and else statements are executed. But the weird thing is that only the foreach loop is executed and "Flag is 0" is printed to the screen. If I replace $Flag = 1 with $Flag = 0, in the else statement, the loop does not get executed. When I replace "isset($_POST['Back'])" with "1", again the loop does not execute and all is well. So how come both my else and my if statement execute when I use $_POST? Thank you for any input
File #1
$Flag = 0;
if (isset($_POST['Back']))
{ echo "Flag is 0";
$Value = sqlsrv_fetch_array(sqlsrv_query($dbhandle,'SELECT MAX([Protocol Branch]) FROM Import_Trial_Information'),SQLSRV_FETCH_NUMERIC);
$Value = $Value[0];
}
else {$Flag = 1; echo "Flag is 1"; }
if ($Flag)
{
foreach ($Database_Tables AS $Delete)
{
$Query = 'DELETE FROM Import_' . $Delete;
sqlsrv_query($dbhandle,$Query);
if ($Delete == 'Paper_Information') {$Protocol = array('','');}
else {$Protocol = array(',[Protocol Branch]',',1');}
$Query = 'INSERT INTO Import_' . $Delete . '([Paper ID]' . $Protocol[0] . ') VALUES (' . (string)$ID . $Protocol[1] .')';
sqlsrv_query($dbhandle,$Query);
}
$Value = 1;
}
File #2
<div id = "Back_Button">
<form action="Import_Article_Advanced.php" method = "POST"><button name = "Back" ID = "Back" Value = "Back">Return to Previous Page</button></form>
</div>
try this
if (isset($_POST['Back']) OR !empty($_POST['Back']) OR $_POST['Back']!="" )
{ echo "Flag is 0";
$Value = sqlsrv_fetch_array(sqlsrv_query($dbhandle,'SELECT MAX([Protocol Branch]) FROM Import_Trial_Information'),SQLSRV_FETCH_NUMERIC);
$Value = $Value[0];
}
else {$Flag = 1; echo "Flag is 1"; }
Related
I have a form with three fields that I want to read separately from the database
$_POST['wkNumer1'];
$_POST['wkNumer2'];
$_POST['wkNumer3'];
How can I read this data without repeating the same code 3 times? In this code, only the variable $wkNumer value will be change.
<?php
if (isset($_POST['show_diagram'])) {
$goodname = $_POST['htDriver'];
$wkNumer = $_POST['wkNumer1'];
// Table with data
$sql = "SELECT WorkingDay, OrderNo, NameFinish, Type FROM `status` where WEEK(WorkingDay) = :wknumer AND NameFinish = :nameFinish"; // SQL with parameters
$stmt = $conn->prepare($sql);
$stmt->bindParam("wknumer", $wkNumer);
$stmt->bindParam("nameFinish", $goodname);
$stmt->execute();
$OCSdatas = $stmt->fetchAll(PDO::FETCH_ASSOC);
$count = $stmt->rowCount();
$countWithoutE = 0;
$countE = 0;
foreach ($OCSdatas as $data) {
if ($data['Type'] != 'E') {
$countWithoutE = $countWithoutE + 1 ;
}
if ($data['Type'] == 'E') {
$countE = $countE + 1 ;
}
}
echo $goodname . '<br />';
echo $wkNumer . '<br />';
echo $countWithoutE . '<br>';
echo $countE . '<br>';
$countE = $countE/2;
$countTotal = $countWithoutE + $countE;
echo $countTotal/5 . '<br>';
echo $count/5;
}
?>
You can put the numbers inside an array and iterate through that array to execute the same code.
$goodname = $_POST['htDriver'];
// Add the numbers to an array which we can iterate
$numbers = [
$_POST['wkNumber1'],
$_POST['wkNumber2'],
$_POST['wkNumber3'],
];
// Prepare the statement only once before the loop and reuse it
$sql = "SELECT WorkingDay, OrderNo, NameFinish, Type FROM `status` where WEEK(WorkingDay) = :wknumer AND NameFinish = :nameFinish";
$stmt = $conn->prepare($sql);
// Loop through the numbers
foreach ($numbers as $number) {
// Add the current number
$stmt->bindParam("wknumer", $number);
$stmt->bindParam("nameFinish", $goodname);
$stmt->execute();
// Now have everything as you had before
$OCSdatas = $stmt->fetchAll(PDO::FETCH_ASSOC);
$count = $stmt->rowCount();
$countWithoutE = 0;
$countE = 0;
foreach ($OCSdatas as $data) {
if ($data['Type'] != 'E') {
$countWithoutE = $countWithoutE + 1 ;
}
if ($data['Type'] == 'E') {
$countE = $countE + 1 ;
}
}
echo $goodname . '<br />';
echo $wkNumer . '<br />';
echo $countWithoutE . '<br>';
echo $countE . '<br>';
$countE = $countE/2;
$countTotal = $countWithoutE + $countE;
echo $countTotal/5 . '<br>';
echo $count/5;
}
How does this work for you?
$workNumbers = array($_POST['wkNumer1'],$_POST['wkNumer2'],$_POST['wkNumer3']);
foreach($workNumbers as $wkNumer){
//Your Code block here
}
I need to output the response from the database in XML. So far I have gotten it to output this:
The outermost tag needs to match the name of the action query, it'll either be <courses> or <students>.
Here is my code:
<?php
require_once('./database.php');
if (isset($_GET['format'])) {
$format = filter_var($_GET['format']);
}
if (isset($_GET['action'])) {
$action = filter_var($_GET['action'], FILTER_SANITIZE_STRING);
$tableName = "sk_$action";
}
$query = "SELECT * FROM $tableName";
if (isset($_GET['course'])) {
$course = filter_input(INPUT_GET, 'course');
$query .= " WHERE courseID = :course";
}
function arrayToXml($arr, $i = 1, $flag = false)
{
$sp = "";
for ($j = 0; $j <= $i; $j++) {
$sp .= " ";
}
foreach ($arr as $key => $val) {
echo "$sp<" . $key . ">";
if ($i == 1) echo "\n";
if (is_array($val)) {
if (!$flag) {
echo "\n";
}
arrayToXml($val, $i + 5);
echo "$sp</" . $key . ">\n";
} else {
echo "$val" . "</" . $key . ">\n";
}
}
}
$statement = $db->prepare($query);
$statement->bindValue(':course', $course);
$statement->execute();
$response = $statement->fetchAll(PDO::FETCH_ASSOC);
$statement->closeCursor();
if ($format == 'json') {
echo json_encode($response);
}
if ($format == 'xml') {
arrayToXml($response, 1, true);
}
I'm pretty new to PHP and have never worked with XML. All help is appreciated. Thanks.
function arrayToXml($arr, $collectionTag, $singleTag) {
$collection = new SimpleXMLElement("<$collectionTag/>");
foreach ($arr as $row) {
$element = $root->addChild($singleTag);
foreach ($row as $tag => $value) {
$element->addChild($tag, $value);
}
}
return $collection;
}
$courses = arrayToXml($response, 'courses', 'course');
echo $courses->asXML();
Tested with PHP 7.1.23. Output:
<?xml version="1.0"?>
<courses>
<course><courseID>cs601</courseID><courseName>Web Application Development</courseName></course>
<course><courseId>cs602</courseId><courseName>Server-Side Application Development</courseName></course>
<course><courseId>cs701</courseId><courseName>Rich Internet Application Development</courseName></course>
</courses>
(I added newlines because by default it doesn't add any.)
I have the following small code which manipulate tweets data. I expect my loop to iterate 10 times. However, what happens is that it iterates only once and then exits, with no sign of any error relating to MySQL or otherwise.
$query = "select data from tweets where `screen_name` = 'username' limit 10";
$tweetsq = mysqli_query($mysqli, $query) or die(mysqli_error($mysqli));
$tweets = mysqli_fetch_assoc($tweetsq);
$tweets_count = mysqli_num_rows($tweetsq);
echo $tweets_count . '<br />'; //See output
$count = 0;
foreach ($tweets as $raw_tweet) {
$tweet = json_decode($raw_tweet);
$tweet_id = $tweet->id_str;
$is_reply = (isset($tweet->in_reply_to_screen_name) && strlen($tweet->in_reply_to_screen_name) > 0) ? 1 : 0;
$is_retweet = (isset($tweet->retweeted_status) && $tweet->retweeted_status != '') ? 1 : 0;
$entity_holder = array();
$has_hashtag = $has_url = $has_mention = $has_media = 0;
foreach ($tweet->entities as $type => $entity) {
if (is_array($entity) && count($entity) < 1) {
//continue;
} else {
$entity = array_pop($entity);
switch ($type) {
case 'hashtags' : $has_hashtag = 1; break;
case 'urls' : $has_url = 1; break;
case 'user_mentions' : $has_mention = 1; break;
case 'media' : $has_media = 1; break;
default :
}
}
}
echo 'Updating recorde... <br />';
$query = "UPDATE tweets SET is_reply='" . $is_reply . "' , is_retweet='" . $is_retweet . "', has_hashtag='" . $has_hashtag . "', has_url='" . $has_url . "', has_mention='" . $has_mention . "', has_media='" . $has_media . "' WHERE tweet_id='" . $tweet_id . "'";
$result = mysqli_query($mysqli, $query) or die(mysqli_error($mysqli));
var_dump($result); //See output
$count++;
echo '<br />';
}
echo $count;
Output:
10 //This is the value of $tweets_count
Updating recorde...
bool(true) //The result of the UPDATE query
1 //The value of $count at the end of script. It SHOULD be 10
mysqli_fetch_assoc fetches a single row as an associative array where the key is the column name and the value is the column value. The correct way to use it would be to iterate over the result set until the fetch returns NULL, indicating that there are no more rows to fetch:
while ($row = mysqli_fetch_assoc($tweetsq)) {
$raw_tweet = $row["data"];
$tweet = json_decode($raw_tweet);
$tweet_id = $tweet->id_str;
# etc...
I want to run this code :
if ($_GET['CHOOSE'] == 1)
{
$field = " 'col1' ";
}
else
{
$field = " 'col2 ' ";
}
echo mysql_result($result,0,$field);
unfortunately I got false ??
Try this
if ($_GET['CHOOSE'] == 1)
{
$field = "col1";
}
else
{
$field = "col2";
}
echo mysql_result($result,0,$field);
I want to take an array I build from a result set, encode it and then put it into a single object. My problem is I am making a lot of objects, but I want all my data to be in one object. The problem is that I echo out multiple objects from my json encode on my foreach loop. How would I take all that data I get out of that foreach loop and put it into one object? Any help is appreciated. Below is my code. Basically, what I need is this.
{"item1":"itemdata","category":"mycategory"}
but all in one object. I don't want multiple {} {} {}
$counter = 0;
$itemID = '';
foreach ($resultsTwo as $result) {
if ($counter >= 0 && $itemID != $result['item_id']) {
$description = $result['item_desc'];
$ID = substr($result['item_id'], 3, 6);
if ($result['bidder'] == 9999999999) {
$bid = $result['amount_bid'] + $result['min_bid_increment'];
} else {
$bid = preg_replace('~\.0+$~','',$result['amount_bid']);
}
//echo $ID . ' ' . $bid . '<br />';
$build['bid'] = $bid;
$build['id'] = $ID;
$build['item_desc'] = $description;
}
$itemID = $result['item_id'];
$counter++;
echo json_encode($build);
}
Create an array to hold the smaller arrays before your loop.
$fullData = array();
Then, inside your loop after you finish your build array add the build array to the fullData array.
$fullData[] = $build;
remove your current json_encode() and then, outside the loop.
echo json_encode($fullData);
This is what it would be changed to:
<?php
$counter = 0;
$itemID = '';
$fullData = array();
foreach ($resultsTwo as $result) {
if ($counter >= 0 && $itemID != $result['item_id']) {
$description = $result['item_desc'];
$ID = substr($result['item_id'], 3, 6);
if ($result['bidder'] == 9999999999) {
$bid = $result['amount_bid'] + $result['min_bid_increment'];
} else {
$bid = preg_replace('~\.0+$~','',$result['amount_bid']);
}
//echo $ID . ' ' . $bid . '<br />';
$build['bid'] = $bid;
$build['id'] = $ID;
$build['item_desc'] = $description;
}
$itemID = $result['item_id'];
$counter++;
$fullData[] = $build;
}
echo json_encode($fullData);
?>
Change this
$counter = 0;
$itemID = '';
foreach ($resultsTwo as $result) {
if ($counter >= 0 && $itemID != $result['item_id']) {
$description = $result['item_desc'];
$ID = substr($result['item_id'], 3, 6);
if ($result['bidder'] == 9999999999) {
$bid = $result['amount_bid'] + $result['min_bid_increment'];
} else {
$bid = preg_replace('~\.0+$~','',$result['amount_bid']);
}
//echo $ID . ' ' . $bid . '<br />';
$build['bid'] = $bid;
$build['id'] = $ID;
$build['item_desc'] = $description;
}
$itemID = $result['item_id'];
$counter++;
echo json_encode($build);
}
To
$counter = 0;
$itemID = '';
foreach ($resultsTwo as $result) {
if ($counter >= 0 && $itemID != $result['item_id']) {
$description = $result['item_desc'];
$ID = substr($result['item_id'], 3, 6);
if ($result['bidder'] == 9999999999) {
$bid = $result['amount_bid'] + $result['min_bid_increment'];
} else {
$bid = preg_replace('~\.0+$~','',$result['amount_bid']);
}
//echo $ID . ' ' . $bid . '<br />';
$build[] = array('bid'=>$bid,'id'=>$ID,'item_desc'=>$description);
}
$itemID = $result['item_id'];
$counter++;
}
echo json_encode($build);