Stack Overflow

Subscribe to Stack Overflow feed
most recent 30 from 2018-02-21T10:21:19Z
Updated: 4 hours 27 min ago

Retrieving specific blog post with query string using mysqli [duplicate]

Tue, 02/20/2018 - 10:07

This question already has an answer here:

I am just getting back into PHP programming and I'm trying to make a basic blog from scratch that has two core pages index.php and viewpost.php. Index.php displays the titles and descriptions of all blog posts and viewpost.php is used to display a specific blog post in full when clicked on. (Config.php stores the database connection.)

To do this I am using query strings to pass the postID of the post that was clicked on to viewpost.php so it can be displayed. However, when clicking on a blog post it is not being displayed.


<?php require('includes/config.php'); ?>

<head> <meta charset="utf-8"> <title>Blog</title> </head> <body> <div id="wrapper"> <?php $sql = "SELECT postID, postTitle, postDescription, postDate FROM blog_posts ORDER BY postID DESC"; $result = $conn->query($sql); if ($result->num_rows > 0) { while($row = $result->fetch_assoc()) { $postID = $row['postID']; $postTitle = $row['postTitle']; echo '<div>'; echo '<h1><a href="'.$postID.'">'.$postTitle.'</a></h1>'; echo '<p>Posted on '.date('jS M Y H:i:s', strtotime($row['postDate'])).'</p>'; echo '<p>'.$row['postDescription'].'</p>'; echo '<p><a href="'.$postID.'">Read More</a></p>'; echo '</div>'; } } $conn->close(); ?> </div> </body>

This is working fine and displays the blog title and a short post description as intended. The problem is displaying the whole of the post when clicking either link.


<?php require('includes/config.php'); $stmt = $conn->prepare('SELECT postID, postTitle, postContent, postDate FROM blog_posts WHERE postID = ?'); $stmt->bind_param('i', $id); $id = $_GET['id']; $stmt->execute(); $row = $stmt->fetch(); ?>

<html lang="en"> <head> <meta charset="utf-8"> <title>Blog - <?php echo $row['postTitle'];?></title> </head> <body> <div id="wrapper"> <h1>Blog</h1> <hr /> <p><a href="./">Blog Index</a></p> <?php echo '<div>'; echo '<h1>'.$row['postTitle'].'</h1>'; echo '<p>Posted on '.date('jS M Y', strtotime($row['postDate'])).'</p>'; echo '<p>'.$row['postContent'].'</p>'; echo '</div>'; ?> </div> </body>

From basic debugging by using variable echoing the $_GET['id'] is holding the current postID and when executing the prepared statement $row returns 1. But there seems to be nothing stored in $row['postID'], $row['postTitle'], $row['postContent'] and $row['postDate'] so the post itself doesn't get displayed.

No idea what the problem is probably something basic since I'm still rusty! Any help is appreciated.

Facing issue while calling post method from angular

Tue, 02/20/2018 - 10:05

I am calling post web api method from angular but getting below error: "Failed to load : Response for preflight has invalid HTTP status code 404" I have enabled allow for cross origin request.

See below code:

return"http://localhost:64575/api/Rules", { currentPage: 1, pageSize: 10, sortColumn: 'id', sortDirection: 'asc' }, requestOptions) .map(res=>res.json());

PHP MySQL Multiple Queries

Tue, 02/20/2018 - 10:03

I am trying to run multiple queries consecutively using MySql. This is the code i am trying to run.

$conn = new \mysqli($servername, $username, $password, $database); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } else if(!$conn){ echo "Connection Failed"; } else{ $this->emptyTable(); $index = 0; foreach($groups as $group){ $sql = "INSERT INTO `allowedgroups`(`id`, `groupname`) VALUES (".$index.",'".$group['groupname']."')"; $result = $conn->query($sql); $index++; }

the $conn object results in a successful connection and i believe the actual SQL itself is correct, however when this controller is hit, it returns this message:

Warning: mysqli::query(): Couldn't fetch mysqli and results in a 503.

Is there a better way of carrying out this function?


function to repeat same numbers y times

Tue, 02/20/2018 - 10:02

I am trying to write a function that returns the number x. y number of times. The function should be able to take in multiple 2d arrays. There will be only 2 elements per input array.

So for example: function([4,3][2,2][12,5]) //output should be exactly: 444, 22, 1212121212

I have solved most of the problem but I am stuck when x is a 2 digit number. would appreciate some help in solving this. I must return the solution as a string with a comma (' ,') that separates the different arrays. Here is my code as of now:

function repeatnumber(data){ var result = " "; for (var i = 0; i < data.length; i++){ if (Array.isArray(data[i])){ var x = data[i][0] var y = data[i][1] for(var j = 1; j <= y; j++){ result = result + x; } } } var number = result var answer = number.match(/(\d)\1*/g) return console.log(answer); } repeatnumber([[10, 2][11,1]])// DOESN'T WORK!! output must be: 1010,11 repeatnumber([[1, 2], [2, 3]]) //works repeatnumber([[1, 4], [3, 6], [9, 2]]) //works

Input user name and each user has their respective rights?

Tue, 02/20/2018 - 10:01

I am just learning Android, I input user name and each user has their respective rights.

For example,

  • User1 has the right of Purchase Order Entry and printed Recap Purchases.

  • User2 has Sales and Sales Recap.

    I want when User1 login will look for Purchase Order Entry and Recap Purchases while others are invisible, so also when User2 login that looks Sales and Recap Sales while others are invisible.

I've searched the Internet and there's no matching like I want. May I ask for a sample program ? Thank you in advance.

how to read xml files in python if the encoding is different than UTF-8

Tue, 02/20/2018 - 09:55

I am trying to read an xml file with different encoding. In case of UTF-8 it is working fine but in case of other formats like GB18030 or BIG5, it is throwing error like multi-byte encoding are not supported.

Please suggest a solution for this. Thanks in advance.

android : converting image uri return null

Tue, 02/20/2018 - 09:51

I am trying to converting selected image uri to real path but it returns null

Selected image uri = content://

onActivityResult returns resultcode= -1

code for onActivityResult

public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); System.out.println("requestCode "+requestCode); System.out.println("resultCode "+resultCode); if (requestCode == 1 && resultCode == RESULT_OK) { String picturePath=""; Cursor cursor = null; Uri selectedImage = data.getData(); try { String[] proj = { MediaStore.Images.Media.DATA }; cursor = this.getContentResolver().query(selectedImage, proj, null, null, null); int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); System.out.println("column index"+column_index); cursor.moveToFirst(); picturePath = cursor.getString(column_index); } finally { if (cursor != null) { cursor.close(); } } System.out.println("image URI "+selectedImage); System.out.println("Real file path "+picturePath); if(picturePath!=null) { TypedFile typedFile = new TypedFile("file", new File(picturePath)); } } }

I am using android emulator and nougat sdk

Saving hash as json and getting it back trouble in ruby on rails

Tue, 02/20/2018 - 09:34

I'm saving the result of this method to file in json format:

class VideosController < ApplicationController ... def getting_hash video = = 12 video.title = "How to make it work?" video.desc = "No idea..." video_hash = video_hash[] = {id:, title: video.title, desc: video.desc} write_to_file(video_hash) end ... end

So for saving to the file I use:

def write_to_file(model) path = "#{Rails.root}/public/my_file.cache" open(path, 'w') { |f| f.write(model.to_json) } end

Seems like vanilla, but when I use: read_from_file(my_file.cache)

def read_from_file(file_name) path = Rails.root + "public/#{file_name}" file = hash_to_return = JSON.parse(file) end

It returns not the hash, but an array!

NoMethodError (undefined method `id' for #<Array:0x007f1926325460>):

And when I check:

["12", {"id"=>"12", "title"=>"How to make it work?", "description"=>"No idea..."}]

I don't understand how is that possible, because if I use variables it makes everything perfect like:

(byebug) test = {"12":{"id":12,"title":"How to make it work?","desc":"No idea..."}} {:"12"=>{:id=>12, :title=>"How to make it work?", :desc=>"No idea..."}} (byebug) test2 = test.to_json "{\"12\":{\"id\":12,\"title\":\"How to make it work?\",\"desc\":\"No idea...\"}}" (byebug) JSON.parse(test2) {"12"=>{"id"=>12, "title"=>"How to make it work?", "desc"=>"No idea..."}}

Please, help me with getting correct hashes back! Any ideas are highly appreciated!


JSON::ParserError (lexical error: invalid char in json text. {"12"=>{:id=>"12", :title=> (right here) ------^ ):

UPDATE 2 my_file.cache's output: {"12":{"id":"12","title":"How to make it work?","description":"No idea..."},"14":{"id":"14","title":"Yoga","description":"Guide"}}

Adding new columns based to existing columns 's modalites with 0/1 values

Tue, 02/20/2018 - 09:29

Suppose that I have the column SENSIBILITE and TYPE_PEAU in the data.table DataIns.

> unique(DataIns$SENSIBILITE) [1] "Fréquente" "Occasionnelle" "Aucune" > unique(DataIns$TYPE_PEAU) [1] "Mixte" "Sèche" "Normale" "Grasse"

As you see, each column has many modalities. Then I want to create new columns based on its which have binary values according to the modalities for each observation. In another word, if I have:

> head(DataIns[,c("SENSIBILITE","TYPE_PEAU")]) SENSIBILITE TYPE_PEAU 1: Fréquente Mixte 2: Fréquente Mixte 3: Fréquente Sèche 4: Occasionnelle Mixte 5: Occasionnelle Mixte 6: Aucune Normale

I need to get as result:

> head(DataIns) TYPE_PEAU_M TYPE_PEAU_N TYPE_PEAU_S TYPE_PEAU_G SENSIBILITE_A SENSIBILITE_O SENSIBILITE_F 1: 1 0 0 0 0 0 1 2: 1 0 0 0 0 0 1 3: 0 0 1 0 0 0 1 4: 1 0 0 0 0 1 0 5: 1 0 0 0 0 1 0 6: 0 1 0 0 1 0 0

I get the result above using this code:

DataIns<-DataIns[,.(TYPE_PEAU_M=as.factor(ifelse(TYPE_PEAU=="Mixte", 1, 0)), TYPE_PEAU_N=as.factor(ifelse(TYPE_PEAU=="Normale", 1, 0)), TYPE_PEAU_S=as.factor(ifelse(TYPE_PEAU=="Sèche", 1, 0)), TYPE_PEAU_G=as.factor(ifelse(TYPE_PEAU=="Grasse", 1, 0)), SENSIBILITE_A=as.factor(ifelse(SENSIBILITE=="Aucune", 1, 0)), SENSIBILITE_O=as.factor(ifelse(SENSIBILITE=="Occasionnelle", 1, 0)), SENSIBILITE_F=as.factor(ifelse(SENSIBILITE=="Fréquente", 1, 0)))]

But I think that this method is very long when I have many columns and modalities! So I am searching for more quickly and automated way using data.table operations to get an efficient result.

Thank you for your suggestions!

Angular Filter pipe not working properly

Tue, 02/20/2018 - 09:14

I have first name and last name in two different columns in my database, so I had to bind it this way to show it as 1 in my table.

However my search function isn't working when I type in space between first and last name:

<tbody> <tr *ngFor="let e of employeelist | filter : searchByName"> <td>{{e.firstName}} {{e.lastName}}</td> import { Injectable, Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'filter' }) @Injectable() export class FilterEmployeesPipe implements PipeTransform { transform(value: any, input: string) { if (input) { input = input.toLowerCase(); //filter je filter() metod iz array.prototype.filter return value.filter(function (employee: any) { return ((employee.firstName.toLowerCase().indexOf(input)) && (employee.lastName.toLowerCase().indexOf(input))) > -1; }) } return value; } }

How to create table dynamically in SSRS

Tue, 02/20/2018 - 08:54

I am a beginner in SSRS and maybe this may sound easy, But I want to know on how to create table dynamically based on number of rows return in my dataset(select query).

If I have 5 rows it should be shown in 5 different table.

Example: Select query:

ID | Name | Age 01 | Mike | 10 02 | Mary | 12

Then in my ssrs:

ID | 01 Name | Mike Age | 10 ID | 02 Name | Mary Age | 12

JSon Request Modification

Tue, 02/20/2018 - 07:27

Need to modify my Json. I want to remove " before [ and ]

Current Request :

{"marital-status":"Single","hospitalisation":"["hello", "world"]","ill-health":false,"specialist-condidtions":"["HEADACHE", "PANIC ATTACK"]","smoker":false,"health-concerns":false}

Modified request :

{"marital-status":"Single","hospitalisation":["hello", "world"],"ill-health":false,"specialist-condidtions":["HEADACHE", "PANIC ATTACK"],"smoker":false,"health-concerns":false}

I tried using translate function fn:translate(req,'"[','[') but this replaced all my " as well as [.

Sitecore 8 - Replacing title to data-original-title attribute when adding links on rich text

Tue, 02/20/2018 - 06:43

I need to replace the title attribute generated when link is added on sitecore rich text. I'm new in sitecore. Any leads on how to do this? Is it possible?

Pidof command not working on terminal for android

Mon, 02/19/2018 - 22:14

I'm trying to use the pidof command but everytime I try, I get no output. Am I typing something wrong?


Picture of terminal

phaser.js - Display spinner while getting results

Mon, 02/19/2018 - 22:14

I have a small game written in phaser.js that retrieves a calculation result form a PHP file like this...

get('calculate.php', function(data) { result =,307, data[index].name, { font: '20px Arial' }) }

The issue is, if the calculation takes some time then things hang up and look like they are broken.

I am looking for a way to display a spinner gif whilst it is waiting for the results.

Does anybody have an example of this being done I can see?

Firebase increment double do infinite loop

Mon, 02/19/2018 - 22:13

I´m creating a method that do a work, it increment a value every time onComplete is finish, but it´s causing a infinite loop on that field in the chield, example : it finish oncomplete then execute the method and must increase 100 points, but it takes the points and keep increasing without finish, here is the method i did

private void addPoints(final String finalCurrentUserKey){ // Create a reference to the DB final FirebaseDatabase mDatabase = FirebaseDatabase.getInstance(); final DatabaseReference refPoints = mDatabase.getReference(Constants.FIRE_BASE_USER_DRIVER); final Double[] count = new Double[1]; refPoints.child(finalCurrentUserKey).addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { try { Double points = dataSnapshot.child("plusPoints").getValue(Double.class); if (points!=null) { count[0] = points+100; } else { count[0] = Double.valueOf(100); } } catch (Exception e){ e.printStackTrace(); } refPoints.child(finalCurrentUserKey).child("plusPoints").setValue(count[0]); } @Override public void onCancelled(DatabaseError databaseError) { } }); }

Any help will be awsome guys, thanks!

Did it create VM?

Mon, 02/19/2018 - 22:13

So i'm new to Azure - Registered about a hour ago. I created Free Trial account but connected my Card to it so i could get 200$ for Trial. +++ I tried to create UbuntuNC24 VM - Wanted to see its hash rate (NOT for CryptoCurrency).

Its very expensive VM ~ 9$/h but I got that 200$ for testing so I wanted to see how would it perform.

But when I created everything and clicked "Finis" or however that last button is called I got some API error. After that I refreshed page and it was on "Dashboard" as creating/starting... And then it disappeared from there.

I looked under VM in menu and on all Resources and its not there. Like I did not created it.

My question is - Did i create it and if I did where did it go? I guess it would be very expensive mistake to just leave it..

Its debit card with 2$ balance on it but I don't want to hog on VM if I'm not using it or to go in debt with Azure (if it's possible).

Android Google Maps slow loading

Mon, 02/19/2018 - 22:13

I am trying to load a simple google maps using support fragment. everything works properly but the initial load causes jank and skips frames. There is nothing in the activity apart from the google map fragment. Is there anything I am doing wrong here? Would appreciate your inputs


02-19 17:00:23.868 22747-22747/ I/MainActivity: onCreate: Start 02-19 17:00:23.908 22747-22747/ I/zzbz: Making Creator dynamically 02-19 17:00:23.913 22747-22747/ I/DynamiteModule: Considering local module and remote module 02-19 17:00:23.913 22747-22747/ I/DynamiteModule: Selected remote version of, version >= 18 02-19 17:00:23.943 22747-22747/ W/zygote64: Unsupported class loader 02-19 17:00:24.022 22747-22747/ I/Google Maps Android API: Google Play services client version: 11910000 02-19 17:00:24.031 22747-22747/ I/Google Maps Android API: Google Play services package version: 11975940 02-19 17:00:24.490 22747-22761/ I/zygote64: Do full code cache collection, code=110KB, data=101KB 02-19 17:00:24.490 22747-22761/ I/zygote64: After code cache collection, code=100KB, data=63KB 02-19 17:00:24.662 22747-22747/ I/MainActivity: onCreate: End 02-19 17:00:24.680 22747-22747/ I/Choreographer: Skipped 48 frames! The application may be doing too much work on its main thread. 02-19 17:00:24.741 22747-22747/ I/MainActivity: onMapReady:


public class MainActivity extends AppCompatActivity implements OnMapReadyCallback { @Override protected void onCreate(Bundle savedInstanceState) { Log.i("MainActivity", "onCreate: Start"); super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(; mapFragment.getMapAsync(this); Log.i("MainActivity", "onCreate: End"); } @Override public void onMapReady(GoogleMap googleMap) { Log.i("MainActivity", "onMapReady: "); LatLng sydney = new LatLng(-33.852, 151.211); googleMap.addMarker(new MarkerOptions().position(sydney) .title("Marker in Sydney")); googleMap.moveCamera(CameraUpdateFactory.newLatLng(sydney)); } }


<fragment xmlns:android="" xmlns:tools="" android:id="@+id/mapfrag" android:name="" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=""/>


//Google Maps dependency compile ''

Why does my UWP app crash when I live edit specific properties in XAML?

Mon, 02/19/2018 - 22:13

For instance, as soon as I delete the background/foreground/borderBrush value, the app crashes and debugging stops which I think due to the invalid value (empty string). Also with margin/padding set to 3 values only, e.g. padding="0 0 0" (VS doesn't even give me chance to complete what I'm typing!).

Is there anything I need to change or is this how XAML "live" editing supposed to work?

Gradle error - issue in Resources

Mon, 02/19/2018 - 22:13

I'm having this 4 error:

Error:java.util.concurrent.ExecutionException: Error while executing process Error while executing process

Error:Execution failed for task ':app:processDebugResources'.

Failed to execute aapt

Error:org.gradle.process.internal.ExecException: Process 'command

This is my gradel

apply plugin: '' android { compileSdkVersion 26 buildToolsVersion '26.0.2' aaptOptions.cruncherEnabled = false aaptOptions.useNewCruncher = false defaultConfig { applicationId "miguelcalado.restauracaofinal" minSdkVersion 15 targetSdkVersion 26 useLibrary 'org.apache.http.legacy' versionCode 31 versionName "5.3.6" testInstrumentationRunner "" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), '' } } sourceSets { main { java.srcDirs = ['src/main/java', 'src/main/java/2'] } } } dependencies { implementation '' compile 'com.amazonaws:aws-android-sdk-core:2.2.13' compile 'com.amazonaws:aws-android-sdk-cognito:2.2.13' compile 'com.amazonaws:aws-android-sdk-s3:2.2.13' compile 'com.amazonaws:aws-android-sdk-ddb:2.2.13' compile 'com.github.javiersantos:AppUpdater:2.6.1' compile fileTree(include: ['*.jar'], dir: 'libs') androidTestCompile('', { exclude group: '', module: 'support-annotations' }) //noinspection GradleCompatible compile '' compile '' compile '' compile '' compile '' compile 'com.github.bumptech.glide:glide:3.7.0' compile 'me.relex:circleindicator:1.2.2@aar' compile '' compile '' compile '' compile 'pl.droidsonroids.gif:android-gif-drawable:1.2.+' testCompile 'junit:junit:4.12' compile files('libs/picasso-2.5.2.jar') }