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])
Related
I'm trying to save with foreach
here is what i get from my form
Array
(
[mulai] => 2016-08-28
[akhir] => 2016-08-31
[keterangan] => remarks
[nip] => Array
(
[0] => 1004384
[1] => 1602744
[2] => 1501039
)
)
and then here is my saving query.
$jumlahrange = $this->db->query("SELECT DATEDIFF(day,'".$mulai."','".$akhir."') AS diff")->row();
$totaldata = count($nip);
$skrg = $this->db->query("SELECT GETDATE() tgl")->row();
for($x = 0;$x<=$totaldata;$x++)
{
for($y=0;$y<$jumlahrange->diff;$y++){
$this->db->query("INSERT INTO attendance
(Nip,AttendanceDate,InTime,OutTime,AttendanceCode,RosterCode,LocationCode,Remarks,CreatedDate,CreatedBy,ModifiedDate,ModifiedBy)
values(
'".$nip[$x]."',DATEADD(DAY,".$y.",'".$mulai."'),'','','P3','','','".$keterangan."','".$skrg->tgl."','$niplogin','','')
");
}
}
i have no problem with my save but i have empty field like this in my table. In row 10,11,12 . That row should not exist right?.
I using SqlServer 2008 and Codeigniter . I know i can use insert_batch, but i want use this way.
in your line for($x = 0;$x<=$totaldata;$x++) i'm pretty sure you wanted to write < instead of <=
To overcome these kind of issues you can use foreach loop instead
foreach($resourcedata as $value){
//your code goes here and you will get all array elements sequentially in **$value** variable
}
This one is right at your fingertips. $nip[$x] is null. Error log or dump and die on the first loop $nip[$x] and see what it returns. If it is in fact not null, then it might be a data type problem (string vs int).
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].
I am trying to build some sort of database class (all PDO). All my functions work up till now, but the insert statement runs twice. I really don't see where it goes wrong. When I run the code with some echoes in it, the echoes only appear once so I don't think that it actually gets executed twice...
When I use the getBind function with other statements it works perfectly fine so...
THE CODE
function insert ($p_sTable, $p_aCol, $p_aVal) {
$this->m_sQuery .= "INSERT INTO ".$p_sTable." (";
$queryCols = "";
foreach ($p_aCol as $col) { ... }
$this->m_sQuery .= $queryCols.") VALUES (";
$queryPlaceholders = "";
foreach ($p_aCol as $placeholder) {... }
foreach ($p_aVal as $p_aValtosave) { .... }
$this->m_sQuery .= $queryPlaceholders.")";
echo "m_sQuery:</br>".$this->m_sQuery;
echo "</br>print bindCol</br>";
print_r($this->m_aBindCol);
echo "</br>print bindVal</br>";
print_r($this->m_aBindVal);
return $this;
}
WHERE I CALL THE FUNCTION:
$db = Db::getConnection();
$arr = $db->insert("geprutsvanlisa",["kolom1","kolom2"], ["24", "24"])->getBind();
THE OUTPUT: m_sQuery:
INSERT INTO geprutsvanlisa (kolom1, kolom2) VALUES (:ikolom1, :ikolom2)
print bindCol
Array ( [0] => ikolom1 [1] => ikolom2 )
print bindVal
Array ( [0] => 24 [1] => 24 )
echo i:0
bindvalue(:ikolom1, 24)
echo i:1
bindvalue(:ikolom2, 24)
echo this ms query
INSERT INTO geprutsvanlisa (kolom1, kolom2) VALUES (:ikolom1, :ikolom2)
echo this bindcol Array ( [0] => ikolom1 [1] => ikolom2 )
echo this bindval Array ( [0] => 24 [1] => 24 )
I am trying to create an array from an mysql query,
It gets around 300 values from the database yet only the first value is stored in the array. when I echo the array it says: Array ( [0] => 0.99 ). What I'm trying to archieve is
Array ( [0] => 0.99 )
Array ( [1] => 0.25 )
etc.
$activering = mysql_query("SELECT tarieven.id, bundels.bundel_id, betaalmethodes.bet_id , bundels.psp_id, bundels.aanmeldkosten, bundels.maandelijkse_kosten, bundels.transactiekosten, bundels.batchkosten, psp.psp_naam, tarieven.percentage, tarieven.prijs, bundels.actief
FROM tarieven
INNER JOIN bundels
ON tarieven.bundel_id = bundels.bundel_id
INNER JOIN betaalmethodes
ON tarieven.bet_id = betaalmethodes.bet_id
INNER JOIN psp
ON bundels.psp_id = psp.psp_id");
if($activering === FALSE) { die(mysql_error()); } // to do better error handling
if ($result = mysql_fetch_array($activering)) {
$prijs = array($result['prijs']); }
It's probably something really easy but I just don't see it..
Try
while ($result = mysql_fetch_array($activering)) {
$prijs[] = array($result['prijs']);
}
your over writing the value(array) in hte loop so you only get the last one:
$prijs[] =$result['prijs']; }
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.