I have a MySQL database set up with Hostmysite.com. It connects just fine, and the idea of my php file is to take form values and input it into the SQL database. I am trying to create a feature that doesn't allow duplicate entries by comparing the email to see if it exists in the db...
The php code I think is right, but on die() it returns No such file or directory found??? That doesn't make sense.
<?php
//connection variables is excluded to get to the point of the problem
$con = mysqli_connect($host, $user, $pass, $db);
if (!$con){
die("Connection failed: " .my_sqli_connect_err());
}
$email = $_POST["email"];
$email = mysqli_real_escape_string($con, $email);
//see if email exists in database
$findEmail = "SELECT * FROM rsvpWedding WHERE email='" . $email."';";
$results = mysql_query($findEmail)or die(mysql_error());
?>
The:
$results
Returns a No such file or directory exists? I don't understand the SQL statement is correct and I believe my php code is also correct.
I don't know if this has anything to do with the problem, but this does mix:
mysqli_*();
with
mysql_*();
*****UPDATE ******
I believe I understand why I am getting that error of No such file or directory found. According to the web page : http://php.net/manual/en/function.mysql-query.php When sql_query() is executed it tries to connect to a link that was executed on
sql_connect()
not
sqli_connect()
If it can't find one it will try and attempt a connection with sql_connect() with no arguments, if that fails it will generate an error.. From researching online I see that No such file or directory is normally associated with sql_connect() errors.
So i suppose my question to this post sort of changes to how do I create a resource using the sqli_* syntax. I tried
$results = mysqli_query($con, $findEmail) or die(mysql_error());
but that still doesn't work, it just skips that entire code block... doesn't even produce an error.
This might be caused by mysql.sock file path is not configured properly for php.
So please make sure you installed the mysql db engine, and find where the mysql.sock file is located.
Then you need to configure in php.ini file:
Find these lines, configure like the following:
mysql.default_socket = /path/mysql.sock
mysqli.default_socket = /path/mysql.sock
pdo_mysql.default_socket = /path/mysql.sock
Restart apache server and mysql service
You can't mix mysqli_* with mysql_*. It's safer to do it the mysqli way anyways:
//see if email exists in database
$stmt = $con->prepare('SELECT * FROM rsvpWedding WHERE email=?'); // question mark is a placeholder
$stmt->bind_param('s', $email); // 's' means it's a string
$stmt->execute();
$stmt->bind_result($result); // assign the result to your $result var
$stmt->fetch();
See the docs here:
http://php.net/manual/en/mysqli.prepare.php
your not printing anything thats why!
try using mysqli_num_rows($result)
echo that one
if its greater than zero then it exist
if none then youre all good
Related
So I'm starting to learn how to use PHP to access MYSQL databases and after successfully connecting to the database. I want to select data from it. However I get the issue that the table doesn't exist. Yet, it exists when I check it in my phpmyadmin. I've checked spelling, capitalization, etc.. and nothing works. I've tried it with multiple databases and I get the same error. So I'm really confused as to whats going on because from the looks of it, there is NOTHING wrong with the code. I've tried running the SQL query in phpmyadmin just to verify that the query works.. and it does. I just get the error "Table 'test.blog_table' doesn't exist" with the code below
<?php
$host = "localhost";
$user = "root";
$password = "";
$database_in_use = "test";
$conn = new mysqli($host, $user, $password, $database_in_use);
if ($conn->connect_errno) {
echo "Failed to connect to MySQL: (" . $conn->connect_errno . ") " . $conn->connect_error;
}
echo $conn->host_info . "<br>";
$sql = "SELECT * FROM blog_table";
$result = $conn->query($sql);
$result = $conn->query($sql) or die($conn->error);
$conn->close();
?>
So I'm just completely lost and have no idea whats going on with it.
Solved! I connected to the wrong database, which is why the tables were there, but weren't showing up. Since I was connecting to a different database and the one I created tables in didn't have the default port.
Probably you are missing the mysqli and the mysqlnd PHP extensions.
Also, I recommend you to use \PDO object to fetch queries to your DB instead of the mysqli driver, if you do it, you will be free to change in the future to a PostgreSQL DB for example anytime just changing the DSN in the constructor (you need for that the PDO and the pdo_whatever_db_driver (e-g.: pdo_mysql) extensions.
My update of the database has no problems whatsoever. And down in my local development environment a new record insert also has no problems. I have tried changing my MySQL user many times because I thought it might be about permissions (maybe that is still the problem, I don't know). I have even made the user root and supplied my correct root password: again, I can perform updates, but no new record inserts. Here is my code which I have shortened (i.e taken out the large number of fields. It works locally, but not on the server).
I am on Ubuntu Linux, 16.04, PHP 7
$message = '';
$db = new mysqli('localhost', 'root', 'notrealpword', 'mydatabase');
if ($db->connect_error){
$message = $db->connect_error;
}else{
// echo $message ;
}
$prep = $db->prepare("INSERT INTO users (userid, username) VALUES
('0',?)");
//Now, you can bind some parameters.
$prep->bind_param('s',$username);
$username = "atservertest";
$prep->execute();
$numaffected = $prep->affected_rows ;
echo $numaffected;
// echo $numaffected . " row(s) affected." ;
$prep->close();
$username must initialize first.
//Call this first
$username = "atservertest";
//Then use bind_param
$prep->bind_param('s',$username);
FIXED MY OWN PROBLEM:
This is caused by the STRICT_TRANS_TABLES SQL mode.
Open phpmyadmin and goto More Tab and select Variables submenu. Scroll down to find sql mode. Edit sql mode and remove STRICT_TRANS_TABLES Save it.
My local phpmyadmin settings were different than the settings for phpmyadmin up at my new server. ... Note that to made the configuration changes above I needed to login as root at phpmyadmin ...
It works, my environment is MacOS and PHP 7.1.12, MySQL 5.6.21
Add code:
$prep->execute();
// see if any error happend
var_dump($db->error_list, $db->error);
to see if any error happend.
If no error, then the result should be
array(0) {
}
string(0) ""
i just wanted to insert data into database from a form, with php. i ran the code below in my Localhost using XAMPP and everything was fine but where i upload it to my host it didn't work.
Question is What shold i put for $servername and when should i look for it ?
There is my codes:
Register.php (in localhost)
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
$Name = $_POST['Name'];
$Username = $_POST['Username'];
$Password = $_POST['Password'];
$Email = $_POST['Email'];
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
header("Location:#");
}
//Inserting Data
try{
$sql = "INSERT INTO User (uName , uUsername , uPassword , uEmail) VALUES ('$Name' , '$Username' , '$Password' , '$Email')";
mysqli_query($conn, $sql);
}catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
$conn->close();
header("Location:#");
}
?>
If your MySQL database is on the SAME SERVER as your PHP script, then the usual logical approach is that your host is localhost. The same as you used on your local computer -- because they're on the same machine.
However, if your MySQL database is on ANOTHER SERVER seperate from your PHP scripts the you will need to access that server using a web address for your PHP to connect to yout MySQL.
We can't tell you what that is, and your server hosts (of your MySQL server) will be able to tell you and provide you with the correct login credentials.
I believe it would be more usual for MySQL and PHP to be on the same disk, especially for non-professional systems as your appears to be, so then the issue would be:
Are your login details set up correcty on your server? (same username/password)
Are there any MySQL errors or PDO errors (if you connect with PDO). Don't redirect on error, but instead output the error to a log file so you can read WHY the MySQL in your code didn't connect.
It is still possible for you to set your PHP to communicate with your localhost MySQL via a remote address (such as servername=$_SERVER['SERVER_NAME'];). (see note below)
Many online accounts (in things such as CPanel) will block you from accessing the MySQL as a root or at least will not give you the root MySQL password. Using root to access MySQL via PHP is NOT a good idea and you should instead set up a specific MySQL user for your PHP with only enough privileges that you need to read/write to the DB, and nothing more.
If your MySQL is remote (not localhost) then you may also need to supply a Port Number with the connection details. Usual port numbers are 3306 but this is something you'd need to know from your server hosts.
Immediately after a header(Location:); redirection instruction you should always set die(); or exit to stop PHP processing the rest of the script.
Your SQL insert data is highly suseptible to SQL injection and other SQL attacks and compromise. You should really, REALLY look into using MySQL Prepared Statements, you're already coding in OO style so you're almost there already.
Example remote connection from the manual
<?php
/***
* Remember 3306 is only the default port number, and it could be
* anything. Check with your server hosts.
***/
$conn = new mysqli('remote.addr.org.uk', 'username', 'my_password', 'my_databasa', '3306');
/***
* This is the "official" OO way to do it,
* BUT $connect_error was broken until PHP 5.2.9 and 5.3.0.
***/
if ($conn->connect_error) {
error_log('MySQL Connect Error (' . $conn->connect_errno . ') '
. $conn->connect_error);
}
/***
* Upon failure, the above will output a connection error notice such as
* user not found or password incorrect. It won't explicity say these
* things but you should be able to deduce which from the notice
***/
echo "Success... \n" . $conn->host_info ;
$mysqli->close();
# : I seem to think that MySQL detects when the remote address given is the same as the server address and auto converts it to localhost, but I'm not sure on this.
The long and the short of it is that if your MySQL is on the same
server as your PHP it makes no sense to open up a network loop to send
data out just to get it back again. Use localhost instead.
I asked my host service providers about the "$servername" and they answered me that the "$serverneme" is localhost.
I am attempting to create new tables every time I post to this method, but for some reason I can not figure out why it dies.
<?php
$host = "127.0.0.1";
$username = 'cotten3128';
$pwd = 'pwd';
$database = "student_cotten3128";
$pin = $_REQUEST['pinSent'];
$words = $_REQUEST['resultSent'];
$tableName = $pin;
$db = new mysqli($host, $username, $pwd, $database);
if ($sql = $db->prepare("CREATE TABLE $pin (id INT(11) AUTO_INCREMENT);")) {
$sql->execute();
$sql->close();
}else{
echo $mysql->error;
die('Could not create table');
}
for($i=0;$i<count($words);$i++){
if($sql = $db->prepare("INSERT INTO ".$pin.$words[$i].";")) {
$sql->execute();
$sql->close();
}else{
echo $mysql->error;
die("Could not add data to table");
}
}
mysqli_close();
?>
Any help or insight would be greatly appreciated.
The intention of my post is to help you finding the issue by yourself. As you did not added much information I assume my post is helpful for you.
Based on the code you have shared I guess you mean one of your called die() functions is executed.
Wrong function call
As Jay Blancherd mentioned mysql_close is the wrong function. You rather have to use mysqli_close as you created a mysqli instance.
Beside of that mysql_* is deprecated and should not be used anymore.
Debugging Steps
Not only for this case but in general you should ask yourself:
Is there an error message available? (Frontend output, error log file, ...)
YES:
What's the message about?
Is it an error you can search for? E.g. via a search engine or the corresponding documentation?
Look up in the bug tracker (if available), by the software developer of the software you are using, and if it has not been reported yet report the issue.
NO: (if none error message available OR you cannot search for it as it is a custom error message)
Search in the files of the software you are using for the error message and start a core-debugging.
STILL NO SOLUTION?:
Ask on stackoverflow.com e.g. and tell your issue and the steps you have performed to find and fix the bug. Post only as much code as necessary plus use a proper format.
Debugging in your case:
In order to narrow down the scope. Which of the die() is executed? Depending on that echo the query to execute just before it actually is executed. Then copy the SQL query to an SQL editor and look at it syntax. After that you probably know the problem already.
What I am trying to do is get mysql database to load up my .php file. I am using hostgator to run mysql database server. So far what i have for sql is a table with three columns.
int: id (primary key / A.I.)
varchar: name
text: message
I save the table and name it "test" and the database is called "testdb"
My php file (tutorialTest.php) looks like this:
<?php
$username = "nfoggia_nick";
$password = "imnick";
$database = "nfoggia_testdb";
mysql_connect(localhost, $username, $password);
#mysql_select_db($database) or die("Unable to find database");
$name =$_GET["name"];
$message = $_GET["message"];
$query = "INSERT INTO test VALUES (' ', '$name', '$message')";
mysql_querry($query) or die(mysql_error("error"));
mysql_close();
?>
I added the .php file in my file directory on hostgator and now my problem is this:
I know that this code will do nothing, but when i type in
http://localhost/tutorialTest.php
the web browser says "browser cannot connect to local host" when it should just show a blank screen. Any help? What did i do wrong?
EDIT:
I moved my php file to the document root for my website and now when i run the
http://myWebsiteName/tutorialTest.php this shows up:
Fatal error: Call to undefined function mysql_querry() in /home2/nfoggia/public_html/tutorialTest.php on line 15
Before mentioning all the PHP errors, your URL is wrong.
localhost means your local computer, instead of your hosting environment, which you mentioned is hostgator.
Do you upload your PHP to hostgator server?
Is the MySQL database schema exist in hostgator environment?
Your URL should look like : http://www.hostgator.com/whatever/tutorialTest.php (or under your domain name). Anything but not http://localhost
First of all, remove the # to reveal the error.
For MySQL connection, the first parameter is a string, so you have to enclose it with single quotes, that is:
mysql_connect('localhost', $username, $password);
Last, you have multiple PHP errors :
mysql_querry($query)
You misspelled the function. Also, mysql_error() accepts link identifier as optional parameter instead of a string.
As a side note, stop using deprecated mysql_* functions. use MySQLi or PDO instead. Also, your code is subjected to SQL Injection attack, as you directly allow GET values to be inserted in your query.