failed in count rows in php sql - php

Thank you in advance!
Please tell me! what is mistake in this code. I want to show total rows of sql on my site. I searched many of codes be like this but all failed. Please help me.
$servername = "localhost";
$username = "root";
$password = "";
// Create connection
$conn = new mysqli($servername, $username, $password, 'sahiwalservices');
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "hunnysheikh99";
;
mysqli_select_db("sahiwalservices", $conn);
$result = mysqli_query("select count(1) FROM login");
$row = mysqli_fetch_array($result);
$total = $row[0];
echo "Total rows: " . $total;
mysqli_close($conn);

Posting as a community wiki; I don't want rep from this.
mysqli_select_db() - The syntax for that is:
Db connection comes first
Database name is second
Yet, you don't need that line since you're already passing that in:
$conn = new mysqli($servername, $username, $password, 'sahiwalservices');
Then, you didn't pass db connection to the query.
Example from the manual:
if ($result = mysqli_query($link, "SELECT Name FROM City LIMIT 10"))
Reference:
http://php.net/manual/en/mysqli.query.php
Check for errors on the query also:
http://php.net/manual/en/mysqli.error.php

Related

How to fetch a single row from a MySQL DB using MySQLi with PHP? [duplicate]

This question already has answers here:
Single result from database using mysqli
(6 answers)
Closed 2 years ago.
I am using PHP with MySQli and I want to fetch a single row from the whole SQL DB, which fits in my condition. Just for a note, this is what my current database looks like :
I want to get that single row where, eg. txnid column's value == $txnid (a variable). I tried to build the SQL Query which would fit my requirements, and here's how it looks like : $sql = "SELECT * FROM 'table1' WHERE 'txnid' = " . $txnid;. When I raw-run this Query in phpMyAdmin, it works as expected. I just want to know, after I run the Query in PHP, how to fetch that row's data which came in as response from the Query using MySQLi?
This is the code which I am using to run the Query :
$servername = "localhost";
$username = "XXXXXXXXXXXXXX";
$password = "XXXXXXXXXXXXXX";
$dbname = "XXXXXXXXXXXXXXXX";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$txnid = $_GET['id'];
$sql = "SELECT * FROM `testtable1` WHERE `txnid` = " . $txnid;
if ($conn->query($sql) === TRUE) {
echo ""; //what should I do here, if I want to echo the 'date' param of the fetched row?
} else {
echo "Error: " . $sql . "<br>" . $conn->error . "<br>";
}
Add LIMIT 1 to the end of your query to produce a single row of data.
Your method is vulnerable to SQL injection. Use prepared statements to avoid this. Here are some links you can review:
What is SQL injection?
https://en.wikipedia.org/wiki/SQL_injection
https://phpdelusions.net/mysqli_examples/prepared_select
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = new mysqli($servername, $username, $password, $dbname);
$conn->set_charset("utf8mb4");
$txnid= $_GET['name_of_txnid_input_field'];
// prepare and bind
$stmt = $conn->prepare("SELECT * FROM `testtable1` WHERE `txnid` = ? LIMIT 1");
$stmt->bind_param("i", $txnid);
// set parameters and execute
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
echo $row['date_field_you_want_to_display'];
$txnid = $_POST['txnid'];
$sql = "SELECT * FROM tableName WHERE txnid = $txnid";
$result = $conn->query($sql);

how to include a php variable as part of a table name?

I have a site where I needed to use separate table names for each of my clients because the data has to be updated all the time with a manual import.
example:
kansas_users
newyork_users
I have set a global variable as $client which will create the state name on all pages so if I echo "$client"; then I will see "kansas" for example on any page.
I would like to include this variable as part of my SQL query if possible to make it easier to code:
SELECT "nick, firstname, lastname, cell
FROM database.$client_members
where active =1 and id = $user->id";
Is this possible or even safe to do?
Yes it possible you can do some thing like below
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$client = 'kansas';
$table_name = "database." . $conn->real_escape_string($client) . "_members";
$query = sprintf("SELECT nick, firstname, lastname, cell
FROM %s WHERE active = 1 and id = ?", $table_name);
// prepare and bind
$stmt = $conn->prepare($query);
$stmt->bind_param("i", $user->id);
But i think you should seriously consider normalizing your database to avoid such issues

No Database selected error in PHP with MySQLi [duplicate]

This question already has answers here:
How to make mysqli connect function?
(2 answers)
Closed 6 years ago.
I have to select data from MySQL Database. I have been looking for the answer, but still haven't found any. I am learning from W3School
My MySQL doesn't have any username or password, so my code looks like this:
<?php
$servername = "localhost";
$dbName = "db_Test";
//Create Connection
$conn = mysqli_connect($servername, $dbName);
//Check Connection
if(!$conn){
die("Connection Failed. ". mysqli_connect_error());
}
$sql = "SELECT ID, Name, Category, Description, Price FROM items";
$result = mysqli_query($conn, $sql);
if(!$result){
die(mysqli_error($conn));
}
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_assoc($result)){
echo "ID: ".$row['ID']." Name: ".$row['Name']." Category: ".$row['Category']."<br>";
}
}
?>
First I got this error
mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in
On further tracing it back in the stack, I got this:
No database selected
I don't know what I'm doing wrong. So can you explain it to me and give me the solution. Thanks in advance
Set mysql username and passwork something like this.
$username = "root";
$password = "";
And set connection like this.
$conn = mysqli_connect($servername, $username, $password, $dbname);

Error: mysql_fetch_array() expects parameter 1 to be resource

So here is my code:
$sql = "SELECT * FROM `items`";
$result = mysqli_query($conn, $sql);
while($prommes = mysql_fetch_array($result)){
}
When I'm running it. I'm getting this error:
mysql_fetch_array() expects parameter 1 to be resource.
Is it something wrong with my database?
And here is my connection which Irequire in the html document. Can it be something here which makes the query not working?
$servername = "localhost";
$username = "root";
$password = "";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// echo "Connected successfully";
You never select a database, as far as I can tell, so $result is not a resultset (because the query never executes properly). It is probably false instead. You can var_dump it to verify that. Try adding the database name in the query. If your database is named db, for example:
SELECT * FROM `db`.`items`;
If you don't want to explicitly specify the database name every time, you'll just want to add the database name to the MySQLi connection string, as shown:
http://php.net/manual/en/mysqli.query.php
In the while loop, mysql_fetch_array is incorrect. It should be
while($prommes = mysqli_fetch_array($result))
Additonally your connection needs to be
$conn = mysqli_connect($servername, $username, $password, $database);
where $database is the name of your database (not the hostname).
As an aside, this can be better avoided using an object orientated approach. So for example, your connection could be;
$conn = new mysqli($servername, $username, $password, $database);
and your query and loop could be;
$result = $conn->query($sql);
while($prommes = $result->fetch_array())
Hope this helps.

Simple and effective way to echo the result of a query in PHP?

I'm new to MySQL and PHP and I m struggling to echo my queries (the results not the text!)
I have searched for this but nothing seems to work properly, the best I managed to do was echoing the text of the query. I might have some fatal mistakes but here is my code:
<?php
$username = "root";
$password = "";
$hostname = "localhost";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
$selected = mysql_select_db("atoma",$dbhandle)
or die("Could not select atoma");
$sql1 = mysql_query("SELECT (MAX(GRADE)) as maximum FROM thema3");
$r = mysql_fetch_array($sql1); // will return the result
echo $r['maximum'];
$sql2 = "SELECT COUNT(DISTINCT NAME) FROM thema2";
$sql1 = "SELECT AVG(GRADE) FROM thema3";
mysql_close($dbhandle);
?>
I get nothing as a result.
I have these 3 queries and all I want is just to print their results. I've written code for echoing only one of the 3 since the other 2 will be echoed as the first one I want to believe.
Your code seems incorrect because, the connection is mysqli and fetching is using mysql
$conn = new mysqli($servername, $username, $password, $dbname);
....
$sql1 = mysql_query("SELECT (MAX(GRADE)) as maximum FROM thema3");
$r = mysql_fetch_array($sql1); // will return the result
A full example of W3Schools
<?php
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
http://www.w3schools.com/php/php_mysql_select.asp
When you use max, avg, etc you pull only one result, so with the $result[0] you has the result you want
Edit:
If you're new, maybe you come to see read this:
http://codular.com/php-mysqli
So A) would leave using an outdated way to call the database, and B) with this in principle bringing the first row you would have the result of AVG, MAX, etc. when only one row which returns you if you make this types of sentences ;)

Categories