Return specific data from mysql string - php

I want to fetch some info from my database, and choose which of the info in the string, I want to display.
--- What I know so far ---
This code is showing me NULL value:
$ticketis = mysql_query("SELECT `module` FROM games ORDER BY `id` DESC LIMIT 1,1");
$showticket = mysql_fetch_assoc($ticketis);
$rest = mb_substr($showticket,0,30);
var_dump($rest);
AND this code is showing me the data-string I want to cut out specific data from:
$ticketis = mysql_query("SELECT `module` FROM games ORDER BY `id` DESC LIMIT 1,1");
$showticket = mysql_fetch_assoc($ticketis);
var_dump($showticket);
This is the return value of the above code:
array(1) { ["module"]=> string(11) "0.435264836" }
What I want is to cut out is the numbers and display these: 0.435264836
Anyone got a clue what I can do to make that happen?
Thank you!

Use this $showticket['module']
mysql_fetch_assoc returns an array, not just a single value. Since you're using mysql_fetch_assoc you get an associative array indexed by the column name, hence the ['module']. If you would use mysql_fetch_row you'd get a numeric index and thus have to use $showticket[0].
But please don't forget that all the mysql_* functions are deprecated and will be removed in future versions of PHP!

Thanks for your help. It seemed I had to use print_r to get the pure numbers from the string. My code ended up like this, combining Remo and FirstOne's suggestions. Thanks.
$ticketis = mysql_query("SELECT `module` FROM games ORDER BY `id` DESC LIMIT 1,1");
$showticket = mysql_fetch_assoc($ticketis);
print_r($showticket['module']);

Related

Get the last Id from database to a string/Int variable

I have to get the biggest id to a string or an int variable.
That is how I'm doing it:
$sql = "SELECT id FROM table ORDER BY id DESC LIMIT 1";
$list = mysql_query($sql) or die (mysql_error());
$lst = mysql_fetch_array($list);
$resId= $lst[0];
ResId is that variable.
Is this going to work?
Is there a better way to do it?
There is no AUTO_INCREACMENT!
If you don't auto increment or in any other way organize your id:s, there is no way to know which was the last one. (Unless you get the last inserted id when you're doing an insert query.)
Your query returns the greatest id, but if you haven't structured your code/table so that the greatest id is the last - then it won't return the last id obviously (oh well, it could).
As for your question if it will work. Why don't you simply try it out? You're much more likely to learn from trying your self than asking people for answers all the time.
If last id is the biggest id (as I see from your query), then you can also use:
$q = 'select max(id) as max_id from `b_iblock_element`';
$q_res = mysql_query($q);
$row = mysql_fetch_assoc($q_res);
$max_id = intval($row['max_id']);
And don't forget that mysql_* functions are deprecated and will be removed soon.

MYSQL Statement with Array Variable

So I have the following mysql statement saving to an array:
$sql = "SELECT did FROM did WHERE id = '$did_id'";
$result = mysqli_query($link, $sql, MYSQLI_STORE_RESULT);
while($row = $result->fetch_row()){
$did[] = $row;
}
That part works great. But now I need to take the values in the $did array and perform another lookup using the values in it. The way it works is we have users assigned to certain did's. So I find the did's that the user is assigned to (the $did array) and only show them results from another table based on those did values. I have no idea how this part works, but this is what my next statement needs to do:
SELECT * FROM log WHERE did_id = "the values in $did array"
Hope someone can help. I really appreciate it. I haven't really been able to find anything on it.
You can use php's join with mysql's IN to make comma separated strings you can also use implode , join() is an alias of implode();
SELECT * FROM log WHERE did_id IN( ".join(',',$did).")
One thing to mention here that your $did should contains ids in manner like
array("1","2","3"....)
So in your loop fetch first index that holds did column value
$did[] = $row[0];
Note: i assume did , did_id type is int or bigint

Can`t MAX() function be used with mysqli?

I can not find a proper answer to this question. I have a very simple code for making a query in mysql to select the row with the maximum value in a determined column (called popularity) from a table (called comments). Every row has a column named comment_id
here is the code:
$connect_error = 'Sorry, try again, there was a connection error';
$con = mysqli_connect('localhost','user_name','password') or die($connect_error);
mysqli_select_db($con, 'database') or die($connect_error);
$result = mysqli_query($con, "SELECT MAX(`popularity`) FROM `comments`");
while ($row = mysqli_fetch_assoc($result)) {
$most_popular = $row['comment_id'];
}
echo "most popular is: $most_popular";
mysqli_free_result($result);
mysqli_close($con);
the screen does not show a proper result. Can someone give me an advice in this regard?
Thank you
You are looking to display the comment_id field, but you don't have that in your SELECT query. You are only selecting the max popularity value, and nothing else.
Try this for your query:
SELECT comment_id FROM comments ORDER BY popularity DESC LIMIT 1
This is sorting your comments by popularity, and then just picking the top one.
Of course you can easily change that to select more columns or even a SELECT * if you want to be able to display other values in this record.
To select the row with max 'popularity' column use this query;
$result = mysqli_query($con, "SELECT * FROM `comments` ORDER BY `popularity` DESC LIMIT 1");
In case you want all sorted by popularity remove the LIMIT 1...
You need
SELECT MAX(`popularity`) AS comment_id FROM `comments`
This will give the column the correct name for the associated array.
You are trying to read the result from a column named comment_id when the result from your query will be named MAX(popularity)
Run this query in mysql "SELECT MAX(popularity) FROM comments" first.The output of this gives you the index to use with $row[index] ie first row which in this case the index will be popularity else just change $row[content_id] to $row[popularity]

Limit FOREACH in MySQL PDO query

I am using the below code to try and echo out the latest 5 entries on the MySQL table, I cannot, however seem able to figure how to limit the number of results, can anyone help me out by allowing me to limit the number of results to 5 rows?
<table>
<?php
require_once($_SERVER['DOCUMENT_ROOT'] . "/resources/pdo.php");
$q = "SELECT * FROM `content` ORDER BY `id`";
$query = $pdo->query($q);
$data = array_reverse($query->fetchAll());
foreach ($data as $row) {
echo "<tr><td>{$row['title']}</td><td>{$row['id']}</td></tr>";
}
?>
</table>
Thanks!
Please note that I am new to PHP and I need help so if this question isn't useful, help me because I have only just started this.
Use LIMIT clause in your SQL query:
SELECT * FROM `content` ORDER BY `id` DESC LIMIT 5
From the manual:
The LIMIT clause can be used to constrain the number of rows returned by the SELECT statement. LIMIT takes one or two numeric arguments, which must both be nonnegative integer constants (except when using prepared statements).
With two arguments, the first argument specifies the offset of the first row to return, and the second specifies the maximum number of rows to return. The offset of the initial row is 0 (not 1):
Use the LIMIT word:
SELECT * FROM `content` ORDER BY `id` DESC LIMIT 5
order by id desc to get rid of the array_reverse and limit 5 to cap the number of returned results.
$q = "SELECT * FROM `content` ORDER BY `id` DESC LIMIT 5";
...
$data = $query->fetchAll();
As a global guideline: when writing queries try to formulate them in such a way that the resultset is as close to what you need as possible, ie no extra sorting or filtering operations afterwards.
having the dbserver send data that you aren't going to use is a waste
having to resort/refilter data on the webserver costs webserver performance and, in the case of big resultsets, it can cost lots of memory as well
When pulling data from a database you normally set a LIMIT via the MySQL-query, instead of counting the loop-iterations when reading the returned data.
$q = "SELECT * FROM `content` ORDER BY `id` LIMIT 5";

Adding up values inside of a while loop

With the first query in the following code I am looking for the checkings made in Berlin under the game number two.
With the second query I want to give points for each of the checkings.
As you will see I am using the function SUM. But let's say that I have 2 checkings and the points for each checking are 50. Well, instead of echoing 100, with this code I echo 5050
What is wrong with it?
Thanks a lot
THE CODE IS CORRECTED AND WORKING, JUST IN CASE SOMEBODY NEEDS IT. Thanks to all
$querya = "SELECT * FROM checkins where gamesid=2 and city='Berlin'";
$resulta = mysql_query($querya) or die(mysql_error());
$sumOfPoints = 0;
while($rowa = mysql_fetch_array($resulta)){
$n = $rowa['venuesid'];
$queryb = "SELECT venuesid, SUM(points) as sumpoints from venues where venuesid='".$n."' GROUP BY venuesid ORDER BY venuesid";
$resultb = mysql_query($queryb) or die(mysql_error());
while($rowb = mysql_fetch_array($resultb)){
$sumOfPoints += $rowb['sumpoints'];
}
}
echo "Total points is $sumOfPoints<br/>";
Some suggestions
Use SUM(points) AS sum (only for clarity when use the sum)
Check that points are numerical fields not varchar.
points must be a string, you need to cast it
SUM(cast(points) as int)
and then follow Gaurav's point about labeling the compute
You're getting 5050 because your script is echoing 50 in two iterations of the loop.
From the looks of it, your second query's GROUP BY clause is not grouping on venuesid when it should be. So, first try changing your GROUP BY clause to:
GROUP BY venuesid
If that doesn't give you the result you're looking for, then you should try running your query directly against the database with a static value for venuesid to see what you get back from it, then perhaps update your question and we can take it from there.

Categories