Check if a value exists in MySQL with php - php

I've been looking around stackoverflow and wasn't able to ever find a way that'd actually work. I have a simple php application
//Database credentials
$servername = "localhost";
$username = "root";
$password = "password";
$database = "database";
// Create connection to database
$db = new mysqli($servername, $username, $password, $database);
// Check connection for errors
if ($db->connect_error) {
die("<h1>Connection to database failed: " . $db->connect_error) . "</h1>";
};
$username = $json['statuses'][0]['user']['screen_name'];
$userid = $json['statuses'][0]['user']['id_str'];
$sql = "SELECT * FROM log WHERE userid='" . $userid . "' LIMIT 1";
if ($db->query($sql)->num_rows > 0) {
echo "<h4>This user already exists</h4>";
} else {
//Put the userid into the database
$sql = "INSERT INTO log (userid) VALUES ('" . $userid . "')";
if ($db->query($sql) === TRUE) {
echo "<h4>Added " . $username . " to the database</h4>";
} else {
echo "Error: " . $sql . "<br>" . $db->error;
}
}
Currently it seems to be hit or miss. It'll work sometimes, other times a record will exist, and it'll still insert the userid again creating duplicates.

Like said #tadman Your code is BAD. Data from variable $json is directly inserted into query - this is not good...
Simple test:
I set :
$userid = "111111111a";
query:
$sql = "SELECT * FROM log WHERE userid='111111111a' LIMIT 1";
return TRUE because, this user doesn't exists in db,
or
$userID ='111111111\' OR \'1=1';
query:
$sql = "SELECT * FROM log WHERE userid='111111111' OR '1=1' LIMIT 1";
return TRUE because 1=1 is always true.
If column userid is INT type, $userid value is converted to 111111111 and inserted into log table

Related

Accessing two tables within same statement?

I'm trying to create an upvote system where, after checking to see if you're logged in and after getting your userid, it checks if the table has your userid with the postid already in it and if it does then it means it was already upvoted. I just want to know what's wrong in my code, this is being used for learning, I don't need any complex thing.
Code:
if (isset($_GET['upvote'])) {
if ($_SESSION["loggedin"] == true) {
$upvoteid = $_GET["upvote"];
$servername = "";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id FROM users WHERE username=".$_SESSION["loggedinusername"];
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$userid = $row["id"];
}
$sql2 = "SELECT userid, postid FROM upvotedposts WHERE userid='".$userid."' AND postid='".$upvoteid."'";
$result2 = $conn->query($sql);
if (!$result2->numrows > 0) {
$sql = "UPDATE posts SET upvotes = upvotes + 1 WHERE id = ".$upvoteid;
if ($conn->query($sql) === TRUE) {
echo "Sucessfully upvoted";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
} else {
echo "Failed;
}
$conn->close();
}
}
When I do click the upvote button, it simply does nothing. The issue here is that as far as I know it looks like it would work but I may be forgetting something that I am unaware of or incorrectly using something.
You are missing a closing "
echo "Failed;
should be:
echo "Failed";

How to put the output query from mySQL to php int variable

I want to do a query to get the last id (int) in a table to create a new row with that last id + 1 but actually this just put all rows with the same id
my code:
<?php
$servername = "localhost";
$user = "root";
$pass = "dbpass";
$dbname = "site";
$mail = $_POST['mail'];
$password = $_POST['password'];
// Create connection
$conn = mysqli_connect($servername, $user, $pass, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sqlID = "SELECT MAX(id) FROM `login`;";
if ($result = mysqli_query($conn, $sqlID)) {
$id = mysqli_fetch_row($result);
}
settype($id, "int");
$id = $id + 1;
$sql = "INSERT INTO login (`id`,`mail`,`password`)
VALUES ('".$id."','".$mail."','".$password."');";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
mysqli_fetch_row returns always an array, also if there is only 1 element. So the MAX(id) in in $row[0].
Fixing this, you also don't need to use settype.
If your id is autoincrement, change this:
$sql = "INSERT INTO login (`id`,`mail`,`password`)
VALUES ('".$id."','".$mail."','".$password."');";
to:
$sql = "INSERT INTO login (`mail`,`password`)
VALUES ('".$mail."','".$password."');";
Then get rid of all code from $sqlID to $id + 1; (for tidyness)

How to i execute this two query in php?

I am new in Stackoverflow and noob in programming.
I have a problem . I am creating a script that can change a database column info by give database username and password.
My source code is here :
<?php
$servername = "localhost";
$username = "admin";
$dbname = "mydb";
$password = "1234";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
mysqli_select_db($conn,"$dbname");
$sql = "UPDATE users SET login='admin1' WHERE id=1";
$sql2 = "UPDATE users SET pass='1234' WHERE id=1";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
$conn->close();
?>
Now there is two query's
$sql = "UPDATE users SET login='admin1' WHERE id=1";
$sql2 = "UPDATE users SET pass='1234' WHERE id=1";
How can I execute this two query's and i want that when this two query's became true I message will be show that Record updated successfully. In the above source code showing error.
You can update both records by one query:
$sql = "UPDATE users
SET login = 'admin1',
pass = '1234'
WHERE id = 1";
Do it in one query:
$sql = "UPDATE users SET login='admin1', pass='1234' WHERE id=1";
Since you are updating one table, you can have one query instead like this:
$sql = "UPDATE users SET login='admin1',pass='1234' WHERE id=1";
try this.
$sql = "UPDATE users "
. " SET login='admin1',pass='1234' "
. " WHERE id=1";

Reducing MSQL Query to a specific session

Using the code below, I was able to display each username and trial 1/0 flag in the table. What I want to do is display the data only for the existing user so I can say something like "Hello USERNAME, you have TRIAL access..." etc...
We're using standard HTACESS as the un/pass to enter the info area.
What needs to change here to only show the existing user's session?
<?PHP
$user_name = "blahblahblah";
$password = "blahblahblah";
$database = "blahblahblah";
$server = "127.0.0.1";
$db_handle = mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database, $db_handle);
if ($db_found) {
$SQL = "SELECT * FROM member_auth";
$result = mysql_query($SQL);
while ( $db_field = mysql_fetch_array($result) ) {
print $db_field['username'] . " : ";
print $db_field['trial'] . " <br> ";
}
mysql_close($db_handle);
}
else {
print "Database NOT Found ";
mysql_close($db_handle);
}
?>
please don't use mysql_ functions.. look into PDO or MySQLi here: http://www.phptherightway.com/#databases
Update your query to only return specific user results.
Using Form POST:
$username = mysql_real_escape_string($_POST["username"]);
$password = mysql_real_escape_string($_POST["password"]);
Using URL Parameters:
$username = mysql_real_escape_string($_GET["username"]);
$password = mysql_real_escape_string($_GET["password"]);
So your SQL query will now look like:
$SQL = "SELECT * FROM member_auth WHERE username = '" . $username . "' AND password = '" . $password . "'";

Can't echo out something after a MySqli query?

Today, I have a question regarding PHP.
I know to be fact based on my setup that this function is being called. However, only the first requested 'echo' is being displayed (I used "cats", long story...).
I know that a lot of times this is something simple like a missed end quote, but my PHP doesn't throw me any errors. Anyting I'm doing wrong? I can't get anything after my code.
Before I do this:
$connection = new mysqli('localhost', 'root', 'root', 'VV_root') or die("There was an error connecting; " . mysqli_connect_error);
Then this is my function.
function knock_on() {
echo("cats");
// It is asssumed that from here, all information is to be kept as secure as possible in the transactions
// Get all the ingredients
$username = $_POST['username'];
$password = $_POST['password'];
// Now, we have all the ingredients
// Mix password !IMPORTANT!
// Now, run the query to see if we get any matches.
$query = $connection->query("select * from user where username = " . $username . " & password = " . $password) or die("Something went wrong");
echo("cats2");
}
You are running into scope issues. The $connection variable is not available inside your knock_on() function. Pass the $connection as a parameter to your function definition.
Like this..
function knock_on($connection) { //Forget the global keyword thing.
Firs of all turn on error displaying and then you have an error in your query:
$query = $connection->query("select * from user where username = " . $username . " & password = " . $password) or die("Something went wrong");
Here you need to use AND operator not an & as you did:
username = " . $username . " AND password = " . $password
Abnd the second : $connection variable is not available inside your knock_on() function as
Shankar Damodaran mentioned.
Note this code is not tested.
$connection = new mysqli('localhost', 'root', 'root', 'VV_root') or die("There was an error connecting; " . mysqli_connect_error);
function knock_on() {
global $connection;
echo("cats");
// It is asssumed that from here, all information is to be kept as secure as possible in the transactions
// Get all the ingredients
$username = $_POST['username'];
$password = $_POST['password'];
// Now, we have all the ingredients
// Mix password !IMPORTANT!
// Now, run the query to see if we get any matches.
$query = $connection->query("select * from user where username = " . $username . " & password = " . $password) or die("Something went wrong");
if($query) {
return true;
} else {
return false;
}
}
There were several things that I had to fix, so here's my new working code
$connection = new mysqli("localhost", "root", "root", "VV_root");
The actual function:
function knock_on() {
echo("cats");
// It is asssumed that from here, all information is to be kept as secure as possible in the transactions
// Get all the ingredients
$username = $_POST['username'];
$password = $_POST['password'];
// Now, we have all the ingredients
// Mix password !IMPORTANT!
// Now, run the query to see if we get any matches.
if ($connection) {
$query = $connection->query("select * from user where username = '" . $username . "' and password = '" . $password . "'") or die("Something went wrong");
}
else {
echo($mysqli->connect_error);
}
echo("cats2");
}

Categories