PHP PDO - Understanding for beginners - php

I've read through PHP PDO Book and now have some basic questions:
If i understood correctly, i'll have to use begin_transaction() in order to turn off autocommit. If i am okay with autocommit, i am always good to go with a simple query()Is this correct?
Did i get it right, that there is basically no difference between query() and exec(), except of the above asked topic?
I made a query like this one:
foreach ($db->query('SELECT * from user') as $row) {
$row = json_encode($row);
echo $row;
}
Which returns a JSON Object:
{
"alias":"tk",
"0":"tk",
"password":"pw",
"1":"pw",
}
This is basically correct, however, why is each value returned twice, once with my chosen keyword and another time with an Integer key?

why is each value returned twice, once with my chosen keyword and another time with an Integer key?
The array has the values both with the column names as keys, and the column ordinals too. So you could access the values from the result set by using the number of which column you want. (of course, that does not seem to be of too much use with a select * statement...)
You can affect this behaviour with PDOStatement::setFetchMode(). The constants starting with PDO::FETCH_ are applicable here. Their documentation can be found here

Related

Why is this string operator not registering valid match with fetch_assoc()?

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!

Drupal / MySQL fetchAllAssoc(); resulting in exception

I have an external database that I am trying to access from within a Drupal page, I have successfully queried the database and output data to the page using fetchAssoc(), however this only returns the first row in the database. I would like to return all rows into an array for processing, so I'm attempting to use fetchAllAssoc(), this however results in an exception. The database has the following SQL fields:
id, model, manufacturer, url, date_modified
My test code is as follows:
<?php
db_set_active('product_db');
$query = db_select('product', 'p')->fields('p');
$sqlresults = $query->execute()->fetchAllAssoc('id');
foreach($sqlresults as $sqlresult)
{
printf($sqlresult);
}
db_set_active();
?>
I'm thinking that it is the key field 'id' that I am specifying with fetchAllAssoc() that is the problem, as fetchAssoc() prints values correctly. All documentation I have found seems to say that you pass a database field as the key but I have also passed a numeric value with no success.
Many thanks in advance for any advice, I'm sure I'm just missing something stupid.
I think it should work in this way, but within the foreach you want to print the $sqlresult variable as a string, but it is an object (it causes the error).
printf function needs a string as the first parameter, see:
http://php.net/manual/en/function.printf.php
Use for instance var_dump instead:
var_dump($sqlresult);

Trouble retrieving data using PDO syntax, PHP

I'm brand new to the PDO syntax and I'm liking the learning curve! I'm refactoring code - migrating over from archaic mysqli_* methods.
Predictably, I've run into some snags, being a novice. One of the big ones is (forgive if this is a dumb question) retrieving data from the DB and echoing it out on the page. Here is what I have so far:
$getURLid = $_GET['id'];
$idQuery = $connection->prepare("SELECT * FROM pages WHERE page_id = :getURLid");
$idQuery->execute(array(':getURLid' => $getURLid));
$idRetrieved = $idQuery->fetchAll(); // This is the part I'm unclear on.
When I echo $idRetrieved['value'] to the page, nothing shows up. I'm missing something or misunderstanding how it works. Maybe fetchAll isn't what I should be using.
If it is, is a loop necessary to retrieve all rows? I was under the impression that fetchAll would loop through them automatically based on what I've read.
Thanks for the help.
Read the doco for PDOStatement::fetchAll closely. It returns an array of row data.
The type of data representing each row depends on your fetch mode which by default is PDO::FETCH_BOTH. This would mean each row is an array with both numeric and associative keys. If you're only going to access the data associatively, I'd recommend using PDO::FETCH_ASSOC, eg
$idRetrieved = $idQuery->fetchAll(PDO::FETCH_ASSOC);
You would then either need to loop or access each row via its index, eg
foreach ($idRetrieved as $row) {
echo $row['value'];
}
// or
echo $idRetrieved[0]['value']; // assuming there's at least one row.

Error in Comparing the same column in mysql

I am fetching the values from the column as the value of integer and doing this for two user so i tried to get the value from the table and compare it but unfortunately for both greater and smaller comparsion i am getting the same result nothing changed.
How do i compare the column values?
My code is like below-----
$sqlres="select membership from register where mid='".$_SESSION['mid']."' ";
$pres=mysql_query($sqlres);
$prest=mysql_fetch_array($pres);
$sqlres1="select membership from register where matri_id='".$row['mtr_id']."' ";
$pres1=mysql_query($sqlres);
$prest1=mysql_fetch_array($pres);
if($pres<$pres1)
{
//somethiung enter code here
}
First of all don't use mysql_* it is deprecated, use mysqli_* or PDO instead.
As for your question, mysql_fetch_array as the name suggests, returns an array, not a single value, so you need to get the first value in the array:
if($pres[0]<$pres1[0])
{
//somethiung enter code here
}
You save the result in $prest and $prest1 (with "t"), not in $pres and $pres1. I suggest always using the variable $query for the query string and $result for the result table. Only when you fetch the result should you use a custom variable name to not get confused.
You can use something like
if($prest['membership']<$prest1['membership']){//do stuff here}
In the piece of code that you provided, you are comparing the resources that mysql_query returned not the values of the columns. You have to do this:
if( $prest['membership'] < $prest1['membership'] ){
//Some stuff going here
}
Advice: Name your variables properly. Use more describing names. After 2 months you won't remember the difference between $prest and $prest1

Echoing the sum of a table in PHP

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.

Categories