PDO row count confusion - php

I am making a login page that checks for matching values in a database if the SELECT query returns a matching row with username and password then it will return a row count of 1. The way I have it coded right now when I echo the variable that stores the row count it will echo 26 for some reason and I'm not to sure why.
Would someone explain if I am doing something wrong or if this is normal behavior and where that value is coming from?
function checkLogin($conn,$myusername,$mypassword,$row,$row1){
try {
$sql = "SELECT COUNT(*) FROM CLL_users WHERE user_name = 'user' AND password = 'XXXX'";
if ($results = $conn->query($sql)) {
if($results->fetchColumn() > 0) {
$sql = "SELECT * FROM CLL_users WHERE user_name = 'user' AND password = 'XXXXX'";
foreach ($conn->query($sql) as $row)
{
$rowCount = count($row);
echo $rowCount;
print ("Username: " . $row['user_name'] . "<br>");
print ("Username: " . $row['password'] . "<br>");
}
echo $count;
}
else {
print "NO ROWS";
}
}
} catch (PDOException $e){
echo 'Connection failed: ' . $e->getMessage();
}
}

Your code, $rowCount = count($row);, is counting the columns in the current row - not the number of rows returned by the query.
On the same note, you are echoing a second count related variable, $count, but you neither declare-it nor increment it in your code. It looks like this one is the one that's supposed to be counting the number of rows you loop through. If this is true, you should set it as $count = 0; before the loop and use $count++; within it:
$count = 0;
foreach ($conn->query($sql) as $row) {
print ("Username: " . $row['user_name'] . "<br>");
print ("Username: " . $row['password'] . "<br>");
$count++;
}
echo $count;
Also, you're currently using PDO's rowCount prior to selecting a user, and you're using it properly. You could just store that result into a variable and use it to tell how many rows you are receiving:
$sql = "SELECT COUNT(*) FROM CLL_users WHERE user_name = 'user' AND password = 'XXXX'";
if ($results = $conn->query($sql)) {
$numRows = $results->fetchColumn();
if($numRows > 0) {
... rest of your code ....

function checkLogin($conn,$myusername,$mypassword,$row,$row1)
{
try
{
$sql = "SELECT COUNT(*) FROM CLL_users WHERE user_name = 'user' AND password = 'XXXX'";
if ($results = $conn->query($sql))
{
$count = $results->fetchColumn();
echo "$count\n";
if($count > 0)
{
$sql = "SELECT * FROM CLL_users WHERE user_name = 'user' AND password = 'XXXXX'";
foreach ($conn->query($sql) as $row)
{
print ("Username: " . $row['user_name'] . "<br>");
print ("Username: " . $row['password'] . "<br>");
}
}
else
{
print "NO ROWS";
}
}
}
catch (PDOException $e)
{
echo 'Connection failed: ' . $e->getMessage();
}
}

Related

using fetch twice in php to get the data

I'm trying to get a data from db, I would to say welcome $row['name'];
then in a loop need to print the items
if I did the below code, I will get all items except the first item, but if I deleted the $row2 with the welcoming name, I will get all items why ?
is there a way to use this $row = $SQL->fetch() for both?
<?php
session_start();
include "connect.php";
$access = isset($_SESSION["userid"]);
if ($access) {
$SQL = $dbh->prepare("SELECT * from items, users where userid = ?");
$SQL->execute([$_SESSION["userid"]]);
$row2 = $SQL->fetch();
echo "Welcome " . $row2['name'] . "<br>";
while ($row = $SQL->fetch()) {
echo $row["itemname"] . "-" . $row["price"] . "-" . $row["itemqty"] . "<br>";
}
}else{
echo "<h1>Not Logged in. Access denied.</h1>";
}
?>
When you run fetch() you are moving forward the pointer in the result set. So your first call to fetch() gets the first row, second gets the second row, etc.
Probably the easiest approach would be to pull all results into an array and then work with that.
<?php
session_start();
include "connect.php";
$access = isset($_SESSION["userid"]);
if ($access) {
$SQL = $dbh->prepare("SELECT * from items, users where userid = ?");
$SQL->execute([$_SESSION["userid"]]);
$data = $SQL->fetchAll();
$row2 = $data[0];
echo "Welcome " . $row2['name'] . "<br>";
foreach ($data as $row) {
echo $row["itemname"] . "-" . $row["price"] . "-" . $row["itemqty"] . "<br>";
}
} else {
echo "<h1>Not Logged in. Access denied.</h1>";
}

How to fetch main, sub and child categories from three tables. PHP MYSQLI

i am working on a project, in which i want to use Categories and their Sub and Child categories, i've created 3 tables ( MainCats, SubCats, ChildCats ).
now i want to fetch data from those tables and want to store in option of HTML.
Here is code PHP, MYSQLI and HTML code.
$cat_fetch = "SELECT categories, sub_categories, child_categories FROM categories.maincatSd, sub_categories.subcat_name, child_categories.child_cat_name";
$cat_run = mysqli_query($con, $cat_fetch);
echo "<option value='' >ڪيٽيگري چونڊيو</option>";
if(mysqli_num_rows($cat_run) >0){
while($cat_row = mysqli_fetch_array($cat_run)){
$cat_name = $cat_row['child_cat_name'];
$cat_name = $cat_row['subcat_name'];
$cat_name = $cat_row['maincatSd'];
//$cat_name = $cat_row['subcat_name'];
echo "<option value='".$cat_name."' ".((isset($Catagory) and $Catagory == $cat_name)?"selected":"")." >".ucfirst($cat_name)."</option>";
}
}else{
echo "<option name='Catagory' tabindex='2' id='Catagory' value=''>NoCat</option>";
}
From the output of your given image.. I don't feel you need to maintain any kind of relation at the time of fetching records from tables. It just needs to fetch records from those three tables & build the options list & print show on the web page. If that's exactly what you want, then check out this.
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
// Connect to DB
$mysqli = new mysqli('127.0.0.1', 'host', 'password', 'DB_Name');
if ($mysqli->connect_errno) {
echo "Error: Failed to make a MySQL connection, here is why: \n";
echo "Errno: " . $mysqli->connect_errno . "\n";
echo "Error: " . $mysqli->connect_error . "\n";
exit;
}
// ---Fetch all main category records---
$sql = "SELECT * FROM main_cat";
if (!$result = $mysqli->query($sql)) {
echo "Errno: " . $mysqli->errno . "\n";
echo "Error: " . $mysqli->error . "\n";
exit;
}
$totRecordsMainCat= array();
if($result->num_rows){
while($dataSource = $result->fetch_assoc()){
$totRecordsMainCat[] = $dataSource;
}
}
// ---Fetch all Sub category records---
$sql = "SELECT * FROM sub_cat";
if (!$result = $mysqli->query($sql)) {
echo "Errno: " . $mysqli->errno . "\n";
echo "Error: " . $mysqli->error . "\n";
exit;
}
$totRecordsSubCat= array();
if($result->num_rows){
while($dataSource = $result->fetch_assoc()){
$totRecordsSubCat[] = $dataSource;
}
}
// ---Fetch all Child category records---
$sql = "SELECT * FROM child_cat";
if (!$result = $mysqli->query($sql)) {
echo "Errno: " . $mysqli->errno . "\n";
echo "Error: " . $mysqli->error . "\n";
exit;
}
$totRecordsChildCat= array();
if($result->num_rows){
while($dataSource = $result->fetch_assoc()){
$totRecordsChildCat[] = $dataSource;
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<?php
echo "<select>";
echo "<option value=''>Select Category</option>";
foreach ($totRecordsMainCat as $key => $value)
{
$cat_name = $value['cat_name'];
echo "<option value='$cat_name'>$cat_name</option>";
}
foreach ($totRecordsSubCat as $key => $value)
{
$cat_name = $value['subcat_name'];
echo "<option value='$cat_name'>$cat_name</option>";
}
foreach ($totRecordsChildCat as $key => $value)
{
$cat_name = $value['childcat_name'];
echo "<option value='$cat_name'>$cat_name</option>";
}
echo "</select>";
?>
</body>
</html>
Why not do it using 3 different queries and nested loops..
SELECT * FROM main_cat
// Loop query result
SELECT * FROM sub_cat WHERE sub_cat_id = main_cat_id
// Loop query result
SELECT * FROM child_cat WHERE child_cat_id = sub_cat_id
// Loop query results

all of my php syntax is true,but update query is not working in while loop

This is cancel_order function,that also in it will call the increase_gameamount() function, i am trying to call increament_gameamount() function it works but when I try to call it from while loop nothing changes in database.
//cancel function
function cancel_order($ord) {
global $conn;
$bqty = 0;
$gqty = 0;
$res = array();
echo "entered cancel function " . $ord . "<br>";
$st = "select (B_qty+G_qty) newqt, B_GM_ID from tb_basket b, tb_game g
where b.B_GM_ID = g.G_ID
and B_O_ID='$ord' ";
$sql = $conn->prepare($st);
$sql->execute();
$sql->bind_result($newqt, $gid);
$i = 0;
while($row = $sql->fetch()) {
$res[$i][0] = $newqt;
$res[$i][1] = $gid;
$i++;
}
$j = 0;
$sql->free_result();
$sql->close();
while($j < sizeof($res)) {
echo $gd = $res[$j][0] . "<br>";
echo $qty = $res[$j][1] . "<br>";
increament_gameamount($gd, $qty);
$j++;
}
}
//increament function
function increament_gameamount($gameid, $new_qty) {
global $conn;
echo "entered increament_gameamount function";
echo $gameid;
echo $new_qty;
$varupdateqty = $conn->prepare("update tb_game set G_qty=? where G_ID=?");
$varupdateqty->bind_param("ss", $new_qty, $gameid);
$varupdateqty->execute();
echo "Prepare failed: (" . $conn->errno . ") " . $conn->error;
}
As I stated in the comments I think you are failing on the WHERE of your query because
echo $gd=$res[$j][0]."<br>";
is making $gd a string like 125<br> and the DB cannot find that.
Also, this would cause an error but if the type of your column is int and you pass:
echo $qty=$res[$j][1]."<br>";
again you make $qty something like 1000<br> and that would fail again this would be an error the above for ID check would not.
UPDATE
Just realized I did not specifially state the resolution. Set the variables then echo them and you should be all good.
$gd=$res[$j][0];
$qty=$res[$j][1];
echo $gd . "<br>" . $qty . "<br>";

Is it possible to assign sql table value to a variable in php?

Basically what I want is to assign the value of a field in my database to an variable. Can it be done in an effective way?
I was thinking something like:
$sql2 = mysql_query("SELECT * FROM rom WHERE idrom = 101");
while ($row = mysql_fetch_array($sql2)) {
$rom1 = $row['idrom'];
$status = $row['status'];
echo $rom1;
echo $status;
}
But this doesn't echo anything.
Edit:
I have gotten a bit longer on the way, now I am looking for a simpler way to assign the values to variables. As we speak I only need 4 values, but this still doesn't look like a very good way to accomplish what I want. Any better suggestions?
Heres what I got now:
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM rom WHERE idrom = 101";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$room101 = $row["idrom"];
$status101 = $row["status"];
echo "This is roomnumber ". $room101 . "!<br >";
echo "And the status of roomnumber ". $room101 ." is ". $status101 ."<br><br>";
}
} else {
echo "0 results";
}
$sql2 = "SELECT * FROM rom WHERE idrom = 102";
$result2 = $conn->query($sql2);
if ($result2->num_rows > 0) {
// output data of each row
while($row = $result2->fetch_assoc()) {
$room102 = $row["idrom"];
$status102 = $row["status"];
echo "This is roomnumber ". $room102 . "!<br >";
echo "And the status of roomnumber ". $room102 ." is ". $status102 ."<br><br>";
}
} else {
echo "0 results";
}
You can use bind_result to do that.
Please try this simple example, hope it run well :
$mysqli = mysqli_connect('host', 'user', 'pass','dbase')or die('Could not connect: ' . mysqli_error());
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
// Because you provide an Id in where clause, you can use it for the new variable
$output = array();
$id = 101;
$sql = "select idrom,status from rom where idrom=?";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param('i',$id);
$stmt->execute();
if ($stmt->errno == 0) {
$stmt->store_result();
// $stmt->bind_result($idrom,$status); // way 1
$stmt->bind_result($output[$id],$output["status".$id]); // way 2
while ($stmt->fetch()) {
echo $output[$id]." -> ".$output["status".$id]."<br />"; // So, your output variable will be like $output[101] for way 2
// or you defined it here like :
// $output[$idrom] = $idrom;
// $output["status".$idrom] = $status; // For way 1
}
} else {
return "Error: " . $sql . "<br>" . $stmt->error;
}
$stmt->close();
$mysqli->close();

AES_DECRYPT returns "Array" instead of decrypted data

I am trying to use AES_DECRYPT in MySQL to decrypt a successfully encrypted SSN. In the output I get the word "Array" instead of the actual data from that field. My PHP and MySQL knowledge is a bit rusty, so I'm sure it's something silly I overlooked. Any help would be appreciated.
OUTPUT:
verify_name other_names ssn dob
: test : test : Array : test
CODE:
$key="88b871WZ3SntWK67rN3l2J1SvMqsOjyk";
$SQLstring = "SELECT * FROM applications";
$QueryResult = #mysql_query($SQLstring, $conn) or die("Query Problem - "
. mysql_error($conn) . " - Error Number - "
. mysql_errno($conn));
echo "verify_name other_names ssn dob";
$num_result = mysql_num_rows($QueryResult);
for ($i = 0; $i < $num_result; $i++)
{
$row = mysql_fetch_array($QueryResult);
$SQLstring2 = "SELECT AES_DECRYPT(ssn,'$key') FROM applications WHERE name='" . $row["name"] . "'";
$QueryResult2 = #mysql_query($SQLstring2, $conn) or die("Query Problem - "
. mysql_error($conn) . " - Error Number - "
. mysql_errno($conn));
$num_result2 = mysql_num_rows($QueryResult2);
for ($j = 0; $j < $num_result; $j++){
$ssndecrypt = mysql_fetch_array($QueryResult2);
echo $ssndecrypt[0];
}
echo $row["verify_name"];
echo $row["other_names"];
echo $ssndecrypt;
echo $row["dob"];
It's because you're fetching the result as an array.
$ssndecrypt = mysql_fetch_array($QueryResult2);
...
echo $ssndecrypt;
It's echoing Array because you never reassign the $ssndecrypt variable.
The core of the problem, however, seems to be that you're needlessly complicating your queries. There's no reason to query the table twice when you can just do:
SELECT verify_name,
other_names,
dob,
AES_DECRYPT(ssn,'$key') AS ssn
FROM applications
This simplifies the code quite a bit:
$stmt = "SELECT verify_name, other_names, dob, AES_DECRYPT(ssn,'$key') AS ssn FROM applications";
$result = #mysql_query($stmt, $conn) or die("Query Problem - " . mysql_error($conn) . " - Error Number - " . mysql_errno($conn));
echo "verify_name other_names ssn dob";
while ($row = mysql_fetch_assoc($result))
{
echo $row["verify_name"];
echo $row["other_names"];
echo $row["ssn"];
echo $row["dob"];
}
Ideally, though, you should be using PDO instead of the mysql_* functions:
try {
$dbh = new PDO('mysql:host=localhost;dbname=mydb', $user, $pass);
foreach($dbh->query("SELECT verify_name, other_names, dob, AES_DECRYPT(ssn,'$key') AS ssn FROM applications") as $row) {
echo $row["verify_name"];
echo $row["other_names"];
echo $row["ssn"];
echo $row["dob"];
}
$dbh = null;
} catch (PDOException $e) { die("ERROR: " . $e->getMessage()); }

Categories