No getting result from query on host database - php

On my test machine the query for finding a users last_name and id works fine. I cannot figure out why it will not work on my host.
For this table
students(
id VARCHAR(5) NOT NULL,
first_name VARCHAR(20) NOT NULL,
last_name VARCHAR(40) NOT NULL,
grade SMALLINT UNSIGNED NOT NULL,
PRIMARY KEY (id)
);
I run this query and there is no problem.
$sql="SELECT * FROM $tbl_name WHERE last_name ='$myusername' and id ='$mypassword'";
$result = #mysqli_query ($dbc, $sql);
mysqli_close($dbc);
if(!is_object($result) || $result->num_rows != 1)
{
$errors[] = 'No entries found, maybe capitalize your last name.';
}
else
{
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
$_SESSION['username'] = $_POST['username']; //last name
$_SESSION['firstName'] = $row['first_name'] ;
}
On the host though, there is no rows in the result.
However, I ran this set of code and all the entries show up. Why does the query not work?
$sql="SELECT * FROM $tbl_name";
$num_results = mysqli_num_rows($result);
for ($i=0; $i<$num_results; $i++)
{
$row = mysqli_fetch_assoc ($result);
print stripslashes($row['last_name'])." ".stripslashes($row['id']);
}
By the way, the username is a persons last name and their password is their id. I am not that experienced with PHP and MySql, but this logically does not make sense to me.

Should be using mysqli_query.
Just please be sure to change $link with the connection result (of mysqli_connect).
Code:
$sql = "SELECT * FROM $tbl_name";
$result = mysqli_query($link, $sql);
$num_results = mysqli_num_rows($result);
$i = 0;
while ($row = mysqli_fetch_assoc ($result)) {
print stripslashes($row['last_name'])." ".stripslashes($row['id']);
$i++;
}

I am not sure about it, but I think you're using the wrong language for a mysql host, for example the loop isn't supposed to be in SQL language. As far as I know, this looks like C or C++ (it could depend of what kind of database you're currently using).
But what you need to know is that with this query you need to know the exact name and the exact password. Just in case, do this.
The query in SQL language, should be written it as it follow :
SELECT * FROM students WHERE last_name = "ifyouknowit" OR password="ifyouknowit";
You'll be sure to have at least one result, and it would show up the whole concerned lines as you're calling the " * ". So you don't really need a parameter, as the password is supposed to be unique to everyone.. (Theorically).
In another case, try to add one more column and call it USERID or something like this, to set a unique referent number. So you'll be sure not to be confusing between two people having the same name and last name which could happen easily.
Also, be sure to use the write syntax correctly about the name (like the capital letters are important somehow).
And I notice also that you don't have any password column in this table. Where is it stored? In anycase, with this query you'll still have results.
"students(
id VARCHAR(5) NOT NULL,
first_name VARCHAR(20) NOT NULL,
last_name VARCHAR(40) NOT NULL,
grade SMALLINT UNSIGNED NOT NULL,
PRIMARY KEY (id)
);"
You should call the password database from where it's stored. Put more informations about the other tables and then I'll write a complete query for you.

This code was clearing the variables values so nothing was being searched for in the query. I thought this was standard code that should be used, apparently not.
//prohibit sql injection
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);

Related

How do I write a JSON_TABLE query in php?

I am running this query in phpmyadmin (mysql 8.0.13):
SELECT people.* FROM product, JSON_TABLE(attributes, '$.people[*]' COLUMNS (firstname VARCHAR(40) PATH '$."firstname"')) people
It works as expected but when I try the same query in php nothing works.
$result = mysqli_query($conn, "SELECT people.* FROM product, JSON_TABLE(attributes, '$.people[*]' COLUMNS (firstname VARCHAR(40) PATH '$."firstname"')) people");
while($row = mysqli_fetch_assoc($result))
{
$firstname = $row['firstname'];
}
Can someone please tell me what I am doing wrong?
$result = mysqli_query($conn, "SELECT people.* FROM product, JSON_TABLE(attributes, '$.people[*]' COLUMNS (firstname VARCHAR(40) PATH '$.firstname')) people");
You had a syntax error in your query. You mixed double and single quotes in the firstname. Give a try to the above query and let me know if it works.

Count num of rows in PDO prepared statements

I have two questions regarding codes below.
I know the second code is correct but not sure if first is also correct both do same thing first one is just easy to write.
I want to count the number of rows in database for the selected element if ($query->num_rows == 1) { doesn't work so how to rowcount for the code below.
First code:
$query = $db->prepare("SELECT * from users WHERE username = :username");
$query->execute(array(':username'=>$un));
Second:
$result = "SELECT * from users WHERE username = :username";
$query = $db->prepare( $result );
$stmt->bindValue(':username'=>$un);
$query->execute($stmt);
You don't need the row count. You need just the row itself. So, just fetch it, from the first variant, which is ok.
As of the row count, you are supposed to be able to get the proper function name from manual.
$query = $db->prepare("SELECT 1 from users WHERE username = ?");
$query->execute(array($un));
if ($query->fetch())
{
// found
}
First, if you want to ensure that only one username is selected, you can use LIMIT in your MySQL statement
SELECT * from users WHERE username = :username ORDER BY id DESC LIMIT 1
Or:
SELECT DISTINCT(username) from users WHERE username = :username```
Even better, when creating the table, you can require that the username is unique:
CREATE TABLE users (
id INT NOT NULL AUTO_INCREMENT,
username VARCHAR(255) NOT NULL,
...
PRIMARY KEY (id),
);
Second, to verify that a row was actually retrieved from the dabase, you can use fetch:
$query = $db->prepare("SELECT * from users WHERE username = :username");
$query->execute(array(':username'=>$un));
$rows = $query->fetch(PDO::FETCH_NUM);
if($rows[0]) {
// Row exists
}

INSERT and UPDATE statements passing wrong data into database

I have this DB table reset_attempts and inside it has an
id : int(10) auto_increment
reset_counter : int(10) default 1
reset_time : timestamp current_timestamp
ip : varchar(255)
and I have this simple php code
$sql = "SELECT * FROM reset_attempts WHERE ip = '$ip'";
$query = mysqli_query($db_conx, $sql);
$num_rows = mysqli_num_rows($query);
$row = mysqli_fetch_array($query);
$reset_counter = $row['reset_counter'];
$reset_time = $row['reset_time'];
if ($num_rows == 0) {
$sql = "INSERT INTO reset_attempts (reset_counter, reset_time, ip) VALUES ('1',now(),'$ip')";
$query = mysqli_query($db_conx, $sql);
} else if ($num_rows == 1) {
$reset_counter = $reset_counter + 1;
$sql = "UPDATE reset_attempts SET reset_counter = '$reset_counter', reset_time = now() WHERE ip = '$ip'";
$query = mysqli_query($db_conx, $sql);
}
This is just a piece of whole php file..this is only the problem code..of course it has the db connection and I take the ip correctly..The problem is when I hit submit it will execute the first if statement, it executes correctly except that the reset_counter value it passes it to DB always as zero and all the other fields are correctly.
When it executes the second if statement again it's not updating the reset_counter field and set it to zero. I don't know where is the problem. Maybe is so simple and I can't see it because I am searching it so much! Anyway thanks in advance!
As per discussion in comments (between the OP and I), the shown snippet of code works on its own and have determined that something else is causing this (in unshown full code).
Let's consider this question to be closed, until the rest of the (OP's) code can be investigated further.
Last two comments between OP and I:
Me: Ok, this is probably going to be my last suggestion, because I don't know what else could be causing this. Can you try and run that snippet on its own (your posted code), without the rest of your code, and see if it will work on its own? If it does work, then you'll know right away that something else in your full code is causing this.
OP: You are right..it was the last thought that did not came to my mid trying it pfff..the snippet works fine on it's own...so it's something else in my code as you said.. :/ I am sorry for that I didn't test it from start...at least now I know what to search..!
For the first time there is no record in the database for that ip so $row['reset_counter'] has value zero and you enter the value zero in the database. Then when you again submit then it fetches the same value from the database and as it enters 0 for reset_counter so when you do
$row = mysqli_fetch_array($query);
$reset_counter = $row['reset_counter'];
It fetches that row with 0 for reset_counter and update it to again zero
Update
Add these this inside else statement if you need it anywhere in your code otherwise remove this too
$reset_time = $row['reset_time'];
And remove
reset_counter = $row['reset_counter'];
Use this code
$sql = "SELECT * FROM reset_attempts WHERE ip = '$ip'";
$query = mysqli_query($db_conx, $sql);
$num_rows = mysqli_num_rows($query);
$row = mysqli_fetch_array($query);
if ($num_rows == 0) {
$sql = "INSERT INTO reset_attempts (reset_counter, reset_time, ip) VALUES ('1',now(),'$ip')";
$query = mysqli_query($db_conx, $sql);
} else if ($num_rows == 1) {
$reset_time = $row['reset_time'];
$sql = "UPDATE reset_attempts SET reset_counter = reset_counter+1, reset_time = now() WHERE ip = '$ip'";
$query = mysqli_query($db_conx, $sql);
}
I don't know exactly what goes wrong in your code but I think you are using too much PHP and too little MySQL. I have a couple of changes I would propose
First, most times you would do the update, right? Then I would just skip the SELECT, do the UPDATE and then ask the driver for number of rows updated. If it's 0 then do the INSERT.
Second. When you do the update just increment inside MySQL, no need to do that in PHP.
UPDATE reset_attempts SET reset_counter = reset_counter+1, reset_time = now() WHERE ip = '$ip';
Otherwise two parallel calls your page might just count as one in the database.
Third, if you reset_counter isn't already an integer change it. From your code it looks like it's a char or varchar and it just doesn't make any sense to store a counter as text.

echo data from database PDO

Trying to echo out in this case the users username. I've had a friend help me, but he seems like he can't solve it either. So I'm asking you guys.
Basically, I'm right now trying to take the username from the person who logged in. The sessions which get set when you log in is called "user_id". Never mind, this is my code`
$user = $dbh->prepare("SELECT `username` FROM `users` WHERE `user_id` = ':user_id'");
$user->bindParam(':user_id', $_SESSION['user_id'], PDO::PARAM_STR);
$user->execute();
while($row = $user->fetch(PDO::FETCH_NUM)){
$user_name = $row['1'];
}
?>
<h3>Welcome <p class="blue"><?php echo $user_name;?></p></h3><br/>`
With this, I get this error:
Undefined variable: user_name in
i know this is wrong, since it obviously doesn't work. But I've also tried setting sessions at that place in the while loop like this.
$_SESSION['user_id'] = $row['username'];
but then I get a blank result. Which means that there's no value of the session, or am I wrong?
You don't need quotes in the $row variable
while($row = $user->fetch(PDO::FETCH_NUM)){
$user_name = $row[0];
}
In your original code, its $row['1']. You don't have a field called 1 so remove the single quotes from around it.
Also, rows (when numerically indexed) start at 0, so the username field would be $row[0]
EDIT
And to touch on what #jeroen mentioned, in your SQL query, you shouldn't have quotes around your parameterized values:
$user = $dbh->prepare("SELECT `username` FROM `users` WHERE `user_id` = :user_id");
When there is no data returned, while won't be executed even once.
So, check your query.
To start you never checked if the user actually exists in the database, so what I personally would do is prepare the query and set a value to the default username- run the query and if no rows are returned then do nothing, if we actually have a row then fetch the corresponding column value in that row ('username') and set the variable to that.
$user = $dbh->prepare("SELECT `username` FROM `users` WHERE `user_id` = ':user_id'");
$user->bindParam(':user_id', $_SESSION['user_id'], PDO::PARAM_STR);
$user->execute();
$UserName = "Unknown!";
while( $row = $user->fetch(PDO::FETCH_NUM) ){
$UserName = $row['username'];
}
echo '<h3>Welcome <p class="blue">{$UserName}</p></h3><br/>';

Issues with when writing to database

I'm unable to write to my database while using this script that I whipped up earlier.
<?php
include("db.php");
if($_SERVER["REQUEST_METHOD"] == "POST")
{
// Data sent from form, then posted to "admin" table in database
$name = mysql_real_escape_string($_POST['name']);
$description = mysql_real_escape_string($_POST['description']);
$author = mysql_real_escape_string($_POST['author']);
$image = mysql_real_escape_string($_POST['image']);
$category = mysql_real_escape_string($_POST['category']);
$sql = "INSERT INTO admin(name,description,author,image,category) VALUES('$name','$description','$author','$image','$category');";
$result = mysql_query($sql);
header("Location: video.php?file=' . $filename . '");
}
?>
And here's my SQL:
CREATE TABLE admin
(
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(50) UNIQUE,
description VARCHAR(50) UNIQUE,
author VARCHAR(50) UNIQUE,
image VARCHAR(50) UNIQUE,
category VARCHAR(50) UNIQUE
);
Everything is submitted with POST via an HTML form. I'm not really sure what I'm doing wrong, so that why I'm wondering what you guys think. Any thoughts?
$result = mysql_query($sql) is not valid (no connection specified).
It needs to be $result = mysql_query($sql, [CONNECTION]);
There may be other issues, but that's an obvious one.
Follow these steps:
Open a MySQL connection (if not omitted in the snippet)
Check your MySQL statement by using var_dump($sql)
Check for the return value of mysql_query(), should be true if the INSERT statement succeeded.
Check for the number of rows affected by the INSERT statement: mysql_affected_rows()
Note:
I'm pretty sure that your INSERT statement fails because all your columns are defined as UNIQUE. As soon as you already have an author with the same name the statement fails!
$auhtor=mysql_real_escape_string($_POST['author']);
The Author variable is spelled wrong.

Categories