I have made a program using PHP and trying to store data into Local Server Xampp, but whenever i run my php script using this url:
http://127.0.0.1/test.php
Getting error message: {"StatusID":"0","Error":"Cannot save data!"}
Please someone help me in this how can i make it useful for me, please check below PHP Script:
<?php
$objConnect = mysql_connect("localhost","root","");
mysql_error($ObjConnect);
$objDB = mysql_select_db("registration_login");
mysql_error($ObjDB);
$strUsername = $_POST["sUsername"];
$strPassword = $_POST["sPassword"];
$strName = $_POST["sName"];
$strEmail = $_POST["sEmail"];
$strTel = $_POST["sTel"];
/*** Insert ***/
$strSQL = "INSERT INTO member (Username,Password,Name,Email,Tel)
VALUES (
'".$strUsername."',
'".$strPassword."',
'".$strName."',
'".$strEmail."',
'".$strTel."'
)
";
$objQuery = mysql_query($strSQL);
mysql_error($ObjQuery);
if(!$objQuery)
{
$arr["Status"] = "0";
$arr["Message"] = "Cannot Save Data!";
echo json_encode($arr);
exit();
}
else
{
$arr["Status"] = "1";
$arr["Message"] = "Register Successfully!";
echo json_encode($arr);
exit();
}
mysql_close($objConnect);
?>
Note: I have created registration_login database and member table under this DB..
Why don't you return the error reported by mysql or log it somewhere?
$objConnect = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
You forgot to check the return the return value to see if this was successful - if it failed, the reason is in mysql_error()
$objDB = mysql_select_db(DB_DATABASE);
You forgot to check the return the return value to see if this was successful - if it failed, the reason is in mysql_error()
$objQuery = mysql_query($strSQL);
At least this time you check the return value - but you don't check what the error was.
BTW your script is wide open to SQL injection.
Convert mysql_* to PDO
What has that got to do with your post?
Related
When I was trying to make website for school project then I make a registration page so I make a html page and a php and a database.
But when I tried to enter anything in form then the result after submitting the information is blank page. When I opened php file in browser then a blank page opened. There should be either connected to the database or failed to connect to database. My coding of php file is given below:
Please help me as less time is remaining for last date of submission.
<?php
define('DB_HOST', 'localhost');
define('DB_NAME', 'practice');
define('DB_USER', 'root');
define('DB_PASSWORD', '');
$con = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) or die("Failed to connect to MySQL: " . mysql_error());
$db = mysql_select_db(DB_NAME, $con) or die("Failed to connect to MySQL: " . mysql_error());
function NewUser()
{
$fullname = $_POST['name'];
$userName = $_POST['user'];
$email = $_POST['email'];
$password = $_POST['pass'];
$query = "INSERT INTO websiteusers(fullname,userName,email,pass) VALUES ('$fullname','$userName','$email','$password')";
$data = mysql_query($query) or die(mysql_error());
if ($data) {
echo "YOUR REGISTRATION IS COMPLETED...";
}
}
function SignUp()
{
if (!empty($_POST['user'])) //checking the 'user' name which is from Sign-Up.html, is it empty or have some text
{
$query = mysql_query("SELECT * FROM websiteusers WHERE userName='$_POST[user]' AND pass = '$_POST[pass]'") or die(mysql_error());
if (!$row = mysql_fetch_array($query) or die(mysql_error())) {
newuser();
} else {
echo "SORRY...YOU ARE ALREADY REGISTERED USER...";
}
}
}
if (isset($_POST['submit'])) {
SignUp();
}
?>
MySQL is depreciated. Use MySQli instead
Connect to your database this way
$connect = mysqli_query(DB_HOST,DB_USER,DB_PASSWORD,DB_NAME);
then check this way
if($connect){
echo "Connected";
}else{
echo "Not connected";
}
and any query you run should be in this format
$query = mysqli_query($connect,$Sql);
I tried many source codes from google but I am unsuccessful everytime. Everytime I clicked on submit button it shows a blank page. Please provide me help I want to create a signup page and in this I want to connect html coding to mysql database I have knowledge about html. So please provide an easy way to interconnect the database and html.
I also came to know about the php so I tried to copy source code from google but everytime I failed as php preview in browser is blank page.
I'm trying to execute an Insert query to write data into a Database. I'm using Mysqli and PHP.
The code looks OK for me. However, every time I go to the webpage to check if the form works, the query gets executed an a new row is created in the DB (empty).
I'm pretty sure there is something wrong with the last if statement. Could you advise?
BTW, the snippet is only for the PHP to execute the sql query, since the form is working just fine.
Thanks!
$servername = "localhost";
$username = "root";
$password = "mysqlpassword";
$dbname = "bowieDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$album = $_POST['album'];
$relyear = $_POST['relyear'];
$label = $_POST['label'];
$chart = $_POST['chart'];
$track1 = $_POST['track1'];
$track2 = $_POST['track2'];
$track3 = $_POST['track3'];
$track4 = $_POST['track4'];
$track5 = $_POST['track5'];
$sql = "INSERT INTO Albums (album, relyear, label, chart, track1, track2, track3, track4, track5)
VALUES ('$album', '$relyear', '$label', '$chart', '$track1', '$track2', '$track3', '$track4', '$track5')";
$result = mysqli_query($conn, $sql);
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
You are mixing Procedural and Object Orientated SQL interactions.
This is Procedural:
$result = mysqli_query($conn, $sql);
This is Object Orientated:
$conn->query($sql)
You can not use both with the same connection details, you should do one or the other throughout your code. The best one to use is Object Orientated approach, so rework the Procedural code to:
$result = $conn->query($sql);
if ($result) {
...
So actually you can simply remove the line starting $result = ... and let the IF statement query you already have handle itself.
Other notes:
Use MySQL error feedback such as checking if(!empty($conn->error)){print $conn->error;} after SQL statements. See example code below...
Use the following PHP error feedback too, set at the very top of your PHP page:
...
error_reporting(E_ALL);
ini_set('display_errors',0);
ini_set('log_errors',1);
you need to read up and be aware of SQL injection that can destory your database should someone POST data that also happens to be MySQL commands such as DROP.
Code for Comment:
if ($_SERVER['REQUEST_METHOD'] == "POST") {
//run SQL query you already have coded and assume
// that the form has been filled in.
$result = $conn->query($sql);
if ($result) {
//all ok
}
if(!empty($conn->error)) {
print "SQL Error: ".$conn->error;
}
}
use
1. if(isset($_POST['Submit'])){//your code here }
and
2. if($result){...
if you are using procedural method
I have an assignment where I have to make a registration page in php.... I just want to keep things simple so making the form work is all I'm aiming for. I am aware of the vulnerability of sql injections/plaintext, but that's the last of my worries for now since it's a class assignment.
The script below works as far as inserting new users/passwords, but if there's an existing user, the page is blank and doesn't give a warning. I'm looking for help in giving the error "Sorry, this user already exists" shown on the screen (or something).
Thanks :D.
<?php
define('DB_HOST', 'localhost');
define('DB_NAME', '////////');
define('DB_USER','/////////');
define('DB_PASSWORD','///////////');
$con=mysql_connect(DB_HOST,DB_USER,DB_PASSWORD) or die("Failed to connect to MySQL: " . mysql_error());
$db=mysql_select_db(DB_NAME,$con) or die("Failed to connect to MySQL: " . mysql_error());
function NewUser() { $userName = $_POST['user']; $password = $_POST['pass']; $query = "INSERT INTO UserName (userName,pass) VALUES ('$userName','$password')"; $data = mysql_query ($query)or die(mysql_error()); if($data) { echo "YOUR REGISTRATION IS COMPLETED..."; } } function SignUp() { if(!empty($_POST['user'])) {
$query = mysql_query("SELECT * FROM UserName WHERE userName = '$_POST[user]' AND pass = '$_POST[pass]'") or die(mysql_error());
if(!$row = mysql_fetch_array($query)))
{ newuser(); }
else { echo "SORRY...YOU ARE ALREADY REGISTERED USER..."; } } } if(isset($_POST['submit'])) { SignUp(); } ?>
First, Its really important check your php_error_log or Add error reporting into the TOP of your file.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
There is an extra closing parenthesis and you are calling an undefined function.
Assuming these are the errors, fix then with:
if(!$row = mysql_fetch_array($query)) {
NewUser();
}
else {
echo "SORRY...YOU ARE ALREADY REGISTERED USER...";
}
Also, consider using mysqli with prepared statements, or PDO with prepared statements, they're much safer.
Hope it helps you.
Thanks to #bcesars for the extra parenthesis fix. I thought there was something odd with the count.
After, I came up with a problem where the "This user already exists" error pops up ONLY if the user and pass matches the same one in the database. If I use a different password, the info is still inserted into the database.
Solution:
Remove
AND pass = '$_POST[pass]'
from
$query = mysql_query("SELECT * FROM UserName WHERE userName = '$_POST[user]' AND pass = '$_POST[pass]'") or die(mysql_error());
So far it works. I'm still new into this whole database/php thing so thanks for bearing with me ♥
Essentially, I am trying to print out information in JSON so that I can communicate with my app, but I cannot connect to the MySQL database from a php script for some odd reason. What could it be that causes the error:
Warning: mysql_connect() [function.mysql-connect]: Lost connection to MySQL server during query in /srv/disk11/1158855/www/(myphpwebsite)/lib.php on line 13
Could not connect: Lost connection to MySQL server during query.
Also, line 13 is indicating the line in lib.php:
mysql_connect ( $dbhost, $dbuser, $dbpass) or die("Could not connect: ".mysql_error());
It should also be noted that this is a followup to a previous question in case anyone wanted to track down the source: MySQL issue connecting to site with php.
Lastly, I get the same error from both a localhost and a remote server using mysql
lib.php
<?
//Database Information
$dbhost = "31.170.160.76";
$dbname = "testdatabase";
$dbuser = "(personalinformation)";
$dbpass = "tested123";
//Connect to database
mysql_connect ( $dbhost, $dbuser, $dbpass) or die("Could not connect: ".mysql_error());
mysql_select_db($dbname) or die(mysql_error());
//executes a given sql query with the params and returns an array as result
function query() {
global $link;
$debug = false;
//get the sql query
$args = func_get_args();
$sql = array_shift($args);
//secure the input
for ($i=0;$i<count($args);$i++) {
$args[$i] = urldecode($args[$i]);
$args[$i] = mysqli_real_escape_string($link, $args[$i]);
}
//build the final query
$sql = vsprintf($sql, $args);
if ($debug) print $sql;
//execute and fetch the results
$result = mysqli_query($link, $sql);
if (mysqli_errno($link)==0 && $result) {
$rows = array();
if ($result!==true)
while ($d = mysqli_fetch_assoc($result)) {
array_push($rows,$d);
}
//return json
return array('result'=>$rows);
} else {
//error
return array('error'=>'Database error');
}
}
//loads up the source image, resizes it and saves with -thumb in the file name
function thumb($srcFile, $sideInPx) {
$image = imagecreatefromjpeg($srcFile);
$width = imagesx($image);
$height = imagesy($image);
$thumb = imagecreatetruecolor($sideInPx, $sideInPx);
imagecopyresized($thumb,$image,0,0,0,0,$sideInPx,$sideInPx,$width,$height);
imagejpeg($thumb, str_replace(".jpg","-thumb.jpg",$srcFile), 85);
imagedestroy($thumb);
imagedestroy($image);
}
?>
Index.php
<?
session_start();
require("lib.php");
require("api.php");
header("Content-Type: application/json");
switch ($_POST['command']) {
case "login":
login($_POST['username'], $_POST['password']); break;
case "register":
register($_POST['username'], $_POST['password']); break;
}
exit();
?>
api.php
<?php
function errorJson($msg){
print json_encode(array('error'=>$msg));
exit();
}
function register($user, $pass) {
//check if username exists
$login = query("SELECT username FROM login WHERE username='%s' limit 1", $user);
if (count($login['result'])>0) {
errorJson('Username already exists');
//try to register the user
$result = query("INSERT INTO login(username, pass) VALUES('%s','%s')", $user, $pass);
if (!$result['error']) {
//success
login($user, $pass);
} else {
//error
errorJson('Registration failed');
}
}
}
function login($user, $pass) {
$result = query("SELECT IdUser, username FROM login WHERE username='%s' AND pass='%s' limit 1", $user, $pass);
if (count($result['result'])>0) {
//authorized
$_SESSION['IdUser'] = $result['result'][0]['IdUser'];
print json_encode($result);
} else {
//not authorized
errorJson('Authorization failed');
}
}
?>
As this is on the "connect" line, the server has been found (otherwise you get a different message) but you've not negotiated your log in.
Straight from the manual:
More rarely, it can happen when the client is attempting the initial connection to the server. In this case, if your connect_timeout value is set to only a few seconds, you may be able to resolve the problem by increasing it to ten seconds, perhaps more if you have a very long distance or slow connection.
If that isn't it, it's either a network problem or your connection has been terminated mid-authentication. Check that your mysql host doesn't have some weird validation that you're coming from a particualr IP (I say weird, as there are more standard ways of managing it than killing the authentication mid-flow), or try your PHP script from a a server that is closer to the MySQL server (closer in terms of network speed).
I figured out what was the matter. It turns out that my php code further down was conflicting with the login. That's why it wouldn't authenticate on multiple remote MySQL's and my own Localhost
I am using this code to insert some values in MySql table:
<?php
mysql_connect("localhost","root","root");
mysql_select_db("bib");
$id = "12";
$titlu = "Joe";
$query = "INSERT INTO carte SET id='$id', titlu='$titlu'";
$result = mysql_query($query);
// Display an appropriate message
if ($result)
echo "<p>Product successfully inserted!</p>";
else
echo "<p>There was a problem inserting the Book!</p>";
mysql_close();
?>
After running it into browser, the following error occurs:
"Apache HTTP Server has encountered a problem and needs to close. We are sorry for the inconvenience."
It seems that mysql_select_db("bib") statement causes it. Database is create , also table...
I am running php 5.3 and mysql 5.1 on windows xp sp 2.
Please any ideas are welcomed...
Thanks...
Any of the mysql_* functions can fail for various reasons. You have to check the return values and if a function indicates an error (usually by returning FALSE) your script has to react appropriately.
mysql_error($link) and mysql_errno($link) can give you more detailed information about the cause. But you don't want to show all the details to just any arbitrary user, see CWE-209: Information Exposure Through an Error Message.
If you don't pass the connection resource returned by mysql_connect() to subsequent mysql_* functions calls, php assumes the last successfully established connection. You shouldn't rely on that; better pass the link resource to the functions. a) If you ever have more than one connection per page you must pass it anyway. b) If there is no valid db connection the php-mysql modules tries to establish the default connection which is usually not what you want; it only takes up more time to fail ..again.
<?php
define('DEBUGOUTPUT', 1);
$mysql = mysql_connect("localhost","root","root");
if ( !$mysql ) {
foo('query failed', mysql_error());
}
$rc = mysql_select_db("bib", $mysql);
if ( !$rc) {
foo('select db', mysql_error($mysql));
}
$id = "12";
$titlu = "Joe";
$query = "INSERT INTO carte SET id='$id', titlu='$titlu'";
$result = mysql_query($query, $mysql);
// Display an appropriate message
if ($result) {
echo "<p>Product successfully inserted!</p>";
}
else {
foo("There was a problem inserting the Book!", mysql_error($mysql), false);
}
mysql_close($mysql);
function foo($description, $detail, $die=false) {
echo '<pre>', htmlspecialchars($description), "</pre>\n";
if ( defined('DEBUGOUTPUT') && DEBUGOUTPUT ) {
echo '<pre>', htmlspecialchars($detail), "</pre>\n";
}
if ( $die ) {
die;
}
}
try this to connect to database:
$mysqlID = mysql_connect(DB_HOST, DB_USERNAME, DB_PASSWORD) or die("Unable to connect to database");
mysql_select_db(DB_DATABASE) or die("Unable to select database ".DB_DATABASE);
also, try this as your insert query:
$query = "INSERT INTO carte (id, title) values ('".$id."', '".addslashes($titlu)."')
$result = mysql_query($query) or die(mysql_error());
By using die(), it will tell you where it has failed and why