PHP code can UPDATE MySQL database, but can't INSERT - php

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) ""

Related

What is servername

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.

PHP mySQL Update doesn't work

I currently have a very big problem with PHP and mySQL. I moved a System I coded to a new Server. And while everything worked fine on the old Server, I had some problems on the new Server. Especially with mySQL. While I solved nearly all of them, I have one which I can't seem to get a hold on. And after 2 hours of trying i searched on the Internet for another two hours and updated my Syntax several times. But nothing seems to work. So now I'm here. I get a Connection to the database without a problem, but I can't update the values. I hope you can help me.
//Connect to mySQL Database
$verbindung = mysql_connect($server, $username, $passwort);
if (!$verbindung) {
echo "Couldn't connect: " . mysql_error();
}
$name=$_POST['fuehrer'];
$ident=$_POST['id'];
//Debugging
echo $name;
echo $ident;
$sql_befehl_0="UPDATE 'olgatermine' SET fuehrer = '".$name."' WHERE ID = '".$ident."';";
if (!mysql_query($verbindung, $sql_befehl_0)){
echo "Couldn't write to database";
}
//Close connection
mysql_close ( $verbindung );
What version of php use? Because in the newest versions of php the mysql functions are deprecated/removed, use instead mysqli.
Try to echo a mysqli_error at the end of the code, also mysql_error if your version of php accepts mysql functions.
If not version of php is the problem check this:
Wrong things what i see in your code..:
$sql_befehl_0="UPDATE 'olgatermine' SET fuehrer = '".$name."' WHERE ID = '".$ident."';"; // wrong
should be:
$sql_befehl_0="UPDATE `olgatermine` SET `fuehrer` = '".$name."' WHERE ID = '".$ident."';";
You need to run mysql_select_db('dbname') below line you do the mysql connection.
You can set at the first line of file:
ini_set('display_errors',1);
error_reporting(E_ALL);
to show all errors.

Access denied for user ''#'localhost' (using password: NO) when using PHP+MySQL in openshift

i have upload my web application to OpenShift.
my application is using the PHP and MySQL Cartridges.
i have created a few databases using PHPmyAdmin (Through the openshift web interface). each database has it's own unique name obviously.
in my PHP code i initialize the connection to one of my MySQL databases in this fashion:
$mysql_database=<some data base>;
$connection = mysqli_connect(getenv('OPENSHIFT_MYSQL_DB_HOST'), getenv('OPENSHIFT_MYSQL_DB_USERNAME'), getenv('OPENSHIFT_MYSQL_DB_PASSWORD'), "$mysql_database", getenv('OPENSHIFT_MYSQL_DB_PORT')) or die("Error: " . mysqli_error($connection));
mysql_set_charset("utf8", $connection);
then somewhere else i am doing some queries from my PHP code (like select , update and so on) on tables inside the database i connected to. for example:
$query_run=mysql_query("SELECT * from `$some_table` WHERE `id`='$id'")
the connection itself does not fail on anything, however all my queries fail on :
Access denied for user ''#'localhost' (using password: NO)
When i manually issue these commands on the actual machine everything runs fine. so this works: SSHing into my machine using PuTTy , and doing :
mysql -u $OPENSHIFT_MYSQL_DB_USERNAME -h $OPENSHIFT_MYSQL_DB_HOST -P $OPENSHIFT_MYSQL_DB_PORT -p <some data base>
mysql>SELECT * from `<some table>` WHERE `id`='<some id>'
i did not modify the security settings of anything, neither did i change the username / password that were generated for me for the MySQL actions.
also, everything runs perfectly fine on my local application running on a xampp Apache+MySQL server.
any ideas?
You shouldn't really be using mysql_query() like that (see Is this query safe from sql injection?)
You can use a much better abstraction: PHP Data Objects (PDO). e.g.
try {
// Set your connection variables
$host = getenv('OPENSHIFT_MYSQL_DB_HOST');
$port = getenv('OPENSHIFT_MYSQL_DB_PORT');
$username = getenv('OPENSHIFT_MYSQL_DB_USERNAME');
$password = getenv('OPENSHIFT_MYSQL_DB_PASSWORD');
$dbname = 'database_name';
// Create the connection string
$conn_str = "mysql:host=$host;port=$port;dbname=$dbname"
// And create a db handler with PDO
$dbh = new PDO($conn_str, $username, $password);
// Prepare whatever statement, could also be SELECT etc
$stmt = $dbh->prepare("INSERT INTO TABLE_NAME (name, value) VALUES (?, ?)");
// Binding parameters like this prevents SQL Injection
$stmt->bindParam(1, $name);
$stmt->bindParam(2, $value);
// Assign values to the variables
$name = 'Random';
$value = 1;
// Finally, execute the statement
$stmt->execute();
}
catch(PDOException $e) {
// Print out whatever error we got
echo $e->getMessage();
}
// Don't forget to close the connection
$dbh = null
Not only this is a better solution for handling MySQL databases with PHP, but hopefully it will also fix your authentication problems (or make them easier to debug, at least).
Stop and Start your application (not a restart). Sometimes apache needs to be restarted to pick up the new mysql environment variables.

PHP mysql_query() No such file or directory found?

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

Connecting .php file to mySQL database

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.

Categories