I have a problem with mysql. When I execute this, that give me an error: No such file or directory 2002, but SELECT query work perfect and print typ on the screen. What can I solve this problem?
<?php
$con=mysqli_connect("db4free.net","****","****","*****");
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$username = $_GET['username'];
$password = $_GET['password'];
$result = mysqli_query($con,"SELECT Typ FROM Uzytkownik where Login='$username' and Haslo='$password'");
$row = mysqli_fetch_array($result);
$data = $row[0];
if($data){
echo $data;
}
$que = "INSERT INTO Uzytkownik VALUES ('10','tr','t','a')";
if( !mysql_query($que) ) {
echo "ERROR!!: ".mysql_error().mysql_errno() ;
}
mysqli_close($con);
?>
Result of this:
testERROR!!: No such file or directory2002
EDIT Sorry, I pasted wrong code, but it was already changed
You cannot mix mysqli_* functions with mysql_* functions.
replace this:
if( !mysql_query($que) ) {
echo "ERROR!!: ".mysql_error().mysql_errno() ;
}
with
if( !mysqli_query($con, $que) ) {
echo "ERROR!!: ".mysqli_error($con) ;
}
In the insert query you should tell which columns you're inserting into.
$que = "INSERT INTO Uzytkownik(col1, col2, col3, col4) VALUES ('10','tr','t','a')";
Also note that most of your queries are vulnerable to sql-injections, you should use prepared statements to protect your code.
Example: Your select query looks like this:
"SELECT Typ FROM Uzytkownik where Login='$username' and Haslo='$password'".
If I were a user I could get in without using a password, by ending the sql statement within the username or within the password, I could drop the table and I could even drop the entire database if I were a blackhat in a bad mood.
Using prepared statements means that instead of using user-input-provided values you replace the user inputs with VALUES(?, ?) and then you can bind parameters that will then be executed and replace the placeholders.
Using PDO allows you to use named paramters, you should take a look at that.
Also note that you're mixing mysql_* and mysqli_* which are not the same library of functions, stick to one (otherwise it simply won't work) and mysqli_* is way better since mysql_* is deprecated. This could be causing your problem.
Related
I'm trying to make my first registration script using PHP/SQL. Part of my code isn't working:
if(!$errors){
$query = "INSERT INTO users (email, password) VALUES ($registerEmail, $registerPassword)";
if(mysqli_query($dbSelected, $query)){
$success['register'] = 'Successfully registered.';
}else{
$errors['register'] = 'Registration did not succeed.';
}
}
When I test my code I get the error 'Registration did not succeed.' For reference, $errors and $success are arrays. Is there anything wrong with this part of my script?
$dbSelected is:
$dbLink = mysqli_connect('localhost', 'root', 'PASSWORD');
if (!$dbLink) {
die('Can\'t connect to the database: ' . \mysqli_error());
}
$dbSelected = mysqli_select_db($dbLink, 'devDatabase');
if (!$dbSelected) {
die('Connected database, but cannot select
devDatabase: ' . \mysqli_error());
}
I'm sure I am connecting and selecting the database.
Any help would be greatly appreciated! I am very new to PHP/SQL so forgive me for any noob mistakes.
Quote the string like below
$query = "INSERT INTO users (email, password) VALUES ('$registerEmail', '$registerPassword')";
You can also do
echo $query;
and take the output on the browser, copy and paste into PHPMyAdmin and execute it from there. It should tell you what is wrong with the query.
I suggest you to use prepared statement as using string concatenation in SQL Statement is prone to SQL injection attack. Refer the example PHP mysqli prepare
First off, PHP is deprecating mysql_ functions, you should migrate to PDO instead.
Also, make sure since you're using the older mysql_ functions to sanitize your entries using mysql_real_escape_string
Also, your entries need to be quoted. Here's a redo of your query string:
$query = "INSERT INTO users (email, password) VALUES ('{$registerEmail}', '{$registerPassword}')";
I am not sure what I am doing wrong, can anybody tell me?
I have one variable - $tally5 - that I want to insert into database jdixon_WC14 table called PREDICTIONS - the field is called TOTAL_POINTS (int 11 with 0 as the default)
Here is the code I am using. I have made sure that the variable $tally5 is being calculated correctly, but the database won't update. I got the following from an online tutorial after trying one that used mysqli, but that left me a scary error I didn't understand at all :)
if(! get_magic_quotes_gpc() )
{
$points = addslashes ($tally5);
}
else
{
$points = $tally5;
}
$sql = "INSERT INTO PREDICTIONS ".
"(TOTAL_POINTS) ".
"VALUES('$points', NOW())";
mysql_select_db('jdixon_WC14');
I amended it to suit my variable name, but I am sure I have really botched this up!
help! :)
I think you just need to learn more about PHP and its relation with MYSQL. I will share a simple example of insertion into a mysql database.
<?php
$con=mysqli_connect("localhost","peter","abc123","my_db");
// Check for errors in connection to database.
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query = "INSERT INTO Persons (FirstName, LastName, Age) VALUES ('Peter', 'Griffin',35)";
mysqli_query($con, $query);
mysqli_close($con); //Close connection
?>
First, you need to connect to the database with the mysqli_connect function. Then you can do the query and close the connection
Briefly,
For every PHP function you use, look it up here first.
(You will learn that it is better to go with mysqli).
http://www.php.net/manual/en/ <---use the search feature
Try working on the SQL statement first. If you have the INSERT process down, proceed.
You need to use mysql_connect() before using mysql_select_db()
Once you have a connection and have selected a database, now you my run a query
with mysql_query()
When you get more advanced, you'll learn how to integrate error checking and response into the connection, database selection, and query routines. Convert to mysqli or other solutions that are not going to be deprecated soon (it is all in the PHP manual). Good luck!
if(! get_magic_quotes_gpc() )
{
$points = addslashes ($tally5);
}
else
{
$points = $tally5;
}
mysql_select_db('jdixon_WC14');
$sql = "INSERT INTO PREDICTIONS (TOTAL_POINTS,DATE) ". //write your date field name instead "DATE"
"VALUES('$points', NOW())";
mysql_query($sql);
I'm fairly new to PHP/MySQL and I seem to be having a newbie issue.
The following code keeps throwing me errors no matter what I change, and I have a feeling it's got to be somewhere in the syntax that I'm messing up with. It all worked at home 'localhost' but now that I'm trying to host it online it seems to be much more temperamental with spaces and whatnot.
It's a simple login system, problem code is as follows:
<?php
session_start();
require 'connect.php';
echo "Test";
//Hash passwords using MD5 hash (32bit string).
$username=($_POST['username']);
$password=MD5($_POST['password']);
//Get required information from admin_logins table
$sql=mysql_query("SELECT * FROM admin_logins WHERE Username='$username' ");
$row=mysql_fetch_array($sql);
//Check that entered username is valid by checking returned UserID
if($row['UserID'] === NULL){
header("Location: ../adminlogin.php?errCode=UserFail");
}
//Where username is correct, check corresponding password
else if ($row['UserID'] != NULL && $row['Password'] != $password){
header("Location: ../adminlogin.php?errCode=PassFail");
}
else{
$_SESSION['isAdmin'] = true;
header("Location: ../admincontrols.php");
}
mysql_close($con);
?>
The test is just in there, so I know why the page is throwing an error, which is:
`Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in 'THISPAGE' on line 12`
It seems to dislike my SQL query.
Any help is much appreciated.
EDIT:
connect.php page is:
<?php
$con = mysql_connect("localhost","username","password");
if(!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("dbname", $con);
?>
and yes it is mysql_*, LOL, I'll get to fix that too.
You should escape column name username using backtick, try
SELECT *
FROM admin_logins
WHERE `Username` = '$username'
You're code is prone to SQL Injection. Use PDO or MYSQLI
Example of using PDO extension:
<?php
$stmt = $dbh->prepare("SELECT * FROM admin_logins WHERE `Username` = ?");
$stmt->bindParam(1, $username);
if ($stmt->execute(array($_GET['name']))) {
while ($row = $stmt->fetch()) {
print_r($row);
}
}
?>
Sean, you have to use dots around your variable, like this:
$sql = mysql_query("SELECT * FROM admin_logins WHERE Username = '". mysql_real_escape_string($username)."' ");
If you use your code just like this then it's vulnerable for SQL Injection. I would strongly recommend using mysql_real_escape_string as you insert data into your database to prevent SQL injections, as a quick solution or better use PDO or MySQLi.
Besides if you use mysql_* to connect to your database, then I'd recommend reading the PHP manual chapter on the mysql_* functions,
where they point out, that this extension is not recommended for writing new code. Instead, they say, you should use either the MySQLi or PDO_MySQL extension.
EDITED:
I also checked your mysql_connect and found a weird regularity which is - if you use " on mysql_connect arguments, then it fails to connect and in my case, when I was testing it for you, it happened just described way, so, please try this instead:
$con = mysql_connect('localhost','username','password');
Try to replace " to ' as it's shown in the PHP Manual examples and it will work, I think!
If it still doesn't work just print $row, with print_r($row); right after $sql=mysql_query() and see what you have on $row array or variable.
I'm using a .Jquery autocomplete function and I'm tring to figure out where can put the mysql_real_escape_string() at. I've tried a few different ideas but I'm just not sure. I get an error of...
Warning: mysql_real_escape_string(): Access denied for user 'www-data'#'localhost'
When I use $ac_term = mysql_real_escape_string("%".$_GET['term']."%"); I'm not even sure if that the right way to use it.
Here's what I have...
<?php
if (!isset($_SESSION)) {
session_start();
}
try {
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
}
catch(PDOException $e) {
echo $e->getMessage();
}
$return_arr = array();
if ($conn)
{
$ac_term = "%".$_GET['term']."%";
$query = "SELECT
CONCAT_WS('', '(',User_ID,') ', UserName, ' (',AccessLevel,')') AS DispName,
User_ID, UserName, AccessLevel
FROM Employees
WHERE UserName LIKE :term
OR User_ID LIKE :term
OR AccessLevel LIKE :term
";
$result = $conn->prepare($query);
$result->bindValue(":term",$ac_term);
$result->execute();
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
$row_array['value'] = $row['DispName'];
$row_array['User_ID'] = $row['User_ID'];
$row_array['UserName'] = $row['UserName'];
$row_array['AccessLevel'] = $row['AccessLevel'];
array_push($return_arr,$row_array);
}
}
$conn = NULL;
echo json_encode($return_arr);
?>
Any suggestions?
You don't have to add mysql_real_escape_string() to this query at all.
Just leave your code as is.
I believe that mysql_real_escape_string is not a right method to be used with PDO, for escaping purpose use PDO quote method.
As stated in documentation, escaping string is not necessary for prepare and execute statements:
Calling PDO::prepare() and PDOStatement::execute() for statements that will be issued multiple times with different parameter values optimizes the performance of your application by allowing the driver to negotiate client and/or server side caching of the query plan and meta information, and helps to prevent SQL injection attacks by eliminating the need to manually quote the parameters.
Prepared statement parameters don't need to be escaped; it's one of the main reasons for them.
Some PDO drivers don't currently support repeating a named parameter. Depending on which version of PHP is installed, you may need to create a separate parameter for each value.
You need to create the connection first. mysql_real_escape_string() relies on an active MySQL connection; it's trying to assume your credentials will let you connect to localhost most likely.
create an active, authenticated mysql connection prior to using mysql_real_escape_string(), and at least that error message should go away.
Additionally, the best way to use it would be:
$ac_term = mysql_real_escape_string($_GET['term']);
with your query looking like
$query = "SELECT ... FROM ... WHERE column LIKE '%$ac_term%'";
this is probably the most basic question in the world, but I cannot figure it out.
I would like to simply display a users First name, and Email adress from my table. I have tried using a loop, but that was entirely worthless considering I am only selecting one row. I know this is a menial question but I could not find/remember how to do it. Thank you!
$db = mysql_connect("server","un", "pw");
mysql_select_db("db", $db);
$sql = "SELECT FirstName, EmailAddress"
. " FROM Student"
. " WHERE StudentID = '$student' ";
$result = mysql_query($sql, $db);
$num = mysql_num_rows($result);
$userinfo = mysql_result($result,$userinfo);
$student is a session variable. I want to echo the First name and email address somewhere in the page, but I cannot believe how much pain thats causing me. Thanks again!
mysql_fetch_assoc() turns a result row into an array.
$result = mysql_query($sql, $db);
$user = mysql_fetch_assoc($result);
echo $user['FirstName'];
echo $user['EmailAddress'];
It looks like you spelled address wrong, so it probably doesn't match your real column name. More importantly, your code appears vulnerable to SQL injection. You really need to use prepared statements (see How to create a secure mysql prepared statement in php?) or escaping.
To fetch a row, you must use one of the mysql_fetch functions (e.g. mysql_ fetch_ array, mysql_ fetch_ object, etc.)