I'm trying to pull information from my database, but the query I'm using is only pulling all of the values after the first one. I have no LIMIT set, but I did try setting a LIMIT 0,30 with no change. In phpMyAdmin, the query returns what I expect. In my PHP file, it returns what I've explained.
The query is :
SELECT * FROM `mainSite_others` WHERE forGame='$gameName'
gameName is previously provided, and I suspect no errors because it does return at least two values. The forGame value in the database is all the same, a constant "+Stellar+Dawn".
The PHP code is:
while ($gameOther = $database->fetchArray($gameOtherQry)) {
echo $gameOther['otherName'];
}
Don't worry about the $database->fetchArray part, that is just my DB class, which works fine as far as I know.
The table I am extracting from looks like this (this is with all the values contained):
id | forGame | otherType | otherName | otherDesc
9 | +Stellar+Dawn | Character | Car | Car
10 | +Stellar+Dawn | Item | Brugson Burson | a guy
11 | +Stellar+Dawn | Item | Space Pie | A pie from space
I am using mySQLi.
Any ideas? Thank you.
You're probably doing a fetch call BEFORE you reach the while loop, which "loses" the first row of the results.
Related
Here i use a query for getting last two collision occurring dates of a licence number as follows:
<?php
$licence=$_POST['licence'];
$sel=mysqli_query($con,"select cdate from tblcollision where licence_number='$licence'");
while($s=mysqli_fetch_row($sel))
{
echo $s[2];
}
?>
I wish to split the result in to separate fields. That means date1 in a text field and date2 in another text field. Actually i didn't get any idea. Please help me.
My db design is
+--------------------------------------------------+
| CID | ID | LICENCE_NUMBER | CDATE |
+--------------------------------------------------+
| 1 | 1 | 3/4858/2012 | 2018-02-06 |
| 2 | 1 | 3/4858/2012 | 2018-03-20 |
+--------------------------------------------------+
As stated by mickmackusa, if the query is filtered for a single licence number, there is no point to group result in the SQL statement and then explode the result in PHP. Just read the rows and make the calculation on the resulting dates.
However, in a more general way, if dealing with several licences, grouping can be done within the SQL statement. Despite the added cost of exploding the result, it will simplify the grouping process.
You need to use GROUP_CONCAT in your query:
SELECT licence_number, GROUP_CONCAT(cdate) AS Events_dates
FROM tblcollision
WHERE licence_number='$licence'
GROUP BY licence_number;
This will return:
3/4858/2012 | 2018-02-06, 2018-03-20
I can't find anything about dynamically referencing a MySQL table entry in my particular case. Most everything I've read leans towards it not being possible, but I'm hoping someone can prove me wrong.
Essentially, I've got multiple MySQL tables that I'm trying to pull data from on an Android app. I want to access 2 at a time. The 1st Table's name always stays the same, history. The 2nd Table's name, however, may be different at times. It's value is determined within the app and referenced with :job in my php script (I'll use moon for my example). The 2nd table itself is generated dynamically through the app, so I guess I'm trying to set up a reference within a php script I have saved to a server so that I can access the 2nd Table.
Sorry for the confusing description, I hope these tables will help explain what I'm trying to get at.
Table #1: history (always stays the same)
| site | code | hours|
|---------|---------|------|
| moon | first | 1 |
| moon | second | 2 |
| moon | third | 3 |
| earth | fourth | 4 |
Table #2: moon (this one I want to dynamically reference)
| code | hours|
|---------|------|
| first | 10 |
| second | 11 |
| third | 12 |
And my current code:
...
/*** Table #1 ***/
SELECT code,
SUM(hours) AS total, '' AS target
FROM history
WHERE site = :job /* :job ends up being moon in this example */
GROUP BY code
UNION ALL
/*** Table #2 ***/
SELECT code,
'' AS total, SUM(hours) AS target
FROM :job /* <--- I'm trying to do something along these lines and use 'moon', or 'earth', or whatever... */
GROUP BY code
...
And later I get :job from the app: (moon)
$query_params = array(
':job' => $_POST['jobname'],
);
Result I'm Looking For: (works perfect if I directly use Table #2's name (ie moon) in my php file)
| code | hours|target|
|---------|------|------|
| first | 1 | 10 |
| second | 2 | 11 |
| third | 3 | 12 |
The code absolutely works as expected when I replace the :job in the 2nd table with the actual name of the table. I'm wondering if there is some way to still do it dynamically though?
Thanks for any and all advice!
I've done some pretty extensive searching and haven't come up with anything that works for me.
Is it possible to reference a mysql table entry value from a second table entry dynamically?
https://dev.mysql.com/doc/refman/5.7/en/derived-tables.html
MySQL table.* AS reference
Retrieve parent-child hierarchy from a self-referencing mysql table
I'm stumped. Consider the following test table:
----------------
| art_projects |
----------------------------------
| project_name | project_creator |
|--------------|-----------------|
| Flying Feet | 1 |
| Dinosaurs | 2 |
| Roadblock | 1 |
----------------------------------
Paired with it, consider the following code (where $db is a confirmed-functional PDO instance):
$dbObj = $db->prepare("SELECT * FROM art_projects WHERE project_creator = ?");
$dbObj->execute([1]);
print_r($dbObj->fetchAll(PDO::FETCH_ASSOC));
Very simple, very little can go wrong. This functions as expected and returns the following result set:
----------------------------------
| project_name | project_creator |
|--------------|-----------------|
| Flying Feet | 1 |
| Roadblock | 1 |
----------------------------------
Here's where the problem starts. If I change the execute() to search for ID 2 instead of 1, I'd expect it would return a single-row result for Dinosaurs. It doesn't - I get this instead:
1
When I change $dbObj->fetchAll(...) to $dbObj->fetch(...), though, I get the expected single-row result. The heck...?
Now, I'm pretty new to PDO, but I'm assuming this is expected behavior; I can't seem to find anything about this being an "error", here or elsewhere on Google. Can someone explain this behavior to me?
Furthermore, is there an accepted/effective method to deal with this? IMHO, It's kind of a Catch-22 to test the length of the result set for the sake of using the right fetch method, and it's unreasonable to magically know when your result set is going to be single-row or multiple-row.
FETCH_ASSOC isn't a valid documented mode for PDO::FetchAll(). When it gets more than one result set row it's probably doing some sort of filling in of an associative array that wipes out the contents.
If I were you I'd loop and do the ordinary fetch() call once per row.
I'm trying to build audit logging for a website. What I want to do is allow existing MySQL queries to go in unchanged (if possible) to a PHP function which parses the data and stores it in the audit log table.
For example, if I have the query
UPDATE members SET name='Bob', age='40' WHERE memberId=123
then I'd like to be able to pull out the table name members, the rowId 123 and both column/data (as if key/value) pairs name:Bob and age:40.
If possible I'd like a solution which also allows for the alternative query format:
UPDATE members (name,age) VALUES ('Bob','40') WHERE memberId=123
These would then go into an audit log table which would look something like this:
+--------+---------+--------+-----+-----------+-----------+
| user | table | column | row | old_value | new_value |
+--------+---------+--------+-----+-----------+-----------+
| admin | members | name | 123 | Joe | Bob |
+--------+---------+--------+-----+-----------+-----------+
| admin | members | age | 123 | 32 | 40 |
+--------+---------+--------+-----+-----------+-----------+
Obviously to populate this table you can see why I need to extract the values. Ideally I'd like to do it from existing MySQL query strings, passed into my PHP function (to handle existing code), but if I need to implement new PHP functions I'm open to suggestions.
Regex seems both complicated and painful since I'd have to format it for each column name for every table. Is there any parsing solution for this problem out there?
I have a database with two identical tables (one containing values, and the other contains values/users). When reading the values I wish to take the two values and place them onto one row. In certain cases (for some columns) there is only a value and not a value/users-value, in these cases I wish for the returned value to be null.
To make things a bit more clear, here is an example;
Value table (Table1)
| id | CPU | Memory | Name |
|------+-------+--------+--------|
| 1 | 45 | 25 | Comp1 |
| 2 | 25 | 12.5 | Comp2 |
Value/Users table (Table2)
| id | CPU | Memory | Name |
|------+-------+--------+--------|
| 1_A | 22.5 | 12.5 | |
| 2_A | 5 | 2.5 | |
I do not for instance need to know the value of Name divided by the number of users. In order to differentiate these values from the rest, I have a table named colInfo that specifies which values DO exist in the second table using the variable columnName. (Note: I cannot modify the structure of the database).
When retrieving the data I use the following SQL Query;
SELECT t1.[NAME] as Value, t2.[UserValue]
FROM (SELECT * FROM TABLE1 WHERE ID = 1) t1
left join (SELECT [ID],
CASE(SELECT COUNT(*) FROM colInfo WHERE [columnName] LIKE 'NAME')
WHEN 0 THEN NULL
ELSE [NAME]
END as [UserValue] from t2 on LEFT(t2.Id,LEN(t2.Id)-1) = LEFT(t1.Id,LEN(t1.Id)-1)
(The reasoning behind the sub-select and the left join goes along with the fact that I cannot change the database structure)
When running this query in SQL Management Studio, I get the correct result;
| ID | Value | UserValue |
|----+-------+-----------|
| 1 | Comp1 | NULL |
But when running it from a php-site using odbc I get, instead of NULL, an empty string. I use the following code;
$query = $this->sqlFactory->getComputerStats($params,$ids);
$result = odbc_exec($this->conn, $query);
for ($j=1; $j<=$no_rows; $j++) {
odbc_fetch_row($result, $j);
if(!is_null(odbc_result($result,"UserValue"))){
echo odbc_result($result,"UserValue");
}
}
Using Developer Tools this will give me an empty string. If I instead echo $query and test this in the SQL environment I do get a NULL value.
How come the odbc_result will not parse the result as null?
EDIT: According to the documentation of odbc_result it should return null when the value of the SQL Query returns NULL. As can be seen in the documentation.
mainly this has to do with how php sees null. in php null is not a possible value for a datatype, but it itself is a datatype of its own.
so when retrieving data from the database, odbc sends a datatype as well as a value (possibly null) which then gets translated into php datatypes, thus no longer accomodating the notion of the database-null. the next-best thing for a string containing null being an empty string.
i think this post will help:
In PHP, what is the differences between NULL and setting a string to equal 2 single quotes