PHP MySQL if row exists not doing anything - php

I am trying to get this piece of code to check if the line already exists in the database.
These lines get inserted into the database:
512150 # Merlinz is banned permanently by SO_Conner. # banned untill never for RDM
Now this piece of code checks if it already exists in the DB, if it doesn't exist we insert it.
$search = "permanently";
$logfile = "ban_list.txt";
$timestamp = time();
// Read from file
$file = fopen($logfile, "r");
?> <head> <title>Searching: <?php echo $search ?></title> </head> <?php
while( ($line = fgets($file) )!= false)
{
if(stristr($line,$search))
{
$check = mysql_query("SELECT * FROM `pincodes` WHERE `Pincode` = '$pincode' ");
if(mysql_num_rows($check) == 1) {
die(); }
else
{
$servername = "localhost";
$username = "root";
$password = "pass";
$dbname = "db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(stristr($line,$search))
$sql = "INSERT INTO `ingamebanlist` (Ban, Timestamp) VALUES ('$line', '$timestamp')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
// case insensitive
echo "<font face='Arial'> $line </font><hr>";
}
}
Like I said, it is still inserting it into my Database even though the line is present in the database.
Thanks }

if(mysql_num_rows($check)>0) {
echo " ";
}
else
{
change your line of code to this,
this would check if it already exist.
Flies Away

Try checking in the following manner
if(mysql_num_rows($check) !== FALSE)
Also try printing the query to see how the value is embedding for debugging purpose...

If it's a ban list based on a unique username why not alter the table to make the column unique. This code will also delete duplicates in the column 'Ban'.
ALTER IGNORE TABLE ingamebanlist ADD UNIQUE (Ban);
Next, mysql_num_rows() is deprecated in php 5.5
http://php.net/manual/en/function.mysql-affected-rows.php
Your best bet (even if your mysql functions work) is to change the mysql function calls to mysqli function calls. They are more secure and up to date.As well as making sure there is a constant in your code so your not switching between them.
If you change the mysql commands to mysqli this should work.
mysqli_affected_rows($conn);
Lastly, if you change the 'Ban' column to unique and make use of the mysqli_affected_rows this code should be all you need to insert when doesn't exist.
mysqli_query($conn,"INSERT INTO `ingamebanlist` (Ban, Timestamp) VALUES ('$line', '$timestamp')");
$num = mysqli_affected_rows($conn);
if($num > 0)
{
echo "Successfully Inserted";
}
else if($num == 0)
{
echo "Line already exists";
}
else
{
echo "Insert Error";
}

Related

Unable to select data from MySQL database using PHP 7.2

Please I haven't quite figured out what's wrong with this code
<?php $servername = "blee.com";
$username= "free";
$password = "free";
$dbname = "one";
// 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";
if ($conn->query($sql) === TRUE) {
echo "success";
} else {
echo "Error creating table: " . $conn->error;
}
$conn->close(); ?>
Somehow, if I try to insert anything into the database, it works perfectly, but if I try to select, it just shows "error creating table :" with no error being displayed...... I've searched all over but found no solution
I'm using php7.2 on my web server
For SELECT (as well as SHOW, DESCRIBE and EXPLAIN) queries mysqli::query returns a mysqli::result object if it succeeds, not a boolean. So your test
if ($conn->query($sql) === TRUE)
will always fail. What you should do instead is check that the query didn't fail (by comparing the return value with false), then you can use the returned object to fetch rows from the result set by using functions such as mysqli_result::fetch_assoc.
$result = $conn->query($sql);
if ($result !== false) {
// do something with results e.g.
// while ($row = $result->fetch_assoc()) { print_r($row); }
}

Why do we check both the value and type when check if a database query was successful?

While I was on w3schools learning about MySQL and PHP, I came across this when on the page about inserting data.
<?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 = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john#example.com')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
When checking the query was successful, why do we check if both are the same type and equal? Wouldn't it be fine if it was just this?
if ($conn->query($sql) == TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
mysqli::query() returns false on failure, another result will be always not false. You can write without equaling with true if you don't need to use special logic for mysqli_result. docs
if ($conn->query($sql))
{
//
} else
{
//
}
Php supports truthyness do if the function returned 1 then it would be true. It's explicitly checking that the result is the Boolean TRUE.
You do NOT need to check type in THIS case and could just have:
if ($conn->query($sql) == TRUE) {
The author is probably using a defensive programming technique which is to validate exactly what you are expecting.
According to: http://php.net/manual/en/mysqli.query.php
If this is a "SELECT, SHOW, DESCRIBE or EXPLAIN" then you would get an object back. If somebody updated the query to something unexpected, they would hit the error condition and know they had done something wrong. This particular scenario is a little off because it's sample code. In reality you would probably have a test to do the real validation.

SQL insert to MySQL doesn't work

I'm currently trying to insert username, pw to a DB, and check if the username already exists.
The problem is that the SQL (select) syntax doesn't work, nor does the (insert). I've checked around for a couple of hours in forums and Stackoverflow, and my current code is the following.
What might be the problem?
Thanks, Jimmie.
<?php
$servername = "localhost";
$username = "name";
$password = "pw";
$dbname = "dbaname";
$mysqli = new mysqli($servername, $username, $password, $dbname);
if ((isset ($_POST["identity"])) && (isset ($_POST["pin"])) && (isset ($_POST["token"])))
{
$identity = htmlspecialchars($_POST['identity'], ENT_QUOTES, "ISO-8859-1");
$pin = htmlspecialchars($_POST['pin'], ENT_QUOTES, "ISO-8859-1");
$token = htmlspecialchars($_POST['token'], ENT_QUOTES, "ISO-8859-1");
echo "$identity";
if($token == "xyz13D;A##:!#")
{
$result = $mysqli->query("SELECT `identity` FROM Users WHERE `identity` = '" . $identity . "'");
if($result->num_rows == 0)
{
echo "successCreat";
// Perform queries
mysqli_query($mysqli,"SELECT * FROM Users");
mysqli_query($mysqli,"INSERT INTO Users (identity,pin,userActivity, identityCreated) VALUES ('$identity', '$pin',1,now())");
}
else
{
echo "failureCreate";
}
}
else
{
echo"Wrong Key";
}
}
$mysqli->close();
?>
Assuming that identity is a primary key, then you can check the error flags after executing an INSERT query to see if an error occurred.
mysqli_query( $mysqli, "INSERT INTO ... " ); //< ... Represents query
if (mysqli_error( $mysqli )) {
echo "Failure";
}
else {
echo "Success";
}
Also, you should properly escape input as stated in the comments. In addition, you should check whether or not the connection attempt was successful using mysqli_connect_error.
Finally, there might be an issue in your SQL suntax which mysqli_error will also catch. A last possibility is that the POST data isn't being set properly and the code is being ignored completely.

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();

$_GET not inserting into MySQL database

I have a small PHP script which I would like to use to add a value to an SQL table.
When I do something like: http://ipaddress/phptest.php?350
If I just put 350 into the insert statement, it works fine. I have tried to get the result of GET to be added but seem to be unable to after many attempts.
I either get a blank, or "array" added to my table.
Any help would be appreciated.
Also how would I add two values? phptext.php?350&?450 for example?
Thanks
<?php
$servername = "localhost";
$username = "administrator";
$password = "blabla";
$dbname = "test";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
print_r($_GET);
if($_GET["a"] === "") echo "a is an empty string\n";
if($_GET["a"] === false) echo "a is false\n";
if($_GET["a"] === null) echo "a is null\n";
if(isset($_GET["a"])) echo "a is set\n";
if(!empty($_GET[a])) echo "a is not empty";
$sql = "INSERT INTO test.sensor (VALUE) VALUES ('$_GET["a"]')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
The HTTP specification declares that GET variables are passed like the following example:
url.com/?bar=value&foo=value
So technically you're passing the GET values wrong. As I see, the correction would be:
http://ipaddress/phptest.php?a=350
Also, as an extra pointer, sanitize your variables before submitting to a SQL database, as it will lead to SQL injection vulnerabilities.
You might want to use...
mysqli_real_escape_string();
Or use prepared statements, the more accepted/fail-safe way of working with them.
For more reference,
http://php.net/manual/en/mysqli.real-escape-string.php

Categories