mysql query in a function... not working - php

I made this function. It's actually one of the first functions I've ever made. However, I can't get it to execute.
$con is defined, i just didn't paste it. In fact, all of the variables are defined.
function cleanse() {
$cleansesql = "Select * FROM rated_teams WHERE server='$server' AND name='$myteam' AND opposition='$opposer'";
$result = mysqli_query($con, $cleansesql)
or die('A error occured: '.mysqli_error());
while (($row = mysqli_fetch_array($result))) {
if ($row['server'] == $server && $row['name'] == $myteam && $row['opposition'] == $opposer && $row['myscore'] == $myscore && $row['oscore'] == $oscore && $row['location'] == $location) {
echo "There is a Match.";
} else {
echo "There are no matches";
}
}
}
And this is how I'm calling it.
if ($solo == "solo" || $solo == "Solo" || $solo == "SOLO") {
echo $solo." <br />";
if (!empty($myscore)) {
echo $myscore." <br />";
if (!empty($oscore)) {
echo $oscore." <br />";
if (!empty($location)) {
echo $location." <br />";
cleanse();
}
}
}
}
Maybe I'm not calling it correctly. I just need someone who knows more than me to help... that'll be most of you hahaha.

Pass the information to your cleanse function, like $con (given that you've created your connection to the database prior to calling this function), $server, $myteam and $opposer so it can work with it.
So the definition of your function would become:
function cleanse($con, $server, $myteam, $opposer) { ... }
And you'd call it this way:
cleanse($con, $server, $myteam, $opposer);

Notice that you are using a variable $con which is the connection to MySQL.
You have not created a connection to MySQL prior to the query.
I suggest reading the basic PHP manuals on using mysqli.
Remeber the follwing:
You need to connect to SERVER
You need to choose the DB u work against
You will execute queries against that DB.
2 is not mandatory.

Campari is right - that is why your function is not working, however:
You are duplicating your code. The function does not need to check if there is a match between your test criteria and the output of the sql because the database does that for you. What your sql says is "fetch all the results that match all of my criteria" then your function says "check all the results match my criteria" this is slow and not required. If you write your sql properly, there is rarely any need for further checking or merging of data in PHP.
function cleanse($connection, $server, $myteam, $opposer)
{
$cleansesql="Select * FROM rated_teams WHERE server=? AND name=? AND opposition=?";
$stmnt=$connection->prepare($cleansesql);
$stmnt->bind_param("sss",$server,$myteam,$opposer);
$stmnt->execute();
$stmnt->store_result();
return $stmnt->num_rows;
}
This (untested) function I've written for you should return the number of rows in rated_teams that match all of the criteria in your variables. It is also safe to input user-entered data as it uses prepared statements and is thus not susceptible to SQL injection.

Related

I can't seem to get this else statement to work in php

<?php
session_start();
$link = mysqli_connect(database connection info);
if (mysqli_connect_error()) {
echo "Could not connect to database";
die;
}
if (isset($_POST['submit'])) {
$query = "SELECT * FROM users WHERE email = '".$_POST['email']."'";
$result = mysqli_query($link, $query);
if ($row = mysqli_fetch_array($result)) {
if ($_POST['email'] == $row['email'] && password_verify($_POST['password'], $row['password']))
{
$success .= "We're in baby";
} else {
$error .= "didn't work boi";
}
}
}
?>
Basically for some reason the else statement in this code
if ($_POST['email'] == $row['email'] && password_verify($_POST['password'], $row['password']))
{
$success .= "We're in baby";
} else {
$error .= "send help";
}
is not working at all. The problem isn't within the error variable as echo does not work either. I can't get the else statement to output any response whatsoever if the original if statement returns false. The if statement executes perfectly fine if it returns true!
Please help.
As per my comment, to get the else statement executed, enter a valid email address from your database and a wrong password. That should get to the else statement.
To echo $error, define $error = ''; at the top of the script and then add
echo $error; //Below the closing `}` of the `if($row....) ` statement
Also your query is not safe at all. You're directly injecting a variable that can be easily manipulated by anyone. You should never trust such. Hence why we have prepared statements. They help prevent SQL injection attacks as well as those pesky quoting issues. Visit the link below for a tutorial on how to use them with the mysqli_ API.
https://phpdelusions.net/mysqli
Add an else part for the if ($row = mysqli_fetch_array($result)) - perhaps your query fails or the specified email doesn't exist in the db.
The condition $_POST['email'] == $row['email'] is useless as it's already part of the SQL statement.
Also, important(!): your code is vulnerable to SQL injection. Do not put unescaped values from POST to an SQL query.

How to check if a $_GET variable exists in database

How to check if a $_GET variable exists in Database if it does not print an error.
I am using this code:
$connection = mysqli_connect("localhost" , "root" , "" , "test");
$query = "SELECT site_title FROM websites";
$select_all_sites = mysqli_query($connection,$query);
$row_count = mysqli_num_rows($select_all_sites);
for ($i=0; $i < $row_count; $i++){
$row = mysqli_fetch_assoc($select_all_sites);
if($_GET['website'] == $row['site_title']){
echo 'Success';
}else{
echo 'error';
}
}
It prints too much errors or (the else condition remains always true.) Help me out.
It is not safe to directly throw any of php array variables into your query. You need to clean it. Consider using the mysqli_real_escape_string. Although i would suggest to make a switch to PDO.
Back to your question, why can't you use a while loop instead of the for loop. you need to check if the variable website actually exists or not. php's isset function will help. Try this:
<?php
if(isset($_GET['website'])){
if($_GET['website'] == $row['site_title']){
#awesome! it matches
} else{
#it does not match
}
} else{
#website $_GET variable does not exist. Handle error
}
?>
Please try below code and inform me if you will face any error.
<?php
$connection = mysqli_connect("localhost" , "root" , "" , "test");
$query = "SELECT site_title FROM websites";
$select_all_sites = mysqli_query($connection,$query);
while($row = mysqli_fetch_assoc($select_all_sites))
{
if($_GET['website'] == $row['site_title'])
{
echo 'Success';
}
else
{
echo 'error';
}
}
?>
You will first have to do a check for is the get variable actually exists. You can do this with the PHP isset function http://php.net/manual/en/function.isset.php if it exists you can proceed to see if it is matching you site title like you do now.

How do I query a database in PHP and return results based on matching user-input?

I’m trying to write a PHP script with MySQLi to query a database.
I’d like it if the user-input could be checked against the database and then return a result from the column ‘conjugation’ if the string in the column ‘root’ of the table ‘normal_verbs’ is in the input.
So if the user input is something like "foobar", and the root-column has "foo", I'd like it to see 'foo' in 'foobar' and return that value of 'conjugation' in that row.
I can’t seem to get the query to work like I want it to. The one I'm using below is basically just a placeholder. I don't entirely understand why it doesn't work.
What I’m trying, is this :
function db_connect() {
static $connection;
if(!isset($connection)) {
$connection = mysqli_connect('localhost','user','password','Verb_Bank');
}
if($connection === false) {
return mysqli_connect_error();
}
return $connection;
}
function db_query($query) {
$connection = db_connect();
$result = mysqli_query($connection,$query);
return $result;
}
function db_quote($value) {
$connection = db_connect();
return "'" . mysqli_real_escape_string($connection,$value) . "'";
}
$m= db_query("SELECT `conjugation` from normal_verbs where `root` in (" . $y . ")");
if($m === false) {
// Handle failure - log the error, notify administrator, etc.
} else {
// Fetch all the rows in an array
$rows = array();
while ($row = mysqli_fetch_assoc($m)) {
$rows[] = $row;
}
}
print_r ($rows);
It’s not giving me any errors, so I think it’s connecting to the database.
EDIT2: I was wrong. I was missing something obvious due to misunderstanding MySQLi and have edited the code accordingly. So the above code does work in that it connects to the database and returns a result, but I'm still stumped on a viable SQL statement to do what I want it to do.
Please try this:
SELECT 'conjugation' FROM 'normal_verbs' WHERE " . $y . " LIKE CONCAT('%',root,'%')
It selects all rows where root contains $y anywhere.
In addition, your code is vulnerable to SQL injections. Please look here for more information.
Try this SQL Query Like this
SELECT `conjugation` from normal_verbs where `root` like '%$y%'

My MySQL database is not updating?

I'm trying to update my datebase from a php archive but i can't:
Before you ask: The names from db are written correctly and the if works too...
<?php
if(isset($_GET["ans"]) && isset($_GET["name"]))
{
include("con.php");
$con = con();
$answer = $_GET["ans"];
$nam = $_GET["name"];
if($answer="firefly" ||$answer="Firefly" ||$answer="FIREFLY")
{
$le=2;
$sc=50;
$update = "UPDATE User SET Level='$le', Score='$sc' where Name = '$nam'";
mysql_query($update,$con);
// header("Location: lv1b.php?n=$nam");
}
else {
echo "try again..." ;
}
}
?>*
This is the con.php...
<?php
function con()
{ $server="localhost"; $user="root"; $pass="";
$con= mysql_connect($server, $user,$pass);
mysql_select_db("games"); return $con;
}
Your if statement currently is assigning values, not testing equality, you can also skip the three tests by using one of the case conversion functions... so instead the if line should be:
if(strtolower($answer)=="firefly") {
Next up - as pointed out in comments - you're using the out-of-date MySQL library, you should rather be using MySQLI or PDO
Also you're wide open to SQL injection, you should be escaping any value you're using in MySQLi see mysqli_real_escape_string. In your example this means escaping the value of $nam
A potential alternative script-fragment (using MySQLi and the above if statement changes) might look something like:
<?php
$mysqli = new mysqli("localhost", /*username*/"root", /*pass*/"", /*dbname*/);
$name=$mysqli->real_escape_string($_GET["name"]);
if (strtolower($_GET["ans"])=="firefly") {
if (!$mysqli->query("UPDATE user SET level='2',score='50' ".
"WHERE name='$name'")) {
echo "query failed";
} else {
echo "Updated"
}
$mysqli->close();
} else {
echo "try again..";
}

How to debug PHP database code?

I am new in PHP and need help with my below code. When I am entering wrong userid instead of giving the message "userid does not exist" it is showing "password/id mismatch. Please guide me where I am wrong.
<?php
session_start();
$id = $_POST['userid'];
$pwd = $_POST['paswd'];
$con = mysqli_connect("localhost", "????", "????", "??????");
if ($con) {
$result = mysqli_query($con, "SELECT * FROM users WHERE userid=$id");
if ($result) {
$row = mysql_fetch_array($result);
if ($row["userid"] == $id && $row["paswd"] == $pwd) {
echo "Welcome! You are a authenticate user";
if ($id == $pwd)
//my default login id and password are same
{
header("Location: changepwd.html");
} else {
header("Location: dataentry.html");
}
} else {
echo "ID/Password Mismatch";
}
} else {
echo "User does not Exist !!!";
}
} else {
echo "Connection failed - ".mysqli_error()." -- ".mysqli_errno();
}
?>
The main problem you have is that you're mixing up between the mysqli and mysql functions. These two libraries are not compatible with each other; you must only use one or the other.
In other words, the following line is wrong:
$row=mysql_fetch_array($result);
It needs to be changed to use mysqli_.
While I'm here, going off-topic for a moment I would also point out a few other mistakes you're making:
You aren't escaping your SQL input. It would be extremely easy to hack your code simply by posting a malicious value to $_POST['userid']. You must use proper escaping or parameter binding. (since you're using mysqli, I recommend the latter; it's a better technique).
Your password checking is poor -- you don't appear to be doing any kind of hashing, so I guess your passwords are stored as plain text in the database. If this is the case, then your database is extremely vulnerable. You should always hash your passwords, and never store the actual password value in the database.
I've gone off topic, so I won't go any further into explaining those points; if you need help with either of these points I suggest asking separate questions (or searching here; I'm sure there's plenty of existing advice available too).
else
{
echo "ID/Password Mismatch";
}
is connected with the
if($row["userid"]==$id && $row["paswd"]==$pwd)
{
So since you are giving a wrong id. It echo's: ID/Password Mismatch
Also the else at if ($result) { wont ever show since
$result = mysqli_query($con, "SELECT * FROM users WHERE userid=$id");
You need some additionnal checks:
select * return 1 row (not 0, and not more)
you need to protect the datas entered by the html form (for example someone could enter 1 or 1 to return all rows
<?php
session_start();
$con = mysqli_connect("localhost", "????", "????", "??????");
$id = mysqli_real_escape_string($_POST['userid']);
$pwd = mysqli_real_escape_string($_POST['paswd']);
if ($con) {
// don't even do the query if data are incomplete
if (empty($id) || empty($pwd)
$result = false;
else
{
// optionnal : if userid is supposed to be a number
// $id = (int)$id;
$result = mysqli_query($con, "SELECT * FROM users WHERE userid='$id'");
}
if (mysqli_num_rows($result) != 1)
$result = false;
if ($result) {
$row = mysqli_fetch_assoc($result);
if ($row["userid"] == $id && $row["paswd"] == $pwd) {
echo "Welcome! You are a authenticate user";
if ($id == $pwd)
//my default login id and password are same
{
header("Location: changepwd.html");
} else {
header("Location: dataentry.html");
}
} else {
echo "ID/Password Mismatch";
}
} else {
echo "User does not Exist, or incomplete input";
}
} else {
echo "Connection failed - " . mysqli_error() . " -- " . mysqli_errno();
}
?>
Try with isset() method while you are checking if $result empty or not.
that is in line
if ($result) {.......}
use
if (isset($result)) { .......}
$result is always true, because mysqli_query() only returns false if query failed.
You could check if $result has actual content with empty() for example.
You can use this sql compare password as well with userid
$sql= "SELECT * FROM users WHERE userid='".$id.", and password='".$pwd."'";

Categories