Good Morning....
I am using php MySQL to store the students marks in database....
my database table is like this...
25 63 96 85 65
56 56 96 36 23
56 78 98 45 12
Now I am trying to display last two values from database table and wants to show anywhere else on my website...
I am using below code...
<?php
$q = "SELECT CONCAT (a) FROM record ORDER BY id DESC
LIMIT 1;";
$result = mysql_query($q);
$data = mysql_fetch_array($result);
echo $data[0];
?>
The above code display only last value....which is 12 above shown table...
I want to display both 45 and 12 from above shown table like this...
{45}==>{12}
Can anybody correct my code....
Thanks...
As Saitama pointed out in the comments, the mysql_* functions are deprecated. Best to use PDO or the mysqli_* functions as they will be supported in the future.
I mention it at the start because it's hugely important for both security and ongoing support.
That being said, you need to do two things in order to get your desired result. First, your query must return more than 1 value, so the LIMIT must be increased as sgeddes pointed out, and then you must display both values, not just the first value in the list of returned values (which is what $data[0] is doing now - just returning the first item in the array).
Try something like this:
<?php
$q = "SELECT CONCAT (a) FROM record ORDER BY id DESC
LIMIT 2;";
$result = mysql_query($q);
$data = mysql_fetch_array($result);
echo "{" . $data[1] . "}==>{" . $data[0] . "}"; //prints: "{45}==>{12}"
?>
Essentially, since $data is an array, you need to convert it into a string. I did this above by referencing its elements, but that is a fairly crude way to do it. If for example there is only 1 value in the database, trying to echo $data[1] would throw a notice because there is no second value in the array.
implode is a handy method to use because you can convert an array into a string and use a value, like a comma, to glue the values together.
echo implode(", ", $data); //prints "12, 45" (12 first because it is the first item in the array)
If you're not sure a key exists in an array, you can use the empty function, which checks if the key is set (isset), and if it has a non-falsey value.
if (empty($data[0] == false) {
echo $data[0];
}
if (empty($data[1] == false) {
echo $data[1];
}
Documentation:
PDO documentation: http://php.net/manual/en/book.pdo.php
mysqli_* documentation: http://php.net/manual/en/book.mysqli.php
implode documentation: http://php.net/manual/en/function.implode.php
isset documentation:http://php.net/manual/en/function.isset.php
empty documentation:http://php.net/manual/en/function.empty.php
$query="SELECT CONCAT (a) FROM record ORDER BY id DESC
LIMIT 2";
Order by DESC Limit 2 get Last two records from Database.
Related
i'm still new towards php but after searching through multiple topics i can't seem to figure this one out.
$query2 = "SELECT COUNT(MAP_CODE2) FROM TCODE_MAPPING WHERE MAP_CODE2 = 'ABC123'";
$result2 = odbc_exec($connect,$query2);
echo $result2;
i have a query above that i'd like to use to get the total number of rows within the query that i've set, however for some reason i keep getting hit by the error
Array to string conversion in /var/www/html/xxx.php on line 85
Would highly appreciate if anyone could help out on what i'm doing wrong. Thank you!
Problem is:-
You are trying to echo a result-set object of array type.
Solution (check the code comments):-
$query2 = "SELECT COUNT(MAP_CODE2) AS MYCOUNT FROM TCODE_MAPPING WHERE MAP_CODE2 = 'ABC123'"; // given a name to the count
$result2 = odbc_exec($connect,$query2); //prepare and execute query
while (odbc_fetch_row($result2)) { //iterate over result-set object
echo odbc_result($result, "MYCOUNT"), "\n"; // echo count
}
What is happening here is you are echoing an array object type that is also a resource type and php echo only string and other primitive type variables.
so you need to use a loop to access the row or to get row count and access row just use a foreach($results as $result)
to get row count visit this sqlsrv-num-rows . on this official php link you can get more example how to fetch data.
When I'm trying to get the number of rows on a SQL request and if not, the connection that follow fails.
But in any case (also if the request should return 0), it returns 1.
Here's my code :
$str = 'SELECT count(*) FROM admins WHERE mail = ? AND mdp = ?';
$arr = array($mail, $pass);
$rqt = sendRqt($str, $arr);
$tab = $rqt->fetchColumn();
$cnt = count($tab);
echo $cnt;
I don't understand why there's no time it returns 0
The problem is the use of the php function count().
You already have the correct number in your $tab variable as a string (probably, depends on php configuration / version) so you can echo it or cast it to an integer to make sure it is a number.
However, in php:
count(0) === 1
count('0') === 1
See here for example.
You should remove count($tab).
the SQL "COUNT(*)" allways returns a row with the count (quantity) of values, so if you apply the php count() function, always will return 1 because there is one row that contains the value of the COUNT sql function
I believe COUNT() needs a column name.WRONG!! count(*) should count all rows, but I still reccomend a column name like id or something. You could also use an AS to make life a little easier
$str = 'SELECT count(`COLUMNNAME`) AS cnt FROM table WHERE ....
Am I using mysqli_fetch_row() the right way ??
I know the customer name and I wanna find out the Env_lines value in that same record. There is only one record with that customer name. I'm not getting an output when i do echo $env_lines. What might be the problem?
<?php require_once("config.php") ?>
<?php require_once("functions.php") ?>
test
<?php
$customer = 'Bickery';
echo ' <br> 1)'.$customer;
$sql_customer = "SELECT * FROM `Customer` WHERE Cust_Name = '$customer' LIMIT 0,1";
echo ' <br> 2)'.$sql_customer,'<br>';
$customer_selection = mysqli_query($conn,$sql_customer);
var_dump($customer_selection);
$customer_row = mysqli_fetch_row($conn, $customer_selection);
$env_lines = $customer_row["Env_Lines"];
echo ' <br> 3)'.$env_lines;
?>
https://gist.github.com/anonymous/520319ac72e7f08419c4
Manual Says
mixed mysqli_fetch_row ( mysqli_result $result )
Does that show anywhere that you need to give it your connection reference? No
Remove your first parameter from here
$customer_row = mysqli_fetch_row($conn, $customer_selection);
^
Then
Fetches one row of data from the result set and returns it as an enumerated array, where each column is stored in an array offset starting from 0 (zero). Each subsequent call to this function will return the next row within the result set, or NULL if there are no more rows
That means this is not the right function to fetch an associative array, mysqli_fetch_assoc is (amongst others).
$customer_row = mysqli_fetch_assoc($customer_selection);
And oh, PHP guys on SO think this is our duty; here it goes
How can I prevent SQL injection in PHP?
This question already has answers here:
Get sum of MySQL column in PHP
(9 answers)
Closed 9 years ago.
how do I get the output from this:
$VisitorsProfile = $mysql->query("SELECT SUM(views) FROM visitors_profile WHERE publisher = '123456'");
I tryed this but nothing prints me out!
<?php echo $VisitorsProfile['sum'] ?>
Any suggestions?
you need to name the column, I know it sounds weird but it should be
$VisitorsProfile = $mysql->query("SELECT SUM(views) as totals FROM visitors_profile WHERE publisher = '123456'");
and as indicated as below you need the mysql_fetch_assoc function on the query so you can reference it by name.
Then you can reference it by
<?php echo $VisitorsProfile['totals'] ?>
you just need to reference it "as" something. whatever you put in after the word as is what you can refer to it by, i wouldn't use something like "sum" as that is a mysql function and can cause problems.
PHP allows you to get the information by column name or by column index. The recommended way is to do it by column name, because this will allow you to change your query's column order without affecting your PHP code.
So to get it you need to add a column alias to your query:
$rs = mysql_query("SELECT SUM(value) AS total FROM visitors_profile WHERE publisher = '123456'");
if ($row = mysql_fetch_assoc($rs)) {
echo $row['total'];
}
On the first line you are actually running the query. Check the column alias: "total".
On the second line you are asking for an array or specifically a "map" from the result set. In other words, by calling mysql_fetch_assoc you are asking for an array whose elements are available by name. That array represents a row from your result set.
On the third line you are printing the actual sum.
Check the "if" in the $row assignment. This will help you validate there is a result row before trying to print it. I recommend you to do the same on the line where you call mysql_query.
EDIT:
Sorry, I think you are using objects, so it should look like this:
$rs = $mysql->query("SELECT SUM(value) AS total FROM visitors_profile WHERE publisher = '123456'");
if ($row = $mysql->fetch_assoc($rs)) {
echo $row['total'];
}
I am trying to get a count and I am getting 1 instead of 0 from it. I have looked thoroughly though the web and this site. I have even been trying to figure it out on my own for a long time. I keep coming empty handed here.
So Basically what I am trying to do is make a like system for my users. I can get everything to work correctly the count works except for one thing. When they have liked it it returns 1 not 0 which it should be.
Here is my code for the count. I am not posting all the coding for security reasons and it really doesn't need to since its about the counting part not the rest.
$sql_like = mysql_query("SELECT * FROM posts WHERE mem2_id='$id' ORDER BY post_date DESC LIMIT 40");
while($row = mysql_fetch_array($sql_like)){
$like1 = $row['like_array'];
$like3 = explode(",", $like1);
$likeCount = count($like3);
}
So here is the code that determines the number. Any ideas what is wrong with this? Why its returning 1 not 0 when the item is empty?
// you do escape your id right??? (sql injection prevention)
$sql_like = mysql_query("SELECT * FROM posts WHERE mem2_id='$id' ORDER BY post_date DESC LIMIT 40");
while($row = mysql_fetch_array($sql_like)){
$likeCount = 0;
$like1 = trim($row['like_array']);
if ($like1) {
$like3 = explode(",", $like1); // exploding emtpy string would result in array('')
$likeCount = count($like3);
}
}
Calling explode on an empty string gives an array containing the empty string. This is one element, not zero.
I would suggest that you change your database design if possible so that you don't store the values separated by commas. Use a separate table instead.
If you can't change the database design you can handle the empty string separately.
count() returns the number of indexes in an array or something in an object (PHP: count - Manual).
if a string var is used rather than an array or object it returns 1. it has to get a null value in order to return 0.
you can give it a go by trying:
print count("");
and
print count(null);
You'll have better luck if you use explode() to break the sql output into an array and then run a check with an if statement. Something like the following:
$like3 = explode(',',$like1);
if (count($like1)=1 && $like1[0] == '')
// etc ..
I hope this helps