Last ID not showing - php

I am trying to grab the largest ID number from the database. The output should be 15 but it shows 1. My PHP script:
$sql = "SELECT MAX(id) AS id FROM employees";
$sql = $db->prepare($sql);
$lid = $sql->execute();
I am outputting it here:
<input type="number" name="id" value="<?php echo $lid; ?>" disabled>
I have also tried:
$sql = "SELECT id FROM employees ORDER BY id DESC LIMIT 1";
I tried the command on phpMyAdmin. It worked fine. The output was 15. So, I suspect that there are no problems in the query.
What is the problem, then?

You should FETCH i.e., $sql->fetch(PDO::FETCH_ASSOC);
So, You shall have something like
$sql = "SELECT MAX(id) FROM employees";
$sql = $db->prepare($sql);
$sql->execute();
$result = $sql->fetch(PDO::FETCH_ASSOC);
print_r($result);
Note : Simply $lid = $sql->execute(); means it will assign whether the query is executing or not.
As your query is executing it is returning true which is 1
Update : If you are not binding any values you don't even need to prepare, you shall fetch it directly like Adelphia said

$sql = $db->query("SELECT MAX(id) FROM employees");
$result = $sql->fetch(PDO::FETCH_ASSOC);
print_r($result);
No need for prepared statements since it's a static query.

Related

PHP get Single Value query using

I have to use this code to get single record but in check var_dump get all record please advice me if any one know
$selected_result = $mysqli_lib_obj->query("SELECT * FROM orders WHERE id='".$order_id."'");
The right Solution would be to limit your result by SQL:
if ($stmt = $mysqli_lib_obj->prepare("SELECT * FROM orders WHERE id=? LIMIT 1")) {
$stmt->bind_param("i", $order_id);
$stmt->execute();
$selected_result = $stmt->get_result();
$num_of_rows = $selected_result->num_rows;
while ($row = $selected_result->fetch_assoc()) {
// Do something with $selected_result
}
$stmt->free_result();
$stmt->close();
}
And always use prepared statment, if you don't ... you are letting hacker open doors to your database .
you can use
"SELECT * FROM orders WHERE id='".$order_id."' Limit 1"
The Actual problem lies in the query itself- try this way.
$sql = "SELECT * FROM orders WHERE id='$order_id' limit 1";

How to set result SQL distinct query to one or different variables?

I'm creating a mobile library app, and for one function of the app I am trying to receive the bookID for all books checked out by a certain user. I would like to be able to echo back the results from the query in a string format (preferably with spaces in between each separate book id) so I can deal with the data later on within the app.
Many of the answers I have found online have simply shown how to execute the query, but not how to use the data afterwards. Sorry if this is a simple question to answer, I am a huge novice.
<?php
require "conn.php";
$email = $_POST["email"];
$mysql_qry = "SELECT * FROM user_data WHERE email like '$email'";
$mysql_qry2 = "SELECT DISTINCT(bookID) AS bookID FROM books_checked_out
WHERE userID LIKE $user_id ORDER BY bookID DESC";
$result = mysqli_query($conn, $mysql_qry);
if(mysqli_num_rows($result) > 0) {
$row = mysqli_fetch_assoc($result);
$user_id = $row["user_id"];
$result2 = mysqli_query($conn, $mysqlqry2);
}
else
{
echo "Error, user name not found";
}
$conn->close;
?>
You could append your results into an array and display values using implode():
<?php
require "conn.php";
$email = $_POST["email"]; // You may test here : if (isset($_POST['email']))
$mysql_qry = "SELECT * FROM user_data WHERE email = '$email'";
$result = mysqli_query($conn, $mysql_qry);
if(mysqli_num_rows($result) > 0)
{
$row = mysqli_fetch_assoc($result);
$user_id = $row["user_id"];
$mysql_qry2 = "SELECT DISTINCT(bookID) AS bookID FROM books_checked_out
WHERE userID = $user_id ORDER BY bookID DESC";
$result2 = mysqli_query($conn, $mysql_qry2);
if(mysqli_num_rows($result2) > 0)
{
$ids = [];
while ($row = mysqli_fetch_assoc($result2)) {
$ids[] = $row['bookID'] ;
}
echo implode(" ", $ids) ; // print list of ID
}
else
{
echo "No books checked out!";
}
}
else
{
echo "Error, user name not found";
}
$conn->close;
NB: I used your code here, but, you should have to look to parameterized queries to prevent SQL injections.
Your query $mysql_qry2 should be defined after to get $user_id.
Your LIKE $user_id could be replaced by =.
First thing first, always sanitize your data:
$email = filter_var( $_POST['email'], FILTER_SANITIZE_EMAIL );
$user_id = preg_replace( "#[0-9]#", '', $row['user_id'] );
Use
DISTINCT bookID instead of DISTINCT(bookID)
From your query: $mysql_qry2 = "SELECT DISTINCT(bookID) AS bookID FROM books_checked_out WHERE userID LIKE $user_id ORDER BY bookID DESC";
If you're not getting any result or the returned result is empty but the user_id does exist, then I think the query format is wrong.
What you should do instead
Change the ORDER BY: The query may be correct but mysql returned an empty result because the result order does not match.
Try this
"SELECT DISTINCT bookID AS bookID FROM books_checked_out WHERE userID LIKE $user_id ORDER BY userID DESC";
"SELECT DISTINCT bookID AS bookID FROM books_checked_out WHERE userID LIKE $user_id ORDER BY `primary_key_here` DESC";
Replace <strong>`primary_key_here`</strong> with the primary key name.
Run the query without conditionals and inspect the result
$query = mysqli_query( $conn, "SELECT bookID FROM books_checked_out DESC" );
var_dump( $query );
Use the result to inspect the rest of the query.
Rather than using your own protocol/format use something like JSON or xml in your response to the request.
This will give you better maintainability in the long run and allow you to easily handle the response in the browser with javascript, and most browsers will give you a nice display of JSON objects in the dev console.
You'll have to extract the user id from the result of the first query or you could do a joined query instead.
$email = validate($POST['email']); //where validate() will try to prevent sql injection
//joined query
$query =
" SELECT bookID FROM user_data
INNER JOIN books_checked_out on user_data.user_id = books_checked_out.userID
WHERE user_data.email='$email'
";
//not sure whether that should be user_id or userID looks like you have mixed conventions
//books_checked_out.userID vs user_data.user_id ... check your database column names
//loop through results
// may be empty if user email doesn't exist or has nothing checked out
$result = $conn->query($query);
while($row = $result->fetch_assoc()){
$response[] = ['bookID'=>$row['bookID']];
}
echo json_encode($response);
When receiving the result in php you can use json_decode() or in javascript/ajax it will automatically be available in your result variable.
if things aren't working as expected it can be a good idea to echo the actual sql. In this case
echo 'SQL IS: '.$query;
and test it against your database directly (phpmyadmin/MySQL-Workbench) to see if you get any results or errors.

How do I count the number of rows in a MySQL Table?

I know that inside MySQL, you can use:
SELECT COUNT(*) FROM table
I have written the following code in PHP to display the number of rows on the page:
$sql = 'select * from users';
$data = $conn -> query($sql);
echo $data;
But when I run it, I get the following error:
Catchable fatal error: Object of class PDOStatement could not be converted to string in [Directory] on line 19.
I think the problem is that the returned value is not in string form. If that is correct, how would I be able to display the number of rows on the page?
If you want to count the rows you can do this with PDO:
$sql = 'select * from users';
$data = $conn->query($sql);
$rows = $data->fetchAll();
$num_rows = count($rows);
Well, you arent badly off, you are almost there:
$sql = 'SELECT COUNT(*) as numrow FROM users';
$data = $conn -> query($sql);
rows = $data->fetchAll();
Depending on the type of return data, you could use
$rows->numrow if the return data is an object
There are some easy and faster way to do this
COUNT the column in query and fetch
$sql = "SELECT COUNT(id) AS total_row FROM table_name";
$stmt = $conn->query($sql);
$stmt->execute();
echo $count['total_row'];
Using rowCount()
$sql = "SELECT * FROM table_name";
$stmt = $conn->query($sql);
$stmt->execute();
$count = $stmt->rowCount();
echo $count;

Mysql query variable syntax

I am trying to pass a variable to a very basic mysql query. but php doesnt return a true value. nothing.
i have checked everything
the problem is here.
the syntax of $a varible typing into mysql query
$result = mysql_query("SELECT id,floatingnumber FROM posts WHERE id='$a' LIMIT 1");
when i change $a to 22 it returns a value otherwise nothing.
exact query is here...
$a=$this->post_id;
$result = mysql_query('SELECT floatingnumber FROM posts WHERE id="'.$a.'" LIMIT 1')or die(mysql_error());
$row = mysql_fetch_row($result);
$sdfa=$a.'-'.$row[0];
$sdfa returns "86 - " without quotes 86 - space
so the problem is on the mysql fetch row please help
Have you tried echoing the query to see what the real value of $a is?
echo "SELECT id,floatingnumber FROM posts WHERE id='$a' LIMIT 1";
Have you tried checking for errors?
$result = mysql_query("SELECT id,floatingnumber FROM posts WHERE id='$a' LIMIT 1") or die(mysql_error());
Also, you shouldn't even be using mysql_* as it's deprecated.
This is how you'd do it in PDO:
$stmnt = $db->prepare("SELECT id,floatingnumber FROM posts WHERE id=:id LIMIT 1");
$stmnt->bindValue( ':id' , $a , PDO::PARAM_INT );
$stmnt->execute();
$result = $stmnt->fetchAll(PDO::FETCH_ASSOC);
typically when I'm writing in double quotes, simply putting in the variable works:
"... $1 ..."
but also, I originally learned it with brackets
"... {$1} ..."
you can try that. also, a handy way to write queries is store the query string in its own variable so you can easily print out the query and see what you wrote before submitting.
$query = "SELECT id,floatingnumber FROM posts WHERE id=$a LIMIT 1";
$result = mysql_query( $query );
This helps identify things like this.
try this
$result = mysql_query("SELECT id,floatingnumber FROM posts WHERE id='".$a."' LIMIT 1");
if your $a is a number then do like that
$result = mysql_query("SELECT id,floatingnumber FROM posts WHERE id= $a LIMIT 1");
EDIT :
your code is right
$row = mysql_fetch_row($result);
$sdfa=$a.'-'.$row[0];
the problem is in your sql or table because there is no floatingnumber where id is 86 .

PHP / MySQL results repeating

I'm having a problem with PHP. I want the following code to only show one result from the databse - the one that matches the siteID field. But instead it is returning all of the results from the database.
<?php
$siteID = $_GET['siteID'];
include 'connect.php';
$sql = "SELECT id, siteID,name,description,skills,extra1,extra2 FROM folio";
$queryresult = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_assoc($queryresult)) {
$id = $row['id'];
$siteID = $row['siteID'];
$name = $row['name'];
$description = $row['description'];
$skills = $row['skills'];
$extra1 = $row['extra1'];
$extra2 = $row['extra2'];
echo "<div id='title'>
<h5>$name</h5>
</div>
<div id='holder'>
<div id='blogleft'>
</div>
<div id='blogright'>
<p>Archive / Calendar<br /><br /> Add some sort of calendar or archive here; for previous blog posts.</p>
</div>
</div>";
}
?>
the url ends with "/work.php?siteID=pluggedin"
You need a WHERE clause.
$sql = "SELECT id, siteID, name, description, skills, extra1, extra2 FROM folio WHERE siteID='".$siteID."'";
Although i don't recommend this at all. Look up SQL injection if you don't know what I'm talking about. I would do a PDO statement instead.
Something like this:
$sql = "SELECT * FROM folio WHERE siteID=:siteid";
$sth = $dbh->prepare($sql);
$sth->bindParam(':siteid', $siteid, PDO::PARAM_STR);
$sth->execute();
$result = $sth->fetchAll();
print_r($result);
You can also do:
$result = $sth->fetch(PDO::FETCH_ASSOC);
which gives you an array with column names, similar to mysql_fetch_assoc, this will retrieve the next row, again similar to mysql_fetch_assoc.
You didnt used any where condition in your query.
Try this
$sql = "SELECT id, siteID, name, description, skills, extra1, extra2 FROM folio WHERE siteID='".(int)$_GET['siteID']."' ";
$sql = "SELECT
id,
siteID,
name,
description,
skills,
extra1,
extra2
FROM folio
where siteID = $siteID";
You just miss the where clause.
That's because you are selecting all your records in your table ... add a LIMIT clause to your query

Categories