mysql query run only for numbers - mysql

$username = $_POST['username'];
$password = $_POST['password'];
$passworda = $_POST['passworda'];
$email = $_POST['email'];
if ($password == $passworda){
echo 'this is the user name to be chacked:' .$username .'<br>';
$query = "SELECT username FROM mishta where username=$username";
$queryrun = mysql_query($query);
echo $queryrun .'<br>';
echo mysql_num_rows($queryrun) .'<br>';
if (mysql_num_rows($queryrun)!=1){
mysql_query("INSERT INTO mishta(id, username, password, email) VALUES ('', '$username','$password','$email')");
}
else{
echo 'user already exist';
}
Hello there,
I'm trying to make a simple registration form, I get useername from html form and I want to make sure it doesn't already exist in my database.
the thing is that whenever I run the username as a number (1,2,3...) it runs smoothly.
but, when I try to write anything with letter, like Bob or Dora I get the following error:
Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in...
Yet the information is still being stored my my data base, means it got false on the last if statement, and it will continue to get false (It will just insert duplicates if I try again).
Any help would be appreciated.

You forgot the quotes around the username:
$query = "SELECT username FROM mishta where username='$username'"
Quotes are used as string delimiter. Numbers are not string and it works if you use a number.

Related

SQL insert is not working

Please can someone help? The code below seems to work and gives no errors, but when I check the database, it hasn't added anything. Tearing my hair out!
<?php
$bcode = $_GET['barcode'];
$businessid = $_GET['businessid'];
$servername = "---------";
$username = "-------";
$password = "-------";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO 'db741921215'.'Scans' (Barcode, Success, Business) VALUES ('".$barcode."', 'Y', '".$businessid."')";
$con->close();
} ?>
The columns in table 'Scans' is as below:
Help is very, very much appreciated!!!
I see a couple things - use backticks "`" around your table name definitions, not single quotes. Also, save yourself some eye strain and use the fact that PHP interpolates variables just fine within doublequoted strings.
$sql = "INSERT INTO `db741921215`.`Scans`
(Barcode, Success, Business)
VALUES
('$barcode', 'Y', '$businessid')";
Also - you never actual execute the query, do you?
$conn->query($sql);
You seem to be missing the step where you execute the sql statement
I can see where you define it but I don't see where it's executed. i.e.
$conn->query($sql);
Also, you seem to be missing a letter when closing the connection: $con->close() should be $conn->close();

Codeigniter database retrieving both in uppercase, lowercase and mixed case

my code
// My code:
$this->db->select('*')
->from('tbl_login')
->where(['username'=>$this->input->post('username'),'password'=>$this->input->post('password')]);
$result = $this->db->get()->result();
if($result)
var_dump($result)
else
echo "not fount";
Doesn't matter what ever I input 'admin1' or 'ADMIN1' & 'password1' or 'PASSWORD1'
it retrieves data from the tables.
But what I actually want is data will be retrieve when case is matched correctly.
Could anyone help???...
Try this one
$query = $this->db->select("*")->from("tbl_login")->where("BINARY username= '".$this->input->post('username')."' and password = '".$this->input->post('password')."'");
$result = $this->db->get()->result();
if($result)
var_dump($result)
else
echo "not found";
Note: Basically use BINARY before your where conditions in Query.
Hope this will help!!

INSERT INTO MYSQL - Can´t insert data

After a couple of week´s trying to insert data in variables from form in MYSQL database, i´m asking here. I found a lot of example codes of INSERT INTO and also my provider checked my skript. He said I have a problem in my $sql=.
I tryed a lot of, but i can´t see any data in phpMyAdmin after click submit, but i receive the mail, that works fine.
Maybe anybody can see an issue in my script.
<?php
if(isset($_POST["sendcopy"])){
mail($mailToCC, $subject, $textCC, $from);
}
if(isset($_POST["submit"])){
$host_name = "database.myprovider";
$database = "db_name";
$user_name = "user_name";
$password = "*****************";
$connect = mysqli_connect($host_name, $user_name, $password, $database);
if (mysqli_connect_errno())
{
echo "KEINE VERBINDUNG MÖGLICH! " . mysqli_connect_error();
}
else
{
echo "ERFOLGREICHE VERBINDUNG ZUR DATENBANK!";}
$sql= 'INSERT INTO "offen"("id", "vorname", "nachname", "email", "telefon", "geburtsjahr", "postleitzahl", "datum", "stunde", "minute", "personen", "bereich", "nachricht")
VALUES ($id, $vorname, $nachname, $email, $tel, $geburtsjahr, $plz, $datum, $stunde, $minute, $personen, $bereich, $nachricht)';
mysql_close($connect);
}
include ("reservtrue.php");
exit;
?>
The "submit" comes from a <form> below.
<form method="post" action="mailer.php" onsubmit="return chkFormular()" name="Formular" id="formTemplate">
<table id="reservtable">
.
.
.
.
<input type="submit" name="submit" value="Reservieren" id="submit">
</td>
</tr>
</table>
</form>
I hope it´s no problem to use german words as variables, here in stackoverflow.
Thank´s for help.
EDIT
Thank you for you´r suggestions. I still can´t insert data from form to MYSQL. I changed my Code a bit. And if I paste the code into phpMyAdmin - SQL, it work´s! But not if I load my script to server and test my form in web.
This is my new Code:
<?php
error_reporting(E_ALL ^ E_NOTICE);
if(isset($_POST["submit"])){
$vorname = $_POST["Vorname"];
$nachname = $_POST["Nachname"];
$email = $_POST["Mailadresse"];
$tel = $_POST["Telefonnummer"];
$geburtsjahr = $_POST["Geburtsjahr"];
$plz = $_POST["PLZ"];
$datum = $_POST["Datum"];
$stunde = $_POST["Stunde"];
$minute = $_POST["Minute"];
$personen = $_POST["Personen"];
$bereich = $_POST["Bereich"];
$nachricht = $_POST["Nachricht"];
$host_name = "database.myprovider";
$database = "db_name";
$user_name = "user_name";
$password = "*****************";
$connect = mysqli_connect($host_name, $user_name, $password, $database);
if (mysqli_connect_errno())
{
echo "KEINE VERBINDUNG MÖGLICH! " . mysqli_connect_error();
}
else
{
echo "ERFOLGREICHE VERBINDUNG ZUR DATENBANK!";}
$insert = ("INSERT INTO offen(vorname, nachname, email, telefon, geburtsjahr, postleitzahl, datum, stunde, minute, personen, bereich, nachricht)
VALUES ('".$id."', '".$vorname."', '".$nachname."', '".$email."', '".$tel."', '".$geburtsjahr."', '".$plz."', '".$datum."', '".$stunde."', '".$minute."', '".$personen."', '".$bereich2."', '".$nachricht."')");
mysqli_query($insert, $sql);
}
include ("reservtrue.php");
exit;
?>
Problem solved
Problem is solved with following code:
$insert = "INSERT INTO `offene`
(
`id`, `vorname`, `nachname`, `email`, `telefon`, `geburtsjahr`, `postleitzahl`, `datum`, `stunde`, `minute`, `personen`, `bereich`, `nachricht`
)
VALUES
(
NULL, '$vorname', '$nachname', '$email', '$tel', '$geburtsjahr', '$plz', '$datum', '$stunde', '$minute', '$personen', '$bereich', '$nachricht');";
mysqli_query($connect, $insert);
Thank you guy´s for information, inspriation and tips! I learnd a lot in the last 2 days.
Where is your mysql_query($sql); ? Add this after your $sql. Your $sql query require mysql_query to run it. If you added that and it still doesn't work, I suggest your go to phpmyadmin's sql tab. Paste your query in with some random VALUES. That's how I check if my query is working or not.
echo "ERFOLGREICHE VERBINDUNG ZUR DATENBANK!";}
$sql= 'INSERT INTO offen (id, vorname, nachname, email, telefon, geburtsjahr, postleitzahl, datum, stunde, minute, personen, bereich, nachricht)
VALUES ('$id', '$vorname', '$nachname', '$email', '$tel', '$geburtsjahr', '$plz', '$datum', '$stunde', '$minute', '$personen', '$bereich', '$nachricht')';
mysqli_query($connect,$sql); //this line was missing from your code.
mysqli_close($connect); //updated to make it MySQLi
The mysqli_query($connect,$sql) actually does the work of applying the SQL you define in the $sql query.
NOTE
You have both MySQLi and MySQL functions in your script, you must stick with just one function, ALL your SQL functions must be MySQL i .
I would recommend that you change your SQL query to use single quotes and backticks. The table name offen and the column names do not need to be in quotes. The variables you insert do need to be in quotes, as I have illustrated.
You do not (usually) need to have mysqli_close because the SQL connection automatically closes once the PHP reaches the end of the page.
The variable names don't need quotes but the parametes do. Also you are missing the code to execute the SQL statement.
echo "ERFOLGREICHE VERBINDUNG ZUR DATENBANK!";}
$sql= "INSERT INTO offen(id, vorname, nachname, email, telefon, geburtsjahr, postleitzahl, datum, stunde, minute, personen, bereich, nachricht)
VALUES ($id, '$vorname', '$nachname', '$email', '$tel', '$geburtsjahr', '$plz', '$datum', '$stunde', '$minute', '$personen', '$bereich', '$nachricht')";
if ($connect->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $connect->error;
}
mysql_close($connect);
}
It appears you have some understandable confusion about quoting of the variables in $insert. You likely have a problem with how you are handling your datatypes.
Here are a few things to look out for
You have too many quotes around your variables. Wrap the query in "" but save the '' for individual variables (where necessary, seen below). For instance, just wrap the variable once like so: .'$vorname'.' if the variable you are inputting is a string. If it is an integer (INT variable type), leave the quotes off, e.g.$number`. In other words, input strings as strings, and INT as int.
If the variable you wish to input is set as auto-increment in your database (i.e. it is the primary key), you probably don't want to be inputting it at all. For example, in your case $id appears to be one. If this is true, you have the syntax backward. Just input it as NULL or leave it off the insert, like so: insert into tablename (id, vorname) values (NULL, '$vorname')
You need to also sanitize your ALL of your variables if you to prevent SQL Injection (very possible with your code). You can do this with mysqli_real_escape_string()
OR instead of going through all of that, you could use prepared statements, which would both handle that information in a cleaner way, but also would protect your code against SQL injection.
Here's how to do this using mysqli:
Connect as an object:
$connect = new mysqli($host_name, $user_name, $password, $database);
And then feed your query into the object and bind the parameters. In this section, "s" is a string, "i" is an integer.
$insert = $connect->prepare("INSERT INTO offen(id, vorname, nachname, email)
VALUES (NULL, ?,?,?");
$insert->bind_param("sss", $vorname, $nachname, $email);
$insert->execute();
$insert->close();
If you name your variables correctly, this should work.

Login with url paramaters

I'm creating a login system of sorts that uses parameters from the URL.
The parameters are set no problem. I dont know what the issue is.
Here's my code:
<?php
require_once("db_const.php");
$mysqli = new mysqli("dont", "try", "to login to", "my database");
# check connection
if ($mysqli->connect_errno) {
echo "<p>MySQL error no {$mysqli->connect_errno} : {$mysqli->connect_error}</p>";
exit();
}
$username = filter_input(INPUT_GET,"username",FILTER_SANITIZE_STRING);
$password = filter_input(INPUT_GET,"password",FILTER_SANITIZE_STRING);
$sql = "SELECT * from users WHERE username LIKE '{$username}' AND password LIKE '{$password}' LIMIT 1";
$result = $mysqli->query($sql);
if (!$result->num_rows == 1) {
echo "failed";
} else {
echo "success";
}
?>
There are a few problems with your code.
The problem is the use of the LIKE function. Your usage is
SELECT * from users WHERE username LIKE '{$username}' AND password LIKE '{$password}' LIMIT 1
Like requires additional specification to find match positions and such, for example :
SELECT ... WHERE username LIKE '%{$username}%'
In the form you used, the WHERE clause if equivalent to
SELECT ... WHERE username = '{$username}'
In addition, LIKE is not recommended even (especially) with the wildcards, as 'tom' will match users 'tom' and 'tommy', and the count will certainly not be == 1.
I'll also urge you to test the query for errors
if (!$result) {
echo 'An error occurred : $mysqli->error;
}
Others have already mentioned the risk in passwing username and passwords on the URL, Please take note of their comments.
In addition, storing the password in plain form the database is not recommended for security reasons. There are plenty of resources explaining how to encrypt passwords and authenticate using the encrypted values.
Try:
$sql = "SELECT * from users WHERE username='$username' AND password='$password'";
CAUTION
Even if the above code solves your problem, It's still very dangerous as it's vulnerable for SQL injection on both username and password parameters and it can be exploited in a manner that a malicious user can bypass the login check by breaking out of the quotes and adding a condition that evaluates to true.
You can use a mysqli::prepare to get over that.
$stmt = mysqli->prepare("SELECT * from users WHERE username=? AND password=?");
$stmt->bind_param("ss", $username,$password);
$stmt->execute();

JSON encode comma delimited row

I'm trying to add an autocomplete tokenizer script to some form fields and one issue I'm having is if a person saves multiple values for the field the autocomplete suggestions come back with all of his values as one long value instead of them being single values delimited by the comma. I first tried to simply explode the value but it doesn't format it correctly in the JSON encode.
Here is my PHP file:
//connection information
$host = "localhost";
$user = "myuser";
$password = "mypass";
$database = "mydb";
$param = ($_GET["term"]);
//make connection
$server = mysql_connect($host, $user, $password);
$connection = mysql_select_db($database, $server);
//query the database
$query = mysql_query("SELECT cb_activities FROM jos_comprofiler WHERE cb_activities REGEXP '^$param'");
//build array of results
for ($x = 0, $numrows = mysql_num_rows($query); $x < $numrows; $x++) {
$row = mysql_fetch_assoc($query);
$activities[$x] = array(cb_activitiesterm => $row[cb_activities]);
}
//echo JSON to page
$response = $_GET["callback"] . "(" . json_encode($activities) . ")";
echo $response;
mysql_close($server);
This gives the output like this:
[{"cb_activities":"Kicking Cats,"},{"cb_activities":"baseball,hockey,"}]
but I need it to output like this:
[{"cb_activities":"Kicking Cats,"},{"cb_activities":"baseball,"},"cb_activities":"hockey,"}]
I also need to find a way to prevent duplicate entries from populating. For instance, the way it is now, say 10 people all have kicking cats selected as a value, it will display 10 times in the autocomplete suggestions.
How do I set this up to correctly delimit at the commas and then weed out duplicate values?
NM the duplicate issue, I just added select distinct instead of just select, this json thing has me overcomplicating things now lol. Now if I can just figure out how to delimit properly at the comma all will be good.