How to figure out if row is equal to a specific input - php

I am trying to figure out how to get a specific input from a database and fetching it. If its not equal to 1 do function.
Example code:
$admincheck = "SELECT admin FROM users";
if($admincheck == 0){
echo "<p style='font-size:40px;text-align:center;'><strong>Du har ikke tilgang til å se dette innholdet.</p>";
In my user database i have Username, Password, Admin.
Admin is default 0. If the number is 1 i want to grant access to that specific website.

You will need to connect to the database and then run your query. You will get a resultset back and you get the value you want from the resultset. Then you can do whatever you need to do with the result.
Try something like the following (most of this was pulled from: https://www.php.net/manual/en/mysqli.query.php):
$mysqli = new mysqli("localhost", "username", "password", "databasename");
$username = "whatever username you are checking";
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
if ($result = $mysqli->query("select admin from users where username='$username'")) {
while($obj = $result->fetch_object()){
$is_admin = $obj->admin;
if ($is_admin === 0){
echo "whatever html you want to echo";
}
}
/* free result set */
$result->close();
}
$mysqli->close();
You will need to make sure that your database prevents more than one person from having the same username, I recommend adding a unique index on username. Usually people have an additional column called "id" that auto_increments so that it will always be a unique number and that's a lot easier to work with.
I recommend abstracting this logic into a separate file that will be responsible for verifying that the user is authenticated.

this query is not for one column
$admincheck = "SELECT admin FROM users";
you should add a where condition and after that, you can check if($admincheck == 0)
<?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);
}
$sql = "SELECT admin FROM users where id=1";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
if($row->admin_check == 1){
/////this is your code to check admin...
}
}
} else {
echo "0 results";
}
$conn->close();
?>

Related

Show records based on a catergory value

I have a table with data in it ID, Name, Task, Business. I am trying to show all records based on the Business category.
I would like a separate page to show all the businesses and then when you click on the name it displays all the records associated with it.
I am unsure of how to display this.
I can almost see what I want in SQL workbench but I am unsure how to do this is php code..
SELECT * FROM job2 where business="MR Plumber"
I want the "Mr plumber" to be what ever business I click on the business page.
I would like to have a page to list the businesses and then when I click on the business name link and displays all records associated to it.
Try this.
<?php $servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
echo "error";
}
$sql = "your sql";
$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["column_name"];
}
} else {
echo "0 results";
}
$conn->close();
?>

phpMyAdmin: one table in database work, another doesn't

I've created an app were you can register as a user. You can sign up and then you're in the database "myAppDataBase" in "firsttable". A second table contains a list of lets say other important users that I manually created in the PHPmyAdmin-Website/"App". This table is called "secondtable".
My code to get the data is as follows:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "mydatabas";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}else{
//Print ("successfully connected");
}
$query = "SELECT * FROM firsttable";
$result = mysqli_query($conn, $query) or die("Error: " . mysqli_error($query));
$num = mysqli_num_rows($result);
$rows = array();
while ($r = mysqli_fetch_assoc($result))
{
$rows[] = $r;
Print ("sf");
}
Print json_encode($rows);
mysqli_close($conn);
?>
The only thing i changed was this line: THIS WORKS
$query = "SELECT * FROM firsttable";
But when I change it to this it won't work anymore.
$query = "SELECT * FROM secondtable";
Any help?
Change this:
mysqli_error($query)
With this:
mysqli_error($conn) // with your connection
Explanation:
mysqli_error() function needs connection link identifier not your query as param.
Mysqli_error PHP Manual
I SOLVED IT! Somehow, my second wasn't encoded the right way. I simply added this coder and it worked:
mysqli_set_charset($conn, 'utf8mb4');
Thanks for all you help though. ;)

If variable is in db then stop- if variable is not- then enter it

i have been trying to get this script done for a while now - im kind of new to php and mysql but i have been trying to get this to check the db for the username and then if the username exists - stop checking the db and if it doesn't exists add it to the db.
here is my code:
//input from application
$test = "wheelsmanx";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT mainusername FROM CCCpro_test";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
if ($row["mainusername"] === $test) {
echo "User Name Already In Use.";
}if($row["mainusername"] !== $test){
echo "this statement";
[code that inserts into db i can do this part myself]
}
}
$conn->close();
} else {
echo "0 results";
}
$conn->close();
The problem with your code is that you do the INSERT of the new name inside an if statement that has confirmed the existence of that user already. In addition I think you messed up your SELECT statement by selecting all the users.
Look into INSERT ON DUPLICATE for a better way to do it, or revise your code as below.
$sql = "SELECT mainusername FROM CCCpro_test WHERE mainusername = $test";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "User Name Already In Use.";
}
else{ //no rows selected therefore the user doesn't exist
[code that inserts into db i can do this part myself]
}
$conn->close();
PLEASE READ I have somewhere to go so I am being lazy so I did not bind the $test variable therefore DO NOT copy and paste this code without updating it to bind the $test variable. Please read this post about PDO and variable binding to prevent SQL injection.
here is my full working code if anyone needs it - it uses the post method - from an html form .... in case some one needs to hack it to pieces for something else
well guys i appreciate all of your help :D but i have found an answer or a way around it i suppose- i thought of it all night and day on how i could make it work and i came up with this
$servername = "127.0.0.1";
$username = "TESTUSER";
$password = "TESTPASS";
$dbname = "TESTDB";
$testusername = $_POST['mainusername'];
$testpassword = $_POST['mainpassword'];
//input from application
$test = $_POST['mainusername'];
$test2 = "0";
//Count switch
$countswitch = "0";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql1 = "INSERT INTO CCCpro_test ( mainusername, mainpassword ) VALUES ('$testusername','$testpassword' )";
$sql = "SELECT mainusername FROM CCCpro_test";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
if ($row["mainusername"] === $test) {
echo "Im Sorry Username Already In Use";
$countswitch ++;
}
}
if($countswitch == $test2){
echo "User Name Registered";
$db_handle = mysql_connect($servername, $username, $password);
$db_found = mysql_select_db($dbname, $db_handle);
if ($db_found) {
$result1 = mysql_query($sql1);
mysql_close($db_handle);
}
}
if ($countswitch == 3){
echo "this";
}
} else {
echo "0 results";
}
$conn->close();

Display a row of the current session

So in my users table there are 5 columns. Id, username, password, email and money.
The money column is an int which is supposed to show how much money that user has. (I'm making a game).
I'm trying to make a script which displays how much money the user in the current session has, but my script displays the money for every user.
My code:
<?php session_start(); ?>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "database4";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM users";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row['money'];
}
} else {
echo "You have no items yet!";
}
$conn->close();
?>
How would I do this?
You've missing where clause in your select query.
it would be something like:
$sql = "SELECT * FROM users WHERE id='{$_SESSION['user_id']}'";
$result = $conn->query($sql);
You just need to replace $_SESSION['user_id'] with the user id you are storing while user gets logged in.
EDIT:
Make sure you have session_start(); where page starts, additionally you may create unique index on email column in users table.
$sql = "SELECT * FROM users WHERE email='{$_SESSION['email']}'";
$result = $conn->query($sql);

mysqli create link based on row

I want to create an link based on row value, AND - MORE IMPORTANT, add an variable - if row empty, then this text... if row have some value, display this....
//I NEED TO GET THIS DISPLAY:
// if row season is empty, the resulting link must be
// web.com/MOVIES/".$row["title_id"]."
// if row season have some value, then the link must be: //web.com/SERIES/".$row["title_id"]."/SEASON/".$row["season"]."/EPISODE/".$row["episode"]."
This is the base code.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "dbname";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, type, label, title_id, season, episode, approved FROM links order by id desc LIMIT 30 OFFSET 50";
$result = $last_id = $conn->query($sql);
if ($result->num_rows > 0)
{
echo "<table><tr><th>ID</th><th>Label</th><th>URL</th><th>Season</th><th>Episode</th><th>Approved</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>".$row["id"]."</td><td>".$row["label"]."</td>";
// --------------------------------------------------------------
echo "<td><a href='http://web.com/(VARIABLES HERE)'>";
echo " ".$row["title_id"]."</a></td>";
// --------------------------------------------------------------
//I NEED TO GET THIS DISPLAY:
// if row season is empty, the resulting link must be
// web.com/MOVIES/".$row["title_id"]."
// if row season have some value, then the link must be:
//web.com/SERIES/".$row["title_id"]."/SEASON/".$row["season"]."/EPISODE/".$row["episode"]."
// -----------------------------------------
echo "<td>".$row["season"]."</td><td>".$row["episode"]."</td><td>".$row["approved"]."</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
?>
As is stated in the comments, you are using a reserved MySQL keyword: type. So your query is not working properly. You can't tell because you haven't set up any checks to make sure it is working. you can either put backticks around it like so:
SELECT id, `type`
or change the name of the key in your database (I'd recommend this approach, something like titleType). Until you fix this, nothing will work in your PHP.
Once you have fixed this, as for how to generate your results, you could do something like this inside your while loop (I'm assuming your mean the episode value):
if (empty($row['episode'])) {
echo 'web.com/MOVIES/'.$row["title_id"];
}
else {
echo 'web.com/SERIES/'.$row['title_id'].'/SEASON/'.$row['season'].'/EPISODE/'.$row["episode"];
}
THIS IS THE CORRECT FULL CODE.
<?php
$servername = "localhost";
$username = "WRITE YOUR DB username ";
$password = "WRITE YOUR DB password";
$dbname = "WRITE YOUR db name";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, label, title_id, season, episode, approved FROM links order by id desc LIMIT 30 OFFSET 1";
$result = $last_id = $conn->query($sql);
if ($result->num_rows > 0)
{
echo "<table><tr><th>ID</th><th>Audio</th><th>URL</th><th>Temporada</th><th>Episodio</th><th>Aprobado</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>".$row["id"]."</td><td>".$row["label"]."</td>";
echo "<td><a href=";
if (empty($row['episode'])) {
echo '/peliculas-online/'.$row["title_id"];
}
else {
echo '/series-online/'.$row['title_id'].'/seasons/'.$row['season'].'/episodes/'.$row["episode"];
}
echo ">".$row["title_id"]."</a></td>";
echo "<td>".$row["season"]."</td><td>".$row["episode"]."</td><td>".$row["approved"]."</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
?>

Categories