Μysql - Ηow to get first value from array after fetch in php - php

Hello i want to get the first value (uid) from the object that i fetch.
Here is the syntax
$sql2 = "SELECT **uid,**notification_created,username,name,profile_pic,tour,email, api_signature,first_name,last_name, artisticBehaviour,location,bio,last_login,first_login,updates_count,friend_count,profile_views,group_count,password
FROM users WHERE username=:username ";
$stmt2 = $db->prepare($sql2);
$stmt2->bindParam("username", $username, PDO::PARAM_STR);
$stmt2->execute();
$userData = $stmt2->fetch(PDO::FETCH_OBJ);
$uid = ????????
I want to retrieve the first value (uid) so i may use it as a variable

First bind the result and then fetch them
you should test if the username is empty before using it
$sql2 = "SELECT uid,notification_created,username,name,profile_pic,tour,email, api_signature,first_name,last_name, artisticBehaviour,location,bio,last_login,first_login,updates_count,friend_count,profile_views,group_count,password
FROM users WHERE username=:username ";
$stmt2 = $db->prepare($sql2);
$stmt2->bindParam("username", $username, PDO::PARAM_STR);
$stmt2->execute();
$result = $stmt2->get_result();
if ($result->num_rows>0) {
while ($row = $result->fetch_assoc()) {
echo $row['uid'];
}
}

Related

Prepared statement fetch row returns nothing

I want to fetch this row and save it into $notescheck, but when I try to do this the $notescheck is empty when I want to echo and there are no errors. With non-prepared statements it works fine.
Code:
if($user_ok == true) {
$sql = "SELECT notescheck FROM users WHERE username=? LIMIT 1";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s",$log_username);
$stmt->execute();
$row = $stmt->fetch();
$notescheck = $row[0];
$stmt->close();
}
With non-prepared statement it would look like this:
if($user_ok == true) {
$sql = "SELECT notescheck FROM users WHERE username='$log_username' LIMIT 1";
$query = mysqli_query($conn, $sql);
$row = mysqli_fetch_row($query);
$notescheck = $row[0];
mysqli_close($conn);
}
This isn't how fetch() works with prepared statements, you're not fetching an array like you think you are. You also need to bind the result of the select into variables, then use those to display. If there are multiple records, you'd use a while($stmt->fetch){ echo $notescheck };
if($user_ok == true) {
$sql = "SELECT notescheck FROM users WHERE username=? LIMIT 1";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s",$log_username);
$stmt->execute();
$stmt->bind_result($notescheck);
$stmt->fetch();
$stmt->close();
}
echo $notescheck;
You should check into reading this:
http://php.net/manual/en/mysqli-stmt.fetch.php
Multiple records matching username=x would look like this:
if($user_ok == true) {
$sql = "SELECT notescheck FROM users WHERE username=? LIMIT 1";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s",$log_username);
$stmt->execute();
$stmt->bind_result($notescheck);
$stmt->store_result()
while($stmt->fetch()){
echo $notescheck;
}
$stmt->close();
}

Combining two prepared statements not working

First, according to another SO post, I tried combining the two statements into one.
<?php
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, 1);
$sql = "UPDATE users SET pass = :password WHERE usrn = :id;
SELECT prim FROM users WHERE usrn = :id;";
$stmt = $conn->prepare($sql);
$stmt->bindParam(":id", $_SESSION["idPersist"]);
$stmt->bindParam(":password", password_hash($_POST["password"], PASSWORD_DEFAULT));
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC); //// line 71
?>
However, this kept throwing the error: Fatal error: Uncaught PDOException: SQLSTATE[HY000]: General error on line 71.
I couldn't find any relevant solutions to this issue, so I decided to simply split up the two statements.
<?php
$sql = "UPDATE users SET pass = :password WHERE usrn = :id";
$stmt = $conn->prepare($sql);
$stmt->bindParam(":id", $_SESSION["idPersist"]);
$stmt->bindParam(":password", password_hash($_POST["password"], PASSWORD_DEFAULT));
$stmt->execute();
$sql = "SELECT prim FROM users WHERE usrn = :id";
$stmt = $conn->prepare($sql);
$stmt->bindParam(":id", $_SESSION["idPersist"]);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
$_SESSION["session"] = $result["prim"];
?>
But a var_dump($result) is returning Bool(false), so obviously something is not working right with fetching the result and storing it as a variable, it seems, in both cases.
I'm new to PHP and MySQL, so I'm at a loss right now.
Change this,
$sql = "SELECT prim FROM users WHERE usrn = :id";
$stmt = $conn->prepare($sql);
$stmt->bindParam(":id", $_SESSION["idPersist"]);
$result = $stmt->fetch(PDO::FETCH_ASSOC);
$_SESSION["session"] = $result["prim"];
To this,
$sql = "SELECT prim FROM users WHERE usrn = :id";
$stmt = $conn->prepare($sql);
$stmt->bindParam(":id", $_SESSION["idPersist"]);
$stmt->execute(); // Your problem
$result = $stmt->fetch(PDO::FETCH_ASSOC);
$_SESSION["session"] = $result["prim"];
You are missing the execution of the query.

SQL statement inside while loop PHP

I am trying to run a SQL statement within a while loop, using the variable $id set in the previous statement but am struggling to get it working. If I remove the statement in the while loop I can see the while loop is functioning as it displays the $id variable multiple times:
$businessPark = $_SESSION['businessPark'];
$num = "1";
$stmt = $conn->prepare("SELECT CompanyId from Portal.services WHERE ".$businessPark." = ?");
$stmt->bind_param("s", $num);
$stmt->execute();
$stmt->bind_result($id);
while ($stmt->fetch()) {
echo "ID: " . $id . "<br>";
}
However when I add the SQL statement back in, I am presented with only the first $id result. If I add in $stmt->close(); at the start of the while loop I do get the first company name, but then the while loops ends. Here is the code:
$businessPark = $_SESSION['businessPark'];
$num = "1";
$stmt = $conn->prepare("SELECT CompanyId from Portal.services WHERE ".$businessPark." = ?");
$stmt->bind_param("s", $num);
$stmt->execute();
$stmt->bind_result($id);
while ($stmt->fetch()) {
$sql = $conn->prepare("SELECT CompanyName from phpipam.ipaddresses WHERE id = ?");
$sql->bind_param("s", $id);
$sql->execute();
$sql->bind_result($CompanyName);
$sql->fetch();
echo $CompanyName;
}
Any ideas please?
Update: If I add in a store result before the loop and free result inside the loop I get the first company name and also get the "finished loop" echo:
$businessPark = $_SESSION['businessPark'];
$num = "1";
$stmt = $conn->prepare("SELECT CompanyId from Portal.services WHERE ".$businessPark." = ?");
$stmt->bind_param("s", $num);
$stmt->execute();
$stmt->bind_result($id);
$stmt->store_result();
while ($stmt->fetch()) {
$stmt->free_result();
$sql = $conn->prepare("SELECT CompanyName from phpipam.ipaddresses WHERE id = ?");
$sql->bind_param("s", $id);
$sql->execute();
$sql->bind_result($CompanyName);
$sql->fetch();
echo $CompanyName;
}
echo "finished the loop";
}
Thanks.
Cant comment so answering here.
I think you need to use $stmt->bind_param("s", $businessPark); instead of $stmt->bind_param("s", $num);
I had it working (albeit with different queries) on my test server - I'm pretty sure the issue is that you need to pass the resultset through to PHP so that you can prepare the second statement (which must be outside the loop) - otherwise sql = $conn->prepare( ... ); fails and returns false.
This should work:
$businessPark = $_SESSION['businessPark'];
$num = "1";
//first statement
$stmt = $conn->prepare("SELECT CompanyId from Portal.services WHERE ".$businessPark." = ?");
$stmt->bind_param("s", $num);
$stmt->execute();
$stmt->bind_result($id);
//pass the result to PHP so you can prepare a new statement
$stmt->store_result();
//second statement
$sql = $conn->prepare("SELECT CompanyName from phpipam.ipaddresses WHERE id = ?");
while ($stmt->fetch()) {
$sql->bind_param("s", $id);
$sql->execute();
$sql->bind_result($CompanyName);
$sql->fetch();
echo $CompanyName;
}
//clean up
$stmt->free_result();
$stmt->close();
You can accomplish what you want with a join. I know that this does not answer why your code is not working but in my opinion it's a better solution anyway.
$businessPark = $_SESSION['businessPark'];
$num = "1";
$stmt = $conn->prepare("
SELECT t2.CompanyName
FROM Portal.services t1
INNER JOIN phpipam.ipaddresses t2 ON t1.CompanyId = t2.id
WHERE " . $businessPark . " = ?
");
$stmt->bind_param("s", $num);
$stmt->execute();
$stmt->bind_result($companyName);
More information about join syntax

Not getting a result from DB

So I'm checking to see if a user already liked a post. Here's what I'm doing
$id = 65;
//Get likes count
$stmt = $con->prepare("SELECT * FROM likes WHERE liked_post_id = :liked_post_id");
$stmt->bindValue(':liked_post_id', $id, PDO::PARAM_STR);
$stmt->execute();
$return = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<pre>
<?php
print_r($return);
?>
</pre>
<?php
//Get user IP
$ip = $_SERVER['SERVER_ADDR'];
//Check if user liked post
$result = $con->prepare("SELECT * FROM likes WHERE liked_post_user = :username");
$result->bindParam(':username', $_SESSION['user']);
$result->execute();
$reprint = $result->fetch(PDO::FETCH_ASSOC);
echo $reprint['liked_post_user'];
$return_cnt = count($reprint);
if($return_cnt < 1){
//Insert like
$query = $con->prepare("INSERT INTO likes (liked_post_id, liked_post_user, liked_post_ip) VALUES (:usr_id, :user, :ip)");
$query->bindValue(':usr_id', $id, PDO::PARAM_STR);
$query->bindValue(':user', $_SESSION['user']);
$query->bindValue(':ip', $ip, PDO::PARAM_STR);
$query->execute();
}
The problem is $query never gets ran. Even though I have no record of the username in the DB. So I'd expect it to run once, and insert $query into the DB, once. But it isn't. I'm not getting any errors either. Any ideas?
First of all you can simply count $reprint. To answer your second issue, you need to select the post, or else it'll simply check all the posts. So do
$result = $con->prepare("SELECT * FROM likes WHERE liked_post_user = :username AND liked_post_id = :post_id");
$result->bindParam(':username', $_SESSION['user']);
$result->bindParam(':post_id', $_GET['id']);
$result->execute();
$reprint = $result->fetch(PDO::FETCH_ASSOC);
Note that if no user is logged in it'll still input an empty value. So make sure to figure a way around that.
The second query should look for a specific liked_post_id. It's currently looking for any posts that the user liked, not just this one.
//Check if user liked post
$result = $con->prepare("SELECT * FROM likes WHERE liked_post_user = :username AND liked_post_id = :id");
$result->bindParam(':username', $_SESSION['user']);
$result->bindParam(':id', $id);
$result->execute();
$reprint = $result->fetch(PDO::FETCH_ASSOC);
And then you should test whether the query found anything by testing whether $reprint is an array or false:
if ($reprint) {
echo $reprint['liked_post_user'];
} else {
//Insert like
$query = $con->prepare("INSERT INTO likes (liked_post_id, liked_post_user, liked_post_ip) VALUES (:usr_id, :user, :ip)");
$query->bindValue(':usr_id', $id, PDO::PARAM_STR);
$query->bindValue(':user', $_SESSION['user']);
$query->bindValue(':ip', $ip, PDO::PARAM_STR);
$query->execute();
}

How can I properly use a PDO object for a parameterized SELECT query

I've tried following the PHP.net instructions for doing SELECT queries but I am not sure the best way to go about doing this.
I would like to use a parameterized SELECT query, if possible, to return the ID in a table where the name field matches the parameter. This should return one ID because it will be unique.
I would then like to use that ID for an INSERT into another table, so I will need to determine if it was successful or not.
I also read that you can prepare the queries for reuse but I wasn't sure how this helps.
You select data like this:
$db = new PDO("...");
$statement = $db->prepare("select id from some_table where name = :name");
$statement->execute(array(':name' => "Jimbo"));
$row = $statement->fetch(); // Use fetchAll() if you want all results, or just iterate over the statement, since it implements Iterator
You insert in the same way:
$statement = $db->prepare("insert into some_other_table (some_id) values (:some_id)");
$statement->execute(array(':some_id' => $row['id']));
I recommend that you configure PDO to throw exceptions upon error. You would then get a PDOException if any of the queries fail - No need to check explicitly. To turn on exceptions, call this just after you've created the $db object:
$db = new PDO("...");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
I've been working with PDO lately and the answer above is completely right, but I just wanted to document that the following works as well.
$nametosearch = "Tobias";
$conn = new PDO("server", "username", "password");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sth = $conn->prepare("SELECT `id` from `tablename` WHERE `name` = :name");
$sth->bindParam(':name', $nametosearch);
// Or sth->bindParam(':name', $_POST['namefromform']); depending on application
$sth->execute();
You can use the bindParam or bindValue methods to help prepare your statement.
It makes things more clear on first sight instead of doing $check->execute(array(':name' => $name)); Especially if you are binding multiple values/variables.
Check the clear, easy to read example below:
$q = $db->prepare("SELECT id FROM table WHERE forename = :forename and surname = :surname LIMIT 1");
$q->bindValue(':forename', 'Joe');
$q->bindValue(':surname', 'Bloggs');
$q->execute();
if ($q->rowCount() > 0){
$check = $q->fetch(PDO::FETCH_ASSOC);
$row_id = $check['id'];
// do something
}
If you are expecting multiple rows remove the LIMIT 1 and change the fetch method into fetchAll:
$q = $db->prepare("SELECT id FROM table WHERE forename = :forename and surname = :surname");// removed limit 1
$q->bindValue(':forename', 'Joe');
$q->bindValue(':surname', 'Bloggs');
$q->execute();
if ($q->rowCount() > 0){
$check = $q->fetchAll(PDO::FETCH_ASSOC);
//$check will now hold an array of returned rows.
//let's say we need the second result, i.e. index of 1
$row_id = $check[1]['id'];
// do something
}
A litle bit complete answer is here with all ready for use:
$sql = "SELECT `username` FROM `users` WHERE `id` = :id";
$q = $dbh->prepare($sql);
$q->execute(array(':id' => "4"));
$done= $q->fetch();
echo $done[0];
Here $dbh is PDO db connecter, and based on id from table users we've get the username using fetch();
I hope this help someone, Enjoy!
Method 1:USE PDO query method
$stmt = $db->query('SELECT id FROM Employee where name ="'.$name.'"');
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
Getting Row Count
$stmt = $db->query('SELECT id FROM Employee where name ="'.$name.'"');
$row_count = $stmt->rowCount();
echo $row_count.' rows selected';
Method 2: Statements With Parameters
$stmt = $db->prepare("SELECT id FROM Employee WHERE name=?");
$stmt->execute(array($name));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
Method 3:Bind parameters
$stmt = $db->prepare("SELECT id FROM Employee WHERE name=?");
$stmt->bindValue(1, $name, PDO::PARAM_STR);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
**bind with named parameters**
$stmt = $db->prepare("SELECT id FROM Employee WHERE name=:name");
$stmt->bindValue(':name', $name, PDO::PARAM_STR);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
or
$stmt = $db->prepare("SELECT id FROM Employee WHERE name=:name");
$stmt->execute(array(':name' => $name));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
Want to know more look at this link
if you are using inline coding in single page and not using oops than go with this full example, it will sure help
//connect to the db
$dbh = new PDO('mysql:host=localhost;dbname=mydb', dbuser, dbpw);
//build the query
$query="SELECT field1, field2
FROM ubertable
WHERE field1 > 6969";
//execute the query
$data = $dbh->query($query);
//convert result resource to array
$result = $data->fetchAll(PDO::FETCH_ASSOC);
//view the entire array (for testing)
print_r($result);
//display array elements
foreach($result as $output) {
echo output[field1] . " " . output[field1] . "<br />";
}

Categories