Make a php variable with MySQL - php

I have a Problem and I don't know how to solve it.
I try to make a simple if statement with a php variable. The Variable contains a MySQL SELECT value.
$adminarray = $mysqli->query("SELECT admin FROM user WHERE name LIKE '$username'");
$currentuser = mysqli_fetch_row($adminarray);
$adm = $currentuser[0];
echo "<form action='?delete1' method='post' style='visibility:";if ($adm = 1){echo "block";}else{echo "hidden";}echo "'>
I try to hide the button for non admins ($adm = 0) but it is not working. The IF Statemant always returns a "true". even if $adm is 0.
I know the code isn't that good, but I'm still learning. So if you can give some tips :)
Thanks for answering

Firstly, use ternary operator for inline comperison and read about comparison operators in PHP
Secondly, do not write a few strings that separated by semicolon together. Semicolon in PHP means end of instruction and it's better to write each in new line, so it will be easier to read and maintain the code
Thirdly, always escape data in SQL queries and check type of variable before indexing it as array(is_array, isset)
Finnaly, use IDE (PhpStorm, NetBeans etc) it will help you to prevent doing such mistakes
$username = $mysqli->real_escape_string($username);
$adminarray = $mysqli->query("SELECT admin FROM user WHERE name LIKE '$username'");
$currentuser = mysqli_fetch_row($adminarray);
$adm = is_array($currentuser) ? $currentuser[0] : null;
$visibility = $adm == 1 ? "block" : "hidden";
echo "<form action='?delete1' method='post' style='visibility:$visibility'>";
It is also worth noting that prepared statements are preferable to plain SQL queries when you are using parameters. In that case code will look slightly different:
$stmt = $mysqli->prepare("SELECT admin FROM user WHERE name LIKE ?");
$stmt->bind_param('s', $username);
$stmt->execute();
$row = $stmt->get_result()->fetch_row();
$visibility = (is_array($row) && $row[0] == 1) ? "block" : "hidden";
echo "<form action='?delete1' method='post' style='visibility:$visibility'>";
More details about prepared statements you can find here: Prepared Statements

Ok, I feel really stupid right now.
I wrote $adm = 1 instead of $adm == 1.
I'm really sorry for the waste of time.

Related

PHP - Populate a field depending on auto-populated select

I'm fairly new to php and have a question. I have an HTML form that has a SELECT auto-populated from an SQL table via PHP. The dropdown is populated with all users with the level of "Admin" or "Moderator". This is the code to connect:
$con = mysqli_connect("localhost", "root", "", "database") or die("Error " . mysqli_error($con));
And the dropdown itself:
<form name="htmlform" role="form" method="POST" action="result.php">
<select id="user" name="user" required>
<option selected disabled>User</option>
<?php
$result = $con->query("SELECT username FROM users WHERE level='admin' OR level='moderator' ORDER BY level");
while ($row = $result->fetch_assoc())
{
$username = $row['username'];
echo '<option value="'.$username.'">'.$username.'</option>';
}
?>
</select>
This works perfectly. The problem I'm having is that I am trying to reuse the data from this form (specifically $_POST['user']) on another page to auto-populate another field in a form. I need to see if the 'user' is an Admin or not and return $other as either "y" (Admin) or "n" (not Admin), which will then be added to another table.
Here's my code on the 2nd page (result.php):
$user=$_POST['user'];
$query = $con->query("SELECT level FROM users WHERE username=$user");
$variable=mysqli_query($con, $query);
if ($variable=="admin") {
$other = 'y';
} else {
$other='n';
}
At the moment all output for $other is "n" regardless of anything. So, obviously I have an error in the code, but don't know enough php to be able to spot or correct it.
Please could someone help point out the error?
text values have to be wrapped in quotes in a query
$query = $con->query("SELECT level FROM users WHERE username='$user'");
You also look like you were trying to execute that same query twice here:
$query = $con->query("SELECT level FROM users WHERE username=$user");
$variable=mysqli_query($con, $query);
this is not legal usage.
Also when you run this line
$variable=mysqli_query($con, $query);
$variable is not a value, but a mysqli_result object that will contain a resultset or FALSE if the query failed, but definitely not the content if the id column in your query.
However if you are using data got from the user, it is not safe to assume thay are not attempting a SQL Injection Attack
So you should use Prepared and Parameterised queries like this
$stmt = $con->prepare("SELECT level FROM users WHERE username=?");
$stmt->bind_param('s', $_POST['user']);
$stmt->execute();
I think you shoud start by reading the PHP manual for the mysqli extension
(Without getting into issues about best practices ...)
Your second code snippet's usage of the return value from mysql_query() is problematic.
The PHP Manual states:
For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning
resultset, mysql_query() returns a resource on success, or FALSE on
error.
Hence, $variable is a PHP resource and cannot ever be equal to a string.
Use tripple === equals when possible. You still need to "fetch" the record from the result resource (you managed to to do this in the first code snippet).
Generally speaking ...
$result = mysqli_query($con, $query);
$record = result->fetch_assoc();
//if(result->fetch_assoc()['level'] === 'admin') in PHP 5.4 and up.
//or
//if(mysqli_query($con, $query)->fetch_assoc()['level'] === 'admin') in PHP 5.4 and up.
if($record['level'] === 'admin')
{
}
else
{
}
Cheers!
According with mysqli_query doc:
Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a mysqli_result object. For other successful queries mysqli_query() will return TRUE.
So don't expect to get database value directly from call, you are comparing a mysql_result object (you made a SELECT) versus a constant string. You need to get your data from mysql_result object and then you can make comparison.
This code should work for you:
$user = $_POST['user'];
$sql = "SELECT level FROM users WHERE username={$user}";
$variable = mysqli_query($con, $sql)->fetch_row();
if ($variable[0]=="admin") {
$other = 'y';
} else {
$other='n';
}

Use variable inside a call?

Is there a way to make this happen? I mean where the stage == to a variable?
$var1 = "1";
$var2 = "2";
$where = $db->query('SELECT * FROM stages WHERE stage = $var1');
$chapter = $where[0]["$var1"];
Edit: Got told to give more information.
When I try to run this I get a php error for the databaseProvider and nothing happens. If I write
$where = $db->query('SELECT * FROM stages WHERE stage = 1');
$chapter = $where[0]["1"];
Everything works fine. I just want to be able to automate those two ones :)
If you use double-quotes instead of single-quotes then PHP will interpolate your variable for you:
$var1 = "1";
$var2 = "2";
$where = $db->query("SELECT * FROM stages WHERE stage = $var1");
But if $var1 is something that comes from user in put then you shouldn't do this to avoid SQL injection.
I'm unclear where your $where[0]["$var1"] was going... Do you mean to then use another variable? If so, you're looking for prepared statements using :var in PDO or ? in mysqli.

Adding a secondary WHERE statement to PDO/MySql statement

I have a PDO/MySQL database connection. My database holds content for various landing pages. To view these landing pages I enter *localhost/landing_page_wireframe.php* and append with ?lps=X (where X represents the Thread_Segment) to display the particular page in the browser. I am now getting to second iterations of these pages and need to add a secondary classifier to follow "Thread_Segment" to distinguish which version I am trying to pull up. Here is a snippet of my current working query.
<?php
$result = "SELECT * FROM landing_page WHERE Thread_Segment = :lps";
$stmt = $connection->prepare($result);
$stmt->bindParam(':lps', $_GET['lps']);
$stmt->execute();
$thread = "";
$threadSegment = "";
$version = "";
$categoryAssociation = "";
while($row = $stmt->fetch()) {
$thread = $row["Thread"];
$threadSegment = $row["Thread_Segment"];
$version = $row["Version"];
$categoryAssociation = $row["Category_Association"];
}
?>
So I need to now change this to add in the secondary classifier to distinguish between versions. I would imagine my query would change to something like this:
$result = "SELECT * FROM landing_page WHERE Thread_Segment = :lps AND Version = :vrsn";
if this is correct so far, then where I am beginning to get lost is in the following PHP code.
$stmt = $connection->prepare($result);
$stmt->bindParam(':lps', $_GET['lps']);
$stmt->execute();
I imagine I need to include some secondary iteration of this in my php to talk to the secondary classifier, but not totally sure how to go about this, and then I would imagine my url appendage would go from ?lps=X to something like this ?lps=X&vrsn=Y (Y representing the version).
I should state that I am somewhat new to PHP/MySql so the answer here may be simple, or may not even be possible. Perhaps I am not even going about this the correct way. Thought you all might be able to shed some insight, or direction for me to curve my research on the matter to. Thanks and apologies for any improper terminology, as I am definitely new to these technologies.
The URL change is as you describe. Just add another bindParam call to use that parameter:
$stmt = $connection->prepare($result);
$stmt->bindParam(':lps', $_GET['lps']);
$stmt->bindParam(':vrsn', $_GET['vrsn']);
$stmt->execute();
Adding another bindParam() should work here.
$stmt = $connection->prepare($result);
$stmt->bindParam(':lps', $_GET['lps']);
$stmt->bindParam(':vrsn', $_GET['vrsn']);
$stmt->execute();
You can access it via ?lps=X&vrsn=Y but just as a warning, the query will fail if those $_GET params are not requested. I recommend defaulting it to something prior to sending it through the query:
$stmt = $connection->prepare($result);
$lps = isset($_GET['lps']) ? $_GET['lps'] : 'default lps value';
$vrsn = isset($_GET['vrsn ']) ? $_GET['vrsn '] : 'default vrsn value';
$stmt->bindParam(':lps', $lps);
$stmt->bindParam(':vrsn', $vrsn);
$stmt->execute();

How to update a specific data of a table?

I am making a likes/dislikes thing in php & html. So, since it uses likes for each blog, I use the blog ID. I would like to know how I could update the "likes" in the table, but only update the "likes" of the specific row using it's id. Here is the php script:
<?php
require 'init.php';
$rating = $_GET['rating'];
$postid = $_GET['id'];
if ($rating = "like") {
$sql = "
";
}
if ($rating = "dislike") {
$sql = "
UPDATE
posts
SET
dislikes = dislikes+1
WHERE
id = $postid
";
}
?>
The update query does not seem to be the problem here, the main problem is your if statement, where you are not using comparison operator but are using assignment operator.
The statement: if ($rating = "like") assigns value "like" to the variable $rating, it does not compare $rating against value "like", which is what I think you want it to do.
There are few other "major" issues to note is that you are wide open for SQL Injection attacks. Since you mentioned that you are using mysql_ functions in your comment, you at least want to make use of mysql_real_escape_string function. e.g.
$rating = mysql_real_escape_string($_GET['rating'], $con); // assuming $con is your MySQL Connection
$postid = mysql_real_escape_string($_GET['id'], $con);
Another equally important point to note is that mysql_ functions are deprecated. You definitely should consider using either mysqli or pdo.
Third and final point to note is that if your rating is "like" then the query is empty. Hopefully you are checking for emptyness before calling mysql_query, which is not shown here.

query two tables in one mysql query

im having trouble getting data from two seperate tables
so far i have this
<?
include('config.php');
$xid = $_GET['xid'];
$result = mysql_query("SELECT * FROM `config`") or trigger_error(mysql_error());
while($row = mysql_fetch_array($result)){
foreach($row AS $key => $value) { $row[$key] = stripslashes($value); }
$result = mysql_query("SELECT * FROM `utinfo` WHERE `xid` = $xid") or trigger_error(mysql_error());
while($row2 = mysql_fetch_array($result)){
foreach($row2 AS $key => $value) { $row2[$key] = stripslashes($value); }
$un = urldecode($row2['un']);
};
switch ($row['module'])
{
case 1:
echo "Function 1 for user $uid on account $un";
break;
case 2:
echo "Function 2 for user $uid on account $un";
break;
case 3:
echo "Function 3 for user $uid on account $un";
break;
default:
echo "No module defined.";
};
};
?>
The config table config has the row named modules, and its populated by 2 entries, one of which is 1, the other 3. So i should be seeing case 1 and then case 3. But all im getting is the default echo.
(This is not an answer to the OP, but something you really should care about, so I think it's worth writting it)
It seems there is a enormous SQL-injection in your code.
The normal way of calling your page would be with something like "xid=5" in the URL, to get informations of user #5.
Now, suppose someone give "xid=5 or 1=1". The resulting query would be :
SELECT * FROM `utinfo` WHERE `xid` = 5 or 1=1
The condition is always true ; you'd get informations of ALL users as an output, as you iterate through the resultset.
Another possibility : "xid=5; delete from utinfo;" ; which would give this query :
SELECT * FROM `utinfo` WHERE `xid` = 5; delete from utinfo;
That would empty your table :-(
You must always escape / check / sanitize / whatever you data before putting them in a SQL query, especially (but not only) if they come from a user of the application.
For strings, see the mysql_real_escape_string function.
For data that sould be integers, you could use intval (worst case, if data was not valid, you'll get 0, which might get no result from the DB, but, at least, won't break it ^^ )
Another solution would be to use prepared statements ; but those are not available with mysql_* function : you have to switch to either
mysqli_*
or PDO
Anyway, for a new application, you shouldn't use mysql_* : it is old, and doesn't get new functionnalities / improvements that mysqli and PDO get...
stripslashes() is used on strings. Your case values are integers. It seems like you have a type mismatch here?
Why are you not using PDO? You should really standardis on PDO if you can.
Table names in SQL select should not be quoted.
You should consider using prepared statements in order to avoid SQL Injection and then you don't have to worry about having to quote your paramaters
The first answer is probably correct regarding type mismatches, you should be able to fix the issue by using the following code:
switch ((integer) $row['module'])
See the following:
http://us.php.net/manual/en/language.types.type-juggling.php#language.types.typecasting
Alternatively, you could try this:
settype($row['module'], "integer");
switch ($row['module'])
See:
http://us.php.net/manual/en/function.settype.php
I would also suggest echo'ing the value of $row['module'] onto the page just to check that it is indeed an integer.

Categories