I'm currently working on a website with a friend and I need to display the average rating for a movie.
So, I have a database with numerous columns (name, mail, etc) including "note".
My friend wrote this code :
<?php
$moyenne = "SELECT avg(note) FROM `annee_1`";
$test = $db->prepare($moyenne);
$test->execute();
$resultat = $test->fetchAll(PDO::FETCH_ASSOC);
echo $resultat;
?>
I'm not overly familiar with php or mysql. I know something is wrong (since this doesn't display a number, but just "Array"), but I don't know what.
Any suggestiong, or solution to my problem?
Thanks ! :)
You can access to your result by passing parameter to your array with a while loop. Replace your echo $result by print_r($resultat) and you can check the result you have received.
Your query will return one row with one column. An easy way to get a single value from a query like that is to use
$resultat = $test->fetchColumn();
Instead of
$resultat = $test->fetchAll(PDO::FETCH_ASSOC);
You're seeing "Array" currently because $resultat is an array (because that's what fetchAll reutrns), and when you try to echo it, it gets converted to a string. In PHP, the string representation of any array is "Array". See the documentation here:
Arrays are always converted to the string "Array"; because of this, echo and print can not by themselves show the contents of an array.
But if you use fetchColumn() instead, $resultat won't be an array. Based on your comments, it should be an int.
Related
I have a mysql query that works fine in phpmyadmin, but does not give the expected results on my php page. I am sure that I have something wrong in the code.
Here is the php code that passes the variable
print "<td><a href='transactions_by_transaction_date.php?var=\''".urlencode(
$row['transaction_date'])."'\''>".$row['transaction_date']."</a></td></tr><tr>";
And here is where I create my query
$var = $_GET['var'];
echo $var;
$stmt2 = $db->prepare("SELECT * FROM bo_transactions WHERE
transaction_date=:var ORDER BY transaction_id");
$stmt2->bindParam(':var',$var,PDO::PARAM_STR);
$stmt2->execute();
// set the resulting array to associative
$result = $stmt2->setFetchMode(PDO::FETCH_ASSOC);
I have the echo $var line to verify that it is passing the correct date and it appears to be. The field transaction_date is a date type.
What have I missed?
I thing you have issue in single quotes and double quotes data passing
Just use this one
print "<td><a href='transactions_by_transaction_date.php?var='".urlencode($
row['transaction_date'])."'>".$row['transaction_date']."</a></td></tr><tr>";
My apologies to everyone. The problem was not in the code posted it was a typing error in my output. Thank you to all that gave me input
As the code is, I think the associative value of 'aurapass' is picking up as a string rather than the corresponding fetch value. Everything is returning positive. How do I select the fetch_assoc() value?
$recruiter=$_POST["recruiter"];
$aurapass=$_POST["aurapass"];
$recruitfetch=mysqli_query($maindb, "SELECT * FROM auras WHERE auraname = $recruiter");
$recruitcheck=mysqli_fetch_assoc($recruitfetch);
if($recruitcheck['aurapass']==$aurapass){
if($recruitcheck['recruitbadge']=="valid"){
echo "<script>alert('Recruiter badge verified.')</script>";
}
}
I have since changed the variables to be different words, so I can test the true value of the variables, and the column names, and string value of "valid" matches the table database values, so what I the problem, here?
With changes, the current code reads:
$recruiter=$_POST["recruiter"];
$recruitpass=$_POST["recruitpass"];
$recruitfetch=mysqli_query($maindb, "SELECT * FROM auras WHERE auraname = '$recruiter'");
$recruitcheck=mysqli_fetch_assoc($recruitfetch);
if($recruitcheck['aurapass']==$recruitpass){
if($recruitcheck['recruitbadge']=="valid"){
echo "<script>alert('Recruiter badge verified.')</script>";
}
}
I am struggling to receive any sort of printout, or echo, to show the values of anything. I am extremely new to this, and struggling. Unfortunately, I have not found sites that talk about exact syntax, especially with PHP7.0. Any advice on troubleshooting this would be fantastic!
Adding the quotes to recruiter did change the results, so apparently the code is correct in the second version, but I think I had some sort of character errors because I had to retype it to get it to work, but it is still the same exact text?
This is what I ended with:
$recruiter=$_POST["recruiter"];
$recruitpass=$_POST["recruitpass"];
$recruitfetch=mysqli_query($maindb, "SELECT * FROM auras WHERE auraname = '$recruiter'");
$recruitcheck=mysqli_fetch_assoc($recruitfetch);
if($recruitcheck["aurapass"]==$recruitpass){
if($recruitcheck["recruitbadge"]=="valid"){
I also figured out how to print a var_dump, and I understand its use. Thank you, all!
This question already has answers here:
fetch single record using PHP PDO and return result
(2 answers)
Closed 6 years ago.
I have not made the change from MySQL_ to PDO until today. Needless to say, the migration is more than a simple headache. So, I need a bit of help. I tried all the search terms I could before registering and asking this question.
My Problem
User types a numeric code into the search box, translates it to
.php?code=term
Script selects all columns from the database where the code is the
code term searched for.
PHP will Echo the results
My Code
if (isset($_GET["code"])) {
//IF USER SEARCHES FOR CODE, RUN THIS. ELSE SKIP.
$crimecode = $_GET["code"];
$crcode = $link->prepare("SELECT * FROM crimecodes WHERE code = :code");
$crcode->bindParam(':code', $crimecode);
$crcode->execute();
$coderesult = $crcode->fetchAll();
echo "<h4>CODE:</h4>";
echo $crimecode;
echo "<br /><h4>DEFINITION:</h4>";
echo $coderesult;
die();
}
Before, it was simple. All I had to do was:
$qcode = mysql_query("SELECT * FROM crimecodes WHERE code = $crimecode");
$fcode = mysql_fetch_assoc($qcode);
echo $fcode['definition'];
But, the ever evolving world has decided to fix something that wasn't broken so now the whole prior code is pointless and you gotta learn something new. Any help is appreciated to get this to work.
Right now, the above PDO code returns definition: ARRAY.
Like literally, the $coderesult prints Array.
The fetchAll() option returns an array containing all of the result set rows (http://php.net/manual/pt_BR/pdostatement.fetchall.php).
$coderesult prints Array because it's actually an array. If you do var_dump($coderesult) you'll see it.
I suppose that you are trying to get one row only. If that's the case, add this line after $coderesult = $crcode->fetchAll();:
$coderesult = $coderesult[0];
Then you can
echo $coderesult['definition'];
If you're trying to get more than one row, you need to use foreach to loop through the array.
I suggest you read the php manual for PDO Class or mysqli, wherever you prefer. There's a lot more options than mysql_.
Also, I think it's worth to mention that your previous code
$qcode = mysql_query("SELECT * FROM crimecodes WHERE code = $crimecode");
$fcode = mysql_fetch_assoc($qcode);
echo $fcode['definition'];
it's vulnerable to SQL Injection.
i'm relatively new to coding and I need a little help. I'm basically trying to loop through an entry in a mySQL database and push any new entry into an array , so that it only comes up once in my array.
// SQL query
$response = $bdd->query('SELECT serie_bd FROM inventaire_bd');
//creating array to group all elements from the db so that they do not repeat
$serie_bd_groupe=array();
while($data_collected = $response->fetch())
{
if(array_key_exists($data_collected,$serie_bd_groupe)==false)
{
array_push($data_collected,$serie_bd_groupe);
}
}
Will this work? - it seems like the loop will just stay stuck after it comes accross an entry a second time because the if statement wont execute itself.
Also in the future, are their any php equivalent to jsfiddle.net so i can test code syntaxically?
Thank you for your time
Your array keys will be default integers, so you don't want to check those. Instead of this:
if(array_key_exists($data_collected,$serie_bd_groupe)==false)
you should do this:
if(!(in_array($data_collected,$serie_bd_groupe)))
http://php.net/manual/en/function.in-array.php
On the other hand, if you're expecting your collected data to be the array key rather than value, you'd do something like this, instead of your array_push:
$serie_bd_groupe[$data_collected] = 1;
then your key check would work.
If you are looking for UNIQUE values (serie_bd) from your database, update your query to include "DISTINCT" like this:
$bdd->query('SELECT DISTINCT serie_bd FROM inventaire_bd');
On the other hand, I think you are looking for http://phpfiddle.org/
I have 2 columns in a table called Points. The 2 columns are UserPoints and UserID.
I want to be able to echo the total amount of points a user has.
I've got something like this but I dont think its right.
$getTotalPoints = mysql_query("SELECT SUM(UserPoints) FROM `Points` WHERE `UserID` = '1'") or die(mysql_error());
$totalPoints = mysql_fetch_array($getTotalPoints);
When i echo the above statement by echoing "$totalPoints" i get "Array".
Anyone know the correct query to do this ?
You're getting Array because that's what's stored in $totalPoints. Look closely at your code and you'll see you used the mysql_fetch_array() function, which retrieves a row of results from the results set as an array. If you do var_dump() on $totalPoints you'll see the following:
Array
(
[0] => 12345
[SUM(UserPoints)] => 12345
)
The sum you're looking for is at index 0 or the column name, in this case SUM(UserPoints), so you can output it using echo $totalPoints[0] or echo $totalPoints['SUM(UserPoints)'].
Alternatively, you could use the mysql_result() function. I think this is more in-line with the behavior you were expecting. It fetches a single value from the row from the result set. So, instead of mysql_fetch_array() you'd wrote:
$totalPoints = mysql_result($result, 0);
For more information on mysql_result(), check out the PHP documentation for it.
As an aside, I would recommend not using mysql_* functions if you have the option. A newer interface like PDO, or at least mysqli, would be better. This will depend on your project of course... if you're working with a large legacy code base it may be difficult to change. But if you're starting out now, I think you'd benefit from the newer libraries. You can see my opinion and some guidance on transitioning extensions in this article I wrote.
Hope this helped... and good luck!
mysql_fetch_array fetches a result row as an associative array, a numeric array, or both. by default it creates both. all that you need is to echo $totalPoints[0];
or, if you rewrite you request as
$getTotalPoints = mysql_query("SELECT SUM(UserPoints) total FROM `Points`
WHERE `UserID` = '1'") or die(mysql_error());
$totalPoints = mysql_fetch_array($getTotalPoints);
echo $totalPoints['total'];
mysql_fetch_array returns an array. Therefore you need to treat $totalpoints as an array.
try adding this line to the end of your snippet:
echo $totalPoints[0];
There are several ways to retrieve data with the mysql functions I suggest reading about them in the php manual.
Here is mysql_fetch_array
The resultset row is an array with as many elements as you got in the SELECT.
In you case you only got 1 element (the sum).
So you should:
echo $totalPoints[0];
If you need to debug this kind of issues I recommend you to read about print_r function.