I'm trying to edit an item in a mySQL database generated list. Here is the code:
<?php
// contact to database
$connect = mysql_connect("<HOST>", "<USER>", "<PASSWORD>") or die ("Error , check your server connection.");
mysql_select_db("tvc");
?>
<html>
<head>
<title></title>
</head>
<body>
<?php
$result = mysql_query("UPDATE closet SET
pattern = '{$_POST['pattern']}'
WHERE id='{$_POST['id']}'") or die ("Error in query");
// if successfully updated.
if($result){
echo "Successful";
echo "<BR>";
echo "<a href='patterns.php'>Back to Patterns List</a>";
}
else {
echo "ERROR";
}
?>
</body>
</html>
I get an 'error in query' error message and I can't figure out what is causing it.
Any help would be much appreciated!
You forgot to remove , before WHERE
Change
$result = mysql_query("UPDATE closet SET
pattern = '{$_POST['pattern']}',
WHERE id='{$_POST['id']}'") or die ("Error in query");
To
$pattern = mysql_real_escape_string($_POST['pattern']);
$id= mysql_real_escape_string($_POST['id']);
$result = mysql_query("UPDATE closet SET
pattern = '".$pattern."' WHERE id='".$id."'") or
die("Could not connect: " . mysql_error());
Recommendations:
1.Learn to prevent from MySQL Injections: Good Link
2.Mysql extension is not recommended for writing new code. Instead, either the mysqli or PDO_MySQL extension should be used. More reading: PHP Manual
Related
I have Ubuntu 16.10 x86_64 x86_64. I installed LAMP to program in PHP and to create databases. In my php program I want to connect to my local database for creating a table ( in HTML ) with the data of any row of the table.
The problem is that when I open the php file( localhost/file.php ) through firefox ,the browser doesn't charge anything. If thare were been an error during the connection with the database, It would have printed something in the browser.
Here the code:
<!DOCTYPE html>
<html>
<head><title> SQL & PHP </title></head>
<body>
<?php
$db = mysql_connect("localhost", "root", "password")
or die ("Non riesco a creare la connessione");
mysql_select_db("scuola")
or die ("Non trovo il DB");
$sql = "SELECT id_utente, nome_utente, password_utente, conta_pres FROM utenti WHERE conta_pres <> 0";
$ris = mysql_query($sql) or die ("Query fallita!");
echo "<TABLE><TR><TH>ID utente <TH> Nome utente <TH>Password<TH>Contatore visite</TR>";
while ($riga= mysql_fetch_array($ris))
{
echo ("<TR>");
echo "<TD>" . $riga["id_utente"];
echo "<TD>" . $riga["nome_utente"];
echo "<TD>" . $riga["password_utente"];
echo "<TD>" . $riga["conta_pres"];
}
mysql_close();
?>
</body>
</html>
I checked the syntax (using a website) of the code and thare aren't problems,even because I copied this one by a book. I read that mysql_connect has been deprecated, so I replaced it with new mysqli_connect but the error still remains: white page. I tried to put 2 echo, one before the connecting function and one after that. Only the first echo is printed on the screen. I tried to type in the terminal sudo apt-get install php5-mysql but there is an error:
The "php5-mysql" packet has not run to install
Can someone help me, please?
First of all use mysqli instead of mysql.
I think I have found the problem. When you call mysqli_select_db, it expects 2 parameters and you only specified one. Even though you have set the $db database connection, you need to specify which database you want to select the database name from.
So mysqli_select_db($db, "scuola") should do the trick.
And at the bottom close the connection specifying which connection to close. In your case it is: mysqli_close($db);
<!DOCTYPE html>
<html>
<head><title> SQL & PHP </title></head>
<body>
<?php
$db = mysqli_connect("localhost", "root", "password")
or die ("Non riesco a creare la connessione");
mysqli_select_db($db, "scuola") // see this line
or die ("Non trovo il DB");
$sql = "SELECT id_utente, nome_utente, password_utente, conta_pres FROM utenti WHERE conta_pres <> 0";
$ris = mysql_query($sql) or die ("Query fallita!");
echo "<TABLE><TR><TH>ID utente <TH> Nome utente <TH>Password<TH>Contatore visite</TR>";
while ($riga= mysql_fetch_array($ris))
{
echo ("<TR>");
echo "<TD>" . $riga["id_utente"];
echo "<TD>" . $riga["nome_utente"];
echo "<TD>" . $riga["password_utente"];
echo "<TD>" . $riga["conta_pres"];
}
mysqli_close($db); // see this line
?>
</body>
</html>
I have the following code that allows me to upload a file to a database but I have cannot get that file to playback on my html page:
<!DOCTYPE html>
<html>
<head>
<link href="site.css" rel="stylesheet">
<title>A</title>
<meta http-equiv="content-type" content="text-html; charset=utf-8">
</head>
<body style="background-color:black">
<?php
define('DB_Name', 'gaufensr_abs3x');
define('DB_User', 'gaufensr_owner');
define('DB_Password', 'Mlee#0407');
define('DB_Host', 'localhost');
$link = mysql_connect(DB_Host, DB_User, DB_Password);
if (!$link) {
die('could not connect:' . mysql_error());
}
$db_selected = mysql_select_db(DB_Name, $link);
if (!#db_selected) {
die('can\t use' . DB_Name. ': ' . mysql_error());
}
echo 'CONNECTED SUCCESSFULLY';
$value = $_Post['submit'];
$sql = "INSERT INTO videos (video_name) VALUES ('$value')";
if (!mysql_query($sql)) {
die('ERROR: ' .mysql_error());
}
mysql_close();
?>
<?php
if (isset($_GET['id']))
{
$id = $_GET['id'];
$query = mysql_query("SELECT * FROM 'videos' WHERE id='$id'");
while($row = mysql_fetch_assoc($query))
{
$id = $row['id'];
$video_name = $row['video_name'];
}
echo "You are watching " .$video_name. "<br />";
echo "<embed src='$id' width='560' height='315'></embed>";
}
else
{
echo "Error!";
}
?>
</body>
</html>
When i upload a file I get the following error:CONNECTED SUCCESSFULLY Error!
I am just learning php and mysql; Any help would be great. Thanks in advance you guys.
Firstly, you're using the incorrect identifiers for your table, being regular single quotes.
FROM 'videos'
Those should be ticks or none at all.
FROM `videos`
Having used or die(mysql_error()) to mysql_query() would have signaled the syntax error.
Sidenote: Your present code is open to SQL injection. Use mysqli with prepared statements, or PDO with prepared statements, they're much safer.
Then this $_Post that should be in uppercase $_POST is a superglobal.
http://php.net/manual/en/language.variables.superglobals.php
Plus, you are closing your DB connection too early with mysql_close(); where you have it placed now.
Place it after your queries, at the end of your code. That could have adverse effects.
Your conditional statement if (isset($_GET['id'])){...} could also play a part in all this.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Error reporting should only be done in staging, and never production.
<?php
//error_reporting(E_ALL); ini_set('display_errors', '1');
$connection = mysql_connect("localhost", "root", "toor");
if (!$connection){
die("Database Connection Failed" . mysql_error());
}
$select_db = mysql_select_db('test');
if (!$select_db){
die("Database Selection Failed" . mysql_error());
}
session_start();
if(!isset($_SESSION['username'])){
header("Location: main.php");
}
echo "<a href='logout.php'>Logout</a>";
/*if (isset($_GET['id']){
$id = $_GET['id'];
$query = "SELECT title FROM news WHERE id=$id";
$title = mysql_query($query) or die(mysql_error());
$query = "SELECT body FROM news WHERE id=$id";
$body = mysql_query($query) or die(mysql_error());
echo "$title\n\n\n";
echo "$body\n\n";
}*/
?>
<html>
<body>
<p>
Login OK
</body>
</html>
I need to display the content of the fields title and body, however I'm getting a blank page (not even the link to logout.php is displayed). There is no error reported by error_reporting(E_ALL); ini_set('display_errors', '1');.
If I comment the if block, both the link to logout.php and the message "Login OK" are displayed.
What might be failing?
In the login.php I call news.php with:
if (isset($_SESSION['username'])){
header("Location: news.php?id=1");
}
edit
I'm noticing the call to news.php?id=1 returns an error 500.
You are using it in the wrong way
$query = "SELECT title, body FROM news WHERE id=$id";
$results = mysql_query($query);
while ($news = mysql_fetch_assoc($results)) {
echo $news["title"];
echo $news["body"];
}
the instruction mysql_query will give you a result set.
Then from results sets you have to fetch the single rows
with mysql_fetch_assoc ( or fetch_row or fetch_array, see the manual for the differencies )
Then with single result pulled you display data.
In your code i cannot see any db connection logic, there is no connection parameter passed to mysql_query function.
Error 500 means php is doing some bad error and fails to execute, anyway i would go to check the logs, the error is clearly written there and will save you headaches. /var/log/httpd/error_log generally on linux.
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?
I've a simple order-form on my website. If I click the submit-button the the form will send the data to my database. This works. But it does not show the success.php - it only shows the start.php again. So there must be a mistake. On my previous hoster it worked. But now I have a new one.
Here's my php-script (start.php):
<?php
$con = mysql_connect("localhost", "user", "pw") or die ("No connection to db possible");
mysql_select_db("db", $con) or die ("No connection to db possible");
mysql_query("SET NAMES 'utf8'");
if (isset($_POST['button']))
{
foreach ($_POST AS $key => $postvar)
$_POST[$key] = stripslashes($postvar);
$_POST['name'] = mysql_real_escape_string($_POST['name']);
$_POST['strasse'] = mysql_real_escape_string($_POST['strasse']);
$_POST['plz'] = mysql_real_escape_string($_POST['plz']);
$_POST['ort'] = mysql_real_escape_string($_POST['ort']);
$_POST['mail'] = mysql_real_escape_string($_POST['mail']);
$_POST['anzahl'] = mysql_real_escape_string($_POST['anzahl']);
$sql = "INSERT INTO `bestellungen` (`name`,`strasse`,`plz`,`ort`,`mail`,`anzahl`,`datetime`)
VALUES ('".$_POST['name']."', '".$_POST['strasse']."', '".$_POST['plz']."', '".$_POST['ort']."', '".$_POST['mail']."', '".$_POST['anzahl']."', '".date("Y-m-d H:i:s")."');";
$result = mysql_query($sql,$con);
if (!$result) echo mysql_error();
mysql_close($con);
?>
<?php Header("Location: success.php");
exit();
?>
<?php
} else { ?>
That won't work because header('Location: success.php') needs to happen before you output anything to the browser. You seem to have gaps before that is called.
$result = mysql_query($sql,$con);
if (!$result) echo mysql_error();
mysql_close($con);
// Now its time for the header!
header("Location: success.php");
exit();
You cannot have any output before the header() redirection.
Check your script for possible errors, warnings or notices, any of these will output text and the redirection will no happen.
So far, whenever I found this kind of problem; there must be two reasons I often do. Either I print any html code before the header function or I don't realize that my success.php also redirect to start.php.
Maybe you can check either of these two exist in your code.
Format it this way.
$result = mysql_query($sql,$con);
if (!$result) {
echo mysql_error();
} else {
Header("Location: success.php");
}
mysql_close($con);
?>