I have been fighting with this small line of code for about 2 hours now, researching with it and trying to figure out where I went wrong. After 9 hours of coding, I hit this little problem and now I'm in deep water. I have a 3800 line code at this point that relied on this and it's dead in the water.
The problem is that none of the final variables are coming back with any information, they're coming back entirely blank/null. When I try to assign "myname" with "$getranks['nickname']", it doesn't even do anything, even though my "print_r($getranks)" comes back with ALL of that information. I also tried fetch instead of fetchAll, but then I only get one result.
I took an old MYSQL website I made for a group on the internet which was subject to SQL Injection, so I remade it using PDO entirely. This is the problem I have.
Any help is much appreciated. I've got a headache and I'm going to go grab a late dinner while I wait for assistance. Thanks everyone.
The Code: "index.php"
$myid = $_SESSION['user'];
echo "User Session ID #" . $myid . ".<br><br>";
if(!empty($_SESSION['user'])) {
$checkrank = $db->prepare("SELECT * FROM logins WHERE id = :myid");
$checkrank->bindParam(':myid',$_SESSION['user']);
$checkrank->execute();
$getranks = $checkrank->fetchAll(PDO::FETCH_CLASS);
print_r($getranks);
$myname = $getranks['nickname'];
$mycallsign = $getranks['callsign'];
$mystatus = $getranks['status'];
$mycallnum = $getranks['callnumber'];
$myrank = $getranks['rank'];
$mynote = $getranks['note'];
$mybadge = $getranks['mybadge'];
echo "<br><br>Check rank passed, the query came back with information.<br/>";
echo "The session ID used to retrieve this information in the query was: " . $myid;
echo "<br> Your name is " . $myname . ".";
}
The Result:
User Session ID #0102.
Array ( [0] => stdClass Object ( [id] => 0102 [badge] => 201 [rank] => 6 [nickname] => Rodger Anderson [username] => MASKED [password] => MASKED [salt] => MASKED [email] => MASKED [note] => [callsign] => [profile] => http://www.MASKED.net/forums/member.php?MASKED [callnumber] => [status] => ) )
Check rank passed, the query came back with information.
The session ID used to retrieve this information in the query was: 0102
Your name is .
You are SESSION[0102]
Your name is [] and your badge number is #.
The OLD Code:
$myid = $_SESSION['user'];
echo "User Session ID #" . $myid . ".<br><br>";
if(!empty($_SESSION['user'])) {
$query = mysql_query("SELECT * FROM logins WHERE id = $myid");
$getranks = mysql_fetch_assoc($query);
$myname = $getranks['nickname'];
$mycallsign = $getranks['callsign'];
$mystatus = $getranks['status'];
$mycallnum = $getranks['callnumber'];
$myrank = $getranks['rank'];
$mynote = $getranks['note'];
$mybadge = $getranks['mybadge'];
echo "<br><br>Check rank passed, the query came back with information.<br/>";
echo "The session ID used to retrieve this information in the query was: " . $myid;
echo "<br> Your name is " . $myname . ".";
}
$getranks is an array of objects, not an associative array. Look at the results from your print_r($getranks).
You should be doing something like
$myname = $getranks[0]['nickname'];
Or use PDO::FETCH_ASSOC but even then you'll need the [0].
Related
Using EasyRdf, I want to fetch query result. I used below code in codeigniter:
$this->load->library('rdf');
EasyRdf_Namespace::set('rdf', 'http://www.w3.org/1999/02/22-rdf-syntax-ns');
EasyRdf_Namespace::set('srt', 'http://persuratan-semweb.dev/ontologies/surat.owl');
$sparql = new EasyRdf_Sparql_Client('http://localhost:3030/surat_single/sparql');
$query = "SELECT * WHERE { "
. "?surat rdf:type srt:Surat . "
. "?surat srt:sifat_surat ?sifat_surat . "
. "?surat srt:nomor_surat ?nomor_surat . }";
$result = $sparql->query($query);
echo "jumlah data: " . $result->numRows() . "<br>";
echo "<br>";
foreach ($result as $row) {
echo $row->sifat_surat . " " .$row->sifat_surat . " " . $row->nomor_surat ."<br>";
}
print_r($result);
The output I got are:
jumlah data: 0
EasyRdf_Sparql_Result Object (
[type:EasyRdf_Sparql_Result:private] => bindings
[boolean:EasyRdf_Sparql_Result:private] =>
[ordered:EasyRdf_Sparql_Result:private] =>
[distinct:EasyRdf_Sparql_Result:private] =>
[fields:EasyRdf_Sparql_Result:private] => Array (
[0] => surat
[1] => sifat_surat
[2] => nomor_surat
)
[storage:ArrayIterator:private] => Array ( )
)
I also try Joshua's solution given here, but got similar output. I also try my query in Fuseki endpoint (I'm using Fuseki triplestore) and got this result. I'm completely beginer in semantic web.
I don't know whether it's the answer or not, but these namespaces don't look right to me:
EasyRdf_Namespace::set('rdf', 'http://www.w3.org/1999/02/22-rdf-syntax-ns');
EasyRdf_Namespace::set('srt', 'http://persuratan-semweb.dev/ontologies/surat.owl');
The rdf namespace should have a # at the end, and you should probably have one for your OWL file, too:
EasyRdf_Namespace::set('rdf', 'http://www.w3.org/1999/02/22-rdf-syntax-ns#');
EasyRdf_Namespace::set('srt', 'http://persuratan-semweb.dev/ontologies/surat.owl#');
But that said, there's no reason you can't try a simpler query first. Why not just run
SELECT ?s ?p ?o { ?s ?p ?o }
to be sure that you can get results, and what the data is.
I am trying to search one word in my whole table.
So if you search Eminem, you have to get everything with the word Eminem.
I search
<?php
$sql="SELECT * FROM album WHERE albumartiest like '$zoek'";
$resultaatcolumn = Yii::app()->db->CreateCommand($sql)->queryAll();
if($resultaatcolumn != null){
$zoekresultaat[] = $resultaatcolumn;}
$sql="select * from album where albumnaam like '%$zoek%'";
$resultaatcolumn = Yii::app()->db->CreateCommand($sql)->queryAll();
if($resultaatcolumn != null){
$zoekresultaat[] = $resultaatcolumn;}
$sql="select * from album where albumartiest like '%$zoek%'";
$resultaatcolumn = Yii::app()->db->CreateCommand($sql)->queryAll();
if($resultaatcolumn != null){
$zoekresultaat[] = $resultaatcolumn;}
$sql="select * from album where albumgenre like '%$zoek%'";
$resultaatcolumn = Yii::app()->db->CreateCommand($sql)->queryAll();
if($resultaatcolumn != null){
$zoekresultaat[] = $resultaatcolumn;}
$sql="select * from album where albumafspeelijst like '%$zoek%'";
$resultaatcolumn = Yii::app()->db->CreateCommand($sql)->queryAll();
if($resultaatcolumn != null){
$zoekresultaat[] = $resultaatcolumn;}
It works, but not exactly how I want it.
The result is this:
Array ( [0] => Array ( [0] => Array ( [albumcode] => 45 [albumnaam] => recovery [albumafspeelijst] => ["Cold Wind Blows","Talkin' 2 Myself","On Fire","Won't Back Down","W.T.P.","Going Through Changes","Not Afraid","Seduction","No Love","Space Bound","Cinderella Man","To Life","So Bad","Almost Famous","Love The Way You Lie","You're Never Over",""] [albumartiest] => Eminem [albumgenre] => hip-hop [albumimage] => images\eminemrecovery.png [albumprijs] => 20 ) ) [1] => Array ( [0] => Array ( [albumcode] => 45 [albumnaam] => recovery [albumafspeelijst] => ["Cold Wind Blows","Talkin' 2 Myself","On Fire","Won't Back Down","W.T.P.","Going Through Changes","Not Afraid","Seduction","No Love","Space Bound","Cinderella Man","To Life","So Bad","Almost Famous","Love The Way You Lie","You're Never Over",""] [albumartiest] => Eminem [albumgenre] => hip-hop [albumimage] => images\eminemrecovery.png [albumprijs] => 20 ) ) )
that's okay, but what I want is take out variable's and use it.
is there a way that I can get variable's out of the array and use it?
If you guys want more information about my code please ask!
Try using this
Yii::app()->db->CreateCommand($sql)->setFetchMode(PDO::FETCH_OBJ)->queryAll()
This will give you an array of objects with column name as the properties.
Eg:-
foreach($result as $row)
{
echo $row->albumcode;
}
If you want to access the result set like an object you can use the native PHP class ArrayObject and provide the flag to indicate that.
$album = new ArrayObject($result, ArrayObject::ARRAY_AS_PROPS);
You can now access the results like the following:
$code = $album->albumcode;
$name = $album->albumnaam;
Hope this can guide you, happy coding!
uhhh just do
foreach($zoekresultaat as $key => $value) {
//do what I want with each seperate returened result. The array key is in $key and the result array is in $value
echo $value['albumcode'] . ' = '. $value['albumnaam'];
}
aka, basic php
And please for the security of your app, learn how to do prepared statements in yii
The way your query is now I could wipe your entire database
I'm trying to get some specific keys and values from the database. My database entries look like so:
id | name | description | value
------------------------------------------
1 | lang | default language | en
2 | date | date format | YYYY-MM-DD
I want to echo only my name and value fields. I've tried using a nested foreach loop, like so:
foreach($details as $key => $value)
{
foreach($value as $index => $row)
{
echo $index . " / " . $row . "<br />";
}
echo "<br />";
}
But that only echos:
id / 1
name / lang
description / default language
value / en
id / 2
name / date
description / date format
value / YYYY-MM-DD
However, when I add an offset, like so: $index[1], I get this like a instead of name, or e instead of description.
I've previously worked from while loops using mysql_fetch_array, but this would give me a repeated element (say a <tr>) whereas I simply need to extract the value of the field because this will be used to build a form for the user to manage.
Would anyone have a suggestion or different approach for me to do something of the sort ?
EDIT
The query comes from a class file:
// extracted from my queries.class.php
public function my_prefs()
{
global $db;
$query = "SELECT * FROM preferences WHERE value!=NULL";
return $db->select($query);
}
// extracted from the source file
$module_details = $query->my_prefs();
EDIT #2
Perhaps this will help you understand my needs:
foreach($module_details as $key => $value)
{
print_r($module_details);
}
returns:
Array
(
[0] => stdClass Object
(
[id] => 1
[name] => lang
[description] => default language
[value] => en
)
[1] => stdClass Object
(
[id] => 1
[name] => date
[description] => date format
[value] => YYYY-MM-DD
)
}
I need to access only lang / en and date / YYYY-MM-DD.
Sounds like you're looking for something like this:
$tmp = array();
foreach($details as $key => $value)
{
// "name" => "value" dictionary later access
$tmp[$value["name"]] = $value["value"];
echo $value["name"] . " = " . $value["name"]; // echos e.q. "date = YYYY-MM-DD"
echo "<br/>";
}
echo $tmp["date"]; // echos e.q. "YYYY-MM-DD"
Perhaps I misunderstood the question..
But I believe you are trying to access the specific column entry from the array. You can do this by using the keys you are outputting instead of using a numeric index.
foreach($details as $key => $value)
{
echo $value['name'];
echo $value['value'];
echo "<br />";
}
EDIT
If you want to limit the results from your query so you only have the fields you requested replace:
$query = "SELECT * FROM preferences WHERE value!=NULL";
with
$query = "SELECT name, value FROM preferences WHERE value!=NULL";
Finally got around to getting something to work. Here's what I did:
foreach($details as $row)
{
$name = $row->name;
$value = $row->value;
// In order to specify for checkboxes, select, radio, etc.
if($name == "lang")
{
// different info depending on the value
}
else
{
// do something generic here
}
}
Might not be an optimal option, but this works like I need it to work.
I have a table set up with a column titled has_sub which contains a tinyint value of 1 or 0 depending on whether the subcategory has another level or not. 1 = has another level and 0 = no other level.
The problem I am having is that I cannot seem to get my anchors hrefs to change depending on the has_sub field (please see the following code)
$dbc = mysql_connect($db_host,$db_user,$db_pass);
$sdb = mysql_select_db($db_database);
$category = mysql_real_escape_string($_GET['category']);
$query = "SELECT subcategory_name, has_sub FROM subcategories WHERE subcategory_parent = '$category'";
$result = mysql_query($query, $dbc)
or die (mysql_error($dbc));
while($row = mysql_fetch_array($result)) {
$subcatname = $row["subcategory_name"];
$hassub = $row["has_sub"];
if($hassub=='1')
echo "<li><a href='getsubsubs.php?category=$subcatname'>$subcatname</a></li>";
else
echo "<li><a href='listings.php?category=$subcatname'>$subcatname</a></li>";
}
As I am a beginner, chances are that I am missing something quite basic but can't seem to figure it out. I have been looking through the documentation to no avail. Many thanks in advance.
Result of print_r($row): (from OP comment)
Array (
[0] => Alarm Systems
[subcategory_name] => Alarm Systems
[1] => 0
[has_sub] => 0
)
Array (
[0] => Building Interiors and Services
[subcategory_name] => Building Interiors and Services
[1] => 1
[has_sub] => 1
)
shouldn't it be if($hassub == 1) instead of if($hassub=='1')
Everything is correct so check input on the database for errors.
You have a few minor errors in the if-else statement. You have the right idea, just a few of the characters need to be changed because the format you have arranged it in, is causing it to be recognized as something it is not. Another thing that would make everything a whole heck of a lot more organized, would be if you would pack everything that is in the if-else statement into a variable rather than just echoing it out.
Instead of:
if($hassub=='1')
echo "<li><a href='getsubsubs.php?category=$subcatname'>$subcatname</a></li>";
else
echo "<li><a href='listings.php?category=$subcatname'>$subcatname</a></li>";
Use Something like this:
if ($hassub == "1") {
$hassub_toggle = '<li>' . $subcatname . '</li>';
}
else {
$hassub_toggle = '<li>' . $subcatname . '</li>';
}
Now wherever you put the
<?php echo $hassub_toggle; ?>
You will get your result. I personally like putting things into variables in that fashion because it makes things very organized and it enables you to apply more things to your return before you echo it onto your page.
I've recently started working with PHP and SQLite and I'm having problems with PHP arrays (I think). This is the code I use:
<?php
$dbo = new SQLiteDatabase("rsc/db.sqlite");
$test = $dbo->arrayQuery("DROP TABLE users;");
$test = $dbo->arrayQuery("CREATE TABLE \"users\"(name text, avatar text);");
$test = $dbo->arrayQuery("INSERT INTO users(name, avatar) VALUES('zad0xsis', 'http://zad0xsis.net/');");
// get number of rows changed
$changes = $dbo->changes();
echo "<br />Rows changed: $changes<br />";
// Get and show inputted data
$tableArray = $dbo->arrayQuery("SELECT * FROM users;");
echo "Table Contents\n";
echo "<pre>\n";
print_r($tableArray);
echo "\n</pre>";
?>
And when showing the data (print_r($tableArray);) I get this array:
Array
(
[0] => Array
(
[0] => zad0xsis
[name] => zad0xsis
[1] => http://zad0xsis.net/
[avatar] => http://zad0xsis.net/
)
)
I don't know why the values are duplicated, like [0] and [name], but it shows the data. Now, when I try to do print_r($tableArray["name"]); I should get the value, but it doesn't prints anything :( What I'm doing wrong? Thanks!
it helps you to select both
$tableArray[0]
or
$tableArray['name'];
it's fine.
to your problem: You'll have to
print_r($tableArray[0]['name'])
or
print_r($tableArray[0][0])