Simple mysqli query not returning anything - php

I am almost certain that this is a boneheaded question with a very simple answer, but I've been knocking my brain against the desk for the last 30 minutes or so and figured it was time to ask for help.
I need to fetch the current highest existing keyID in the database. Simple! So I did this:
$newIDQ = "SELECT MAX(mediaKey) FROM `imd_media`";
$newIDResult = $con->query($newIDQ);
$row = mysqli_fetch_array($newIDResult);
echo "Highest ID should be: " . $row['mediaKey'];
But it never spits anything out in $row['mediaKey']. It's been awhile since I used mySQL for anything and this is my first tussle with mysqli, so I'm sure I'm just looking right past the answer or misunderstanding something.

$row[0] will do it I believe.
Always debug your code. Say, for your current problem print_r($row); can help

Try this:
$newIDQ = "SELECT MAX(mediaKey) AS mediaKey FROM `imd_media`"; // rename the result col
$newIDResult = $con->query($newIDQ);
$row = mysqli_fetch_array($newIDResult);
echo "Highest ID should be: " . $row['mediaKey'];
or this:
$newIDQ = "SELECT MAX(mediaKey) FROM `imd_media`";
$newIDResult = $con->query($newIDQ);
$row = mysqli_fetch_array($newIDResult);
echo "Highest ID should be: " . $row['MAX(mediaKey)']; // your probable current result

$newIDQ = "SELECT MAX(mediaKey) FROM 'imd_media'";
$newIDResult = $con->query($newIDQ);
$row = $newIDResult ->fetch_array(MYSQLI_ASSOC);
echo "Highest ID should be: " . $row['mediaKey'];`

Related

Compare a value to each row in the database table

Already solved. I just used WHERE MONTH(due_date) = $month in the SQL clause. Never knew it would just be like that. Thank you for all your answer!
We have a table called bills. We do not delete a bill even if it is paid already for record purposes.
So our goal is to only display The Bills for this Month. I have a $cur_month = current month value. I know how to extract the month value from a field using MONTH(), using a loop to run though the table, but when I try to echo MONTH(date) the value through out the displayed series is just the MONTH VALUE of the very first row. It seems it failed to get the MONTH VALUE of the other rows.
Fixed code below
$query = "SELECT * FROM bill WHERE MONTH(due_date)=$month";
$bresult = mysql_query($query);
while($brow = mysql_fetch_array($bresult, MYSQL_ASSOC))
{
$bdata = mysql_fetch_assoc(mysql_query("SELECT MONTH(due_date) AS M FROM `bill`"));
if($bdata['M'] == $month)
{
echo "<tr>";
echo "<td>".$brow['room_id']."</td>";
echo "<td>".$brow['tenant_id']."</td>";
echo "<td>".$brow['due_date']."</td>";
echo "</tr>";
}
}
$month there is the holder of the current month
$bdata['M'] there is the holder of the month extracted. We just displayed it to check.
So if extracted_month is equls to current_month then display bill
I hope you can help me in this.
PS: Still an amateur. This is not yet an online website. We only need help for the purpose of having it work.
1) Use a WHERE statement in your first SQL to only fetch those rows from the table.
Like this:
$query = "SELECT *, MONTH(due_date) as M FROM bill WHERE MONTH(due_date)=" . $month;
$bresult = mysql_query($query);
while($brow = mysql_fetch_array($bresult, MYSQL_ASSOC)) {
echo "<tr>";
echo "<td>".$brow['M']."</td>";
echo "<td>".$brow['tenant_id']."</td>";
echo "<td>".$brow['due_date']."</td>";
echo "</tr>";
}
2) I find it good practice to always check if the result object is created and if so, to check if it returned matches (with mysql_num_rows($result)). That way you can show an error if something goes wrong (most likely in the SQL statement) or show the user that there are no matches (bills in this case).
3) Try to use MYSQLI to connect to your database instead of MYSQL, since the latter is deprecated. (See: http://php.net/manual/en/mysqli-result.fetch-assoc.php for an example.)
Try solving this problem using SQL.
SELECT b.amount_paid
FROM bills b
WHERE MONTH(b.due_date) = 3
Using the result of this query you would have all of the amounts for this month. Sum your result and you are done.

Get values of each row

In my mysql tables I have for example a row that holds values, lets call this table "days" and the row "haircuts".
So I have 5 rows all with "1","2","3","4","5" under "haircuts". What I want to do, in php, is add them all together and echo. So it would maybe look like this:
echo "Total haircuts: ",$haircuts;
Which would hopefully show:
Total haircuts: 15
I can't figure out how, though. Here's how I'm currently doing it.
$getstats = mysqli_query($con,"SELECT * FROM stats");
$gotstats = mysqli_fetch_array($getstats);
$haircuts = $gotstats['haircuts'];
But it only echoes the "haircuts" of the first row? :(
I have multiple columns I would like to total and echo too if that is possible?
You can use the MySQL statment SUM in your query, just change your code by this one:
$getstats = mysqli_query($con,"SELECT SUM(haircuts) AS totalhaircuts FROM stats");
$gotstats = mysqli_fetch_array($getstats);
$totalhaircuts = $gotstats['totalhaircuts'];
echo "Total haircuts: ",$totalhaircuts;
You probably should use MySQL SUM().
SELECT SUM(haircuts) as tot_cuts FROM stats;
$gotstats['tot_cuts'];
You need to use loop for getting all rows. Example:
$getstats = mysqli_query($con,"SELECT * FROM stats");
while($gotstats = mysqli_fetch_array($getstats)){
$haircuts = $gotstats['haircuts'];
echo $haircuts . '<br />';
}

PHP multiple entries

I'm creating a small project with PHP/MYSQL but i can't get my query working the way i need it. I have 2 tables
Table 1 (char):
Id, name.
Table 2 (spells):
Id, char, spell_name.
I'm getting the output:
Name Spell1
Name Spell2
Name Spell3
But I need it to be:
Name Spell1
Spell2
Spell3
Here's my query:
$query = "SELECT char.name AS name, spells.spell_name AS spell
FROM char, spells
WHERE (char.id = spells.spell_name)";
Any ideas?
I think you're gonna have to first get the ID of the character to query, and then pull the spells s/he has access to. Example:
$char_id = 0; // value would be assigned arbitrarily.
$query = "SELECT *
FROM 'spells' s
WHERE s.char = $char_id;";
$result = $pdo->query($query);
while($row = $result->fetchObj()){
// do something with the spells obj here
}
With SQL, you need to grab full rows at a time, so I believe the situation you want isn't possible.
As Goldentoa11 wrote. Make two selects, or create query with two result sets (more selects in one command), or accept current state (is normal and you can verify data consistency). I prefer current state, but sometimes use any of described solution (based on query frequency, size of result etc.).
If you need to list such data, you can than use something like this:
$currentName = null;
while ($row = mysql_fetch_object($result))
{
if ($currentName != $row->name)
{
echo "<b>" . $row->name . "</b><br />";
$currentName = $row->name;
}
echo $row->spell_name . "<br />";
}

Issue retrieving SUM result from query

I have this query here which I use in order to get the sum of a certain column, however I keep getting the error Undefined index.
$sql_shuma="SELECT SUM(vlera) AS shuma "
."FROM servis_pjeset_perdorura "
."WHERE random = $random";
$resultshuma = odbc_exec($connection, $sql_shuma) or die(odbc_error());
while( $rowshuma = odbc_fetch_array($resultshuma) ) {
echo $total1 = $rowshuma['shuma'];
}
?>
What am I doing wrong here? Maybe it's the $total1 value, I don't know how to save the result.
Thanks
Is $random an integer? If not, you must use ' ' to delimit the string, like this:
$sql_shuma="SELECT SUM(vlera) AS shuma FROM servis_pjeset_perdorura WHERE random = '$random'";

Sql query only printing first row

I am coding in php and the code takes data from an array to fetch additional data from a mysql db. Because I need data from two different tables, I use nested while loops. But the code below always only prints out (echo "a: " . $data3[2]; or echo "b: " . $data3[2];) one time:
foreach($stuff as $key)
{
$query3 = "SELECT * FROM foobar WHERE id='$key'";
$result3 = MySQL_query($query3, $link_id);
while ($data3 = mysql_fetch_array($result3))
{
$query4 = "SELECT * FROM foobar_img WHERE id='$data3[0]'";
$result4 = MySQL_query($query4, $link_id);
while ($data4 = mysql_fetch_array($result4))
{
$x += 1;
if ($x % 3 == 0)
{
echo "a: " . $data3[2];
}
else
{
echo "b: " . $data3[2];
}
}
}
}
First and foremost, improve your SQL:
SELECT
img.*
FROM
foobar foo
INNER JOIN foobar_img img ON
foo.id = img.id
WHERE
foo.id = $key
You will only have to iterate through one array.
Also, it appears that you're actually only selecting one row, so spitting out one row is expected behavior.
Additionally, please prevent yourself from SQL injection by using mysql_real_escape_string():
$query3 = "SELECT * FROM foobar WHERE id='" .
mysql_real_escape_string($key) . "'";
Update: As Dan as intimated, please run this query in your MySQL console to get the result set back, so you know what you're playing with. When you limit the query to one ID, you're probably only pulling back one row. That being said, I have no idea how many $keys are in $stuff, but if it spins over once, then it will be one.
You may be better off iterating through $stuff and building out an IN clause for your SQL:
$key_array = "";
foreach($stuff as $key)
{
$key_array .= ",'" . mysql_real_escape_string($key) . "'";
}
$key_array = substr($key_array, 1);
...
WHERE foo.id IN ($key_array)
This will give you a result set with your complete list back, instead of sending a bunch of SELECT queries to the DB. Be kind to your DB and please use set-based operations when possible. MySQL will appreciate it.
I will also point out that it appears as if you're using text primary keys. Integer, incremental keys work best as PK's, and I highly suggest you use them!
You should use a JOIN between these two tables. It the correct way to use SQL, and it will work much faster. Doing an extra query inside the loop is bad practice, like putting loop-invariant code inside a loop.

Categories