unable to properly use the resqult of an sql query in php - php

What I'm trying to do is take the number of rows that meet a certain requirement, and depending on the number that do, the script will do different things.
my code:
$sql2 = "SELECT COUNT(email)FROM subscribers WHERE id= ?";
$stmt2 = $conn->prepare($sql2);
$stmt2->bind_param("s", $id);
$stmt2->execute();
$callbacks = $stmt2->get_result();
while($rows = $callbacks->fetch_assoc()){
$results = $rows;
}
$stmt2->close();
if ($results <2001){
$email = trim($_POST["email"]);
}else{
$email_err = "This user has reached the limmit to what their plan can allow .";
}
The problem I'm having is that I'm unsure of how to actually use the number of rows.
In this configuration, it doesn't care what the number of results is, it just posts them anyways.
If I do something like this id_err = $results; to see what the query result is it gives me an array to string conversion error.
As hardware intensive as it sounds for this kind of operation, if you think should query the rows directly and count them with PHP please show me how.
I have also tried doing some variation on $results = $rows['count'] with different names such as 'total', and 'result' but they still post. when I try to see what the query result with id_err = $results; it flat out ignores it and posts anyways.
to avoid any confusion for on what $id_err is, it stops the script from posting if it ever gets used.
and to clarify this SQL query is within a conditional statement.
thank you in advance.

The count function returns all records as one row with the count.. so remove the while and compare the appropriate index.
$sql2 = "SELECT COUNT(email) as the_count FROM subscribers WHERE id= ?";
$stmt2 = $conn->prepare($sql2);
$stmt2->bind_param("s", $id);
$stmt2->execute();
$callbacks = $stmt2->get_result();
$rows = $callbacks->fetch_assoc();
$stmt2->close();
if ($rows['the_count'] < 2001){
$email = trim($_POST["email"]);
}else{
$email_err = "This user has reached the limmit to what their plan can allow .";
}

Related

Prepared statement returns no results

I have been chasing my tale with this for a long time. I have not been able to find an issue with this code:
$query = "SELECT * FROM CUSTOMER WHERE username = ?";
$stmt = $db->prepare($query);
$stmt->bind_param("s", $username);
$stmt->execute();
echo $stmt->num_rows." ".$username;`
The CUSTOMER table in my database has three columns: username, pwd, and email. But nonetheless, no results are returned when I assign the $username variable to a value I know exists in the database. I know it exists because this query
$results = $db->query("SELECT * FROM CUSTOMER WHERE username ='$username'");
echo $results->num_rows;
Displays one row, which is what is expected. Can anybody please tell me why my prepared statement will not produce the correct results? I have tried several variations of quoting, not quoting, hardcoding the variable's value, but nothing works. I am on a university server so I have no control over PHP's or MySQL's settings, but I'm not sure that has anything to do with it. It seems like a coding issue, but I can't see anything wrong with the code.
num_rows will be populated only when you execute $stmt->store_result();.
However, 99.99% of the time you do not need to check num_rows. You can simply get the result with get_result() and use it.
$query = "SELECT * FROM CUSTOMER WHERE username = ?";
$stmt = $db->prepare($query);
$stmt->bind_param("s", $username);
$stmt->execute();
$result = $stmt->get_result();
foreach($result as $row) {
// ...
}
If you really want to get the num_rows, you can still access this property on the mysqli_result class.
$result = $stmt->get_result();
$result->num_rows;
You've executed the query successfully, but not done anything with the result. After $stmt->execute();, you're looking for $stmt->bind_result($result);.
With this, you'll have access to the user's information in the $result variable.

How to SELECT * with multiple WHERE using fetch_assoc in prepared statements in PHP-MYSQL?

It's been two days and I have not found any solution for this on Google, so please help.
I have to SELECT * from one row with multiple WHERE clauses, using a prepared statements, I want to retrieve the results using fetch_assoc so that I don't have to bind variables using bind_result(), using fetch_assoc I can print many columns as $row['column_name']. My code is below and it's not running, giving no error.
$query = 'SELECT * FROM `table_name` WHERE `uid` = ? AND `email` = ?';
if ($stmt_select = $conn->prepare($query)) {
$stmt_select->bind_param('is', $user_id, $user_email);
$user_id = $_SESSION['uid']; //this variable is set and prints perfectly
$user_email = $_SESSION['user_email']; //this variable is set and prints perfectly
$result = $stmt_select->execute();
$stmt_select->store_result();
while ($row = $result->fetch_assoc()) {
print_r($row);
echo $row["supermarket_name"];
echo $row["supermarket-region"];
/*Nothing is being printed*/
}
$stmt_select->free_result();
$stmt_select->close();
}else{
echo 'query returned false';
}
The var_dump($result) returns (boolean)true
Since the above code isn't throwing any error and in last two days I couldn't figure out what's wrong with my code, can somebody let me know what's wrong with my code?
Thanks!

PHP: How to select single value from single row in MySQL without using array for results

I am new to PHP and have a really basic question.
If I know the result of a query is only a single value (cell) from a single row in MySQL how can I simplify the below without having to go through an array of results and without increasing the risk of SQL injection ?
In the example below I would just need to echo a single email as the result of the query.
I found a couple of posts suggesting different approaches with fetch_field for this but I am not sure what is the best way here since some of these seem to be pretty old or deprecated now.
My PHP:
$stmt = $conn->prepare("SELECT email FROM Users WHERE userName = ? LIMIT 1");
$stmt->bind_param('s', $userName);
$stmt->execute();
$result = $stmt->get_result();
$arr = $result->fetch_assoc();
echo $arr["email"];
Many thanks in advance.
You can avoid caring what the column is called by just doing this:
<?php
$stmt = $conn->prepare("SELECT email FROM Users WHERE userName = ? LIMIT 1");
$stmt->bind_param('s', $userName);
$stmt->execute();
$email = $stmt->get_result()->fetch_object()->email;
echo $email;

Results UNDEFINED in SQL query and php

I am new when it comes to php, SQL and still learning, I am trying to get the last 4 string value of my column where the value is a telephone numbers: (7258787)
I am trying to display the last 4 string even the search query is full 7 string (8787) base on what i have read SUBSTRING(column_name, -4) will result the last 4 strings from the right.
my codes returns undefined, can you enlighten me with this?
if (isset($_GET['telephone'])) {
$data = "%".$_GET['telephone']."%";
$sql = 'SELECT telephone, SUBSTRING(telephone,-4)FROM employee';
Using this:
$sql = 'SELECT * FROM employee WHERE telephone like ?';
will result the correct value of 7258787 but it will result the whole string(telephone numbers) that i type on a search box
Thank you in advance
This is the whole code:
This is not the answer but the whole script, (credits to Israel Barragan)
In my database I have employee as table and the columns are 'ID', 'NAME', 'TELEPHONE', and 'EMAIL'
<?php
header('Content-Type: application/json');
require_once 'Connectiondb.php';
$conn = dbConnect();
$OK = true; // We use this to verify the status of the update.
if (isset($_GET['telephone'])) {
// Create the query
$data = "%".$_GET['telephone']."%";
$sql = 'SELECT * FROM employee WHERE telephone like ?';
// we have to tell the PDO that we are going to send values to the query
$stmt = $conn->prepare($sql);
// Now we execute the query passing an array toe execute();
$results = $stmt->execute(array($data));
// Extract the values from $result
$rows = $stmt->fetchAll();
$error = $stmt->errorInfo();
//echo $error[2];
}
// If there are no records.
if(empty($rows)) {
echo json_encode( array('error'=>'There were not records','0'=> 'There were not records'));
}
else {
echo json_encode($rows);
}
?>
sorry I am new to stackoverflow,
You can bind the result in your query, and then get the last 4 digits from that to display.
For instance, you can do this
(not you aren't binding your parameters. You need to do something like this)
$stmt->bind_param("s", $data);
and then execute it like this:
$stmt->execute();
In your query instead of using select *, name the specific keys and then you can bind the result like this (assuming all you need is the phone number:
$stmt->bind_result($telephone);
then get the result like so:
$stmt->fetch();
then you can just get a substring off of $telephone like so (in php it is substr())
echo substr($telephone,-4);
(oh yeah and don't forget to close your object with
$stmt->close();
after you are done)
Edit:
Here's your query put together to get the substring
$data = "%".$_GET['telephone']."%";
$stmt = $conn->prepare("SELECT telephone FROM employee WHERE telephone like ?");
$stmt->bind_param("s", $data);
$stmt->execute();
$stmt->bind_result($telephone);
$stmt->fetch();
echo substr($telephone,-4);
$stmt->close();

mysqli counting results and fetching them

Hello I have a prepared statement and I need to count the number of results I get. In order to do this I use store_result and num_rows
$query = 'SELECT userId, promo, email FROM users WHERE active = ?';
$rsActivation = $db->prepare($query);
$rsActivation->bind_param('s', $actv);
$rsActivation->execute();
$rsActivation->store_result();
$totalRows = $rsActivation->num_rows;
This code manages to get me the number of rows. The problem is that if I do this I cannot use fetch() on $rsActivation. If I use fetch and not use store_result I cannot get the number of rows.
How can I accomplish both things?
Thanks
SOLVED:
Turns out my problem was I was trying to fetch the results as an associative array. Instead I used bind_result to assign values to variables. Then I was able to use store_result and num_rows to get the count and after that I used fetch() together with the variables I assigned in bind_result.
$query = 'SELECT userId, promo, email FROM users WHERE active = ?';
$rsActivation = $db->prepare($query);
$rsActivation->bind_param('s', $actv);
$rsActivation->execute();
$rsActivation->bind_result($userId, $promo, $email);
$rsActivation->store_result();
$totalRows = $rsActivation->num_rows;
while($rsActivation->fetch()){
echo "<p>". $userId ."</p>";
...
}
You can try using
...
$rsActivation->execute();
$results = $rsActivation->get_results();
$totalRows = $results->num_rows;
and you should be able to fetch using something like
$results->fetch_assoc(), $results->fetch_row(), etc.
Here's the doc for it: http://php.net/manual/en/class.mysqli-result.php

Categories