PHP posting <a href> causes error on insert - php

I am writing a php file that takes values from a form and posts them to a mysql database. One of the table fields is a button link to a video that will play when clicked. It works great if I go into the database and manually add the link. However my PHP insert causes an error. Please have a look at this code:
$fileName = "video_".$id.".html";
$link = "<button class=\"count\">Watch Video</button>";
$con=mysqli_connect("localhost","videomanager","password","my_database");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO video_list (date, title, description, link) VALUES('$_POST[date]','".mysqli_real_escape_string($_POST['sermon'])."','".mysqli_real_escape_string($_POST['description'])."','$link' )";
if (!mysqli_query($sql,$con))
{
die('Error: ' . mysqli_error());
}
echo "This video has been successfully added to the video database.";
mysqli_close($con);
If I look at $link by doing something like: echo $link; die(); it produces a page with the button and the code in the button looks good. Is it how I am trying to insert it? Thanks for your help!

you have a lot of errors
<?php
$fileName = "video_".$id.".html";
$link = "<button class=\"count\">Watch Video</button>";
$con = mysqli_connect("localhost","videomanager","password","my_database");
// Check connection
if ( mysqli_connect_errno() )
die('Failed to connect to MySQL: ' . mysqli_connect_error() );
// Check param is set
if( !isset($_POST['date'], $_POST['sermon'], $_POST['description']) )
die('Param Error');
// SQL Request
$sql = sprintf("INSERT INTO video_list (date, title, description, link) VALUES('%s','%s','%s','%s')",
mysqli_real_escape_string($con, $_POST['date']),
mysqli_real_escape_string($con, $_POST['sermon']),
mysqli_real_escape_string($con, $_POST['description']),
mysqli_real_escape_string($con, $link)
);
// SQL execute
$result = mysqli_query($con, $sql) or die('Error: ' . mysqli_error($con));
// Free result
mysqli_free_result($result);
// Close connection
mysqli_close($con);
echo "This video has been successfully added to the Kim Watt videos.";

Related

POST request not sending string to the database

I want to be able to read the raw data from the URL path. The URL will look like:
https://newtest.000webhostapp.com/db.php?datainurl
The db.php is:
<?php
$postdata = file_get_contents("php://input");
$conn = new mysqli('localhost','2541','yhte','tg543');
// Check connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
$sql = "insert into cloud set rfid='.$postdata'";
if ($conn->query($sql) === TRUE)
{
echo "New record created successfully";
}
else
{
echo "Error: " . $sql . "<br>" . $conn->error;
}
?>
When I press enter in the URL the webpage echos: New record created successfully. I see the id in the database but the contents is not shown in the database.
Why the "datainurl" in the URL is not showing in the database?
The query string is available through $_SERVER['QUERY_STRING'].
php://input contains the request body.

Failed to query daabaseNo database selected

i am getting error no database is selected can anybody correct the code.
I am trying to learn php and mysql. So i tried making a database using
phpmyadmin and connect it with my php. Here is a simple example where I try to see if the database is working.
<?php
//Get values passe from form in donateform.html.
$link;
$Name = $_POST['Name'];
$Mobile = $_POST['Mobile'];
$Email = $_POST['Email'];
$Donating =isset($_POST['Donating']);
$Address = isset($_POST['Address']);
//To prevent mysql injection
$Name = stripcslashes($Name);
$Mobile = stripcslashes($Mobile);
$Email = stripcslashes($Email);
$Donating = stripcslashes($Donating);
$Address = stripcslashes($Address);
//connect to the server and select database.
$link=mysqli_connect("localhost", "gooddeeds", "");
mysqli_select_db($link,"donaters");
$Name = mysqli_real_escape_string($link,$Name);
$Mobile = mysqli_real_escape_string($link,$Mobile);
$Email = mysqli_real_escape_string($link,$Email);
$Donating = mysqli_real_escape_string($link,$Donating);
$Address = mysqli_real_escape_string($link,$Address);
//Query the database for user
$result =mysqli_query($link,"INSERT INTO donaters (Name, Mobile, Email, Donating, Address) VALUES ('$Name', '$Mobile', '$Email', '$Donating', '$Address')")
or die("Failed to query daabase".mysqli_error($link));
if(mysqli_query($result)){
echo "Records inserted successfully.";
} else{
echo "ERROR: Could not able to execute $sql. ".mysqli_error($link);
}
?>
and i get
Database query failed::: No database selected
which means this part of code
//connect to the server and select database.
$link=mysqli_connect("localhost", "gooddeeds", "");
mysqli_select_db($link,"donaters");
is not working (i put a different number of these ":" in each if. Any help would be appreciated! Thank you!
You can try with following as databasename.tablename (gooddeeds.donaters)
INSERT INTO gooddeeds.donaters (Name, Mobile, Email, Donating, Address) VALUES ('$Name', '$Mobile', '$Email', '$Donating', '$Address')
This is by the first example in the php documentation. Try the the conditional to check connection.
$link = mysqli_connect("127.0.0.1", "my_user", "my_password", "my_db");
if (!$link) {
echo "Error: Unable to connect to MySQL." . PHP_EOL;
echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
exit;
}

How to resolve echo error:Error: Duplicate entry in home header

I keep getting this error displayed in a new page
Error: Duplicate entry 'company' for key 'cname'
how can i display this in a new header
Heres my code:
$con=mysqli_connect("localhost","root","password","mydb");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO profile (cname, cobusiness, cphone,crep,cdescription)
VALUES
('$_POST[cname]','$_POST[cobusiness]','$_POST[cphone]','$_POST[crep]','$_POST[cdescription]')";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
header("Location: home.php?error");
} else {
header("Location: home.php?success");
exit;
}
mysqli_close($con);
I have added a trigger in mysql to check for duplicate entries and just need to figure out how to prevent this duplicate entry error display in a new page by default.This way i can display it in a header on the current page like i have already done with the other headers in the code.
With valuable assistance from Jean-maxime Bouloc
This is the solution:
Insert.php
$sql = "INSERT INTO profile (cname, cobusiness, cphone,crep,cdescription)
VALUES
('$_POST[cname]','$_POST[cobusiness]','$_POST[cphone]','$_POST[crep]','$_POST[cdescription]')";
if (!mysqli_query($con,$sql)) {
header("Location: home.php?error");
}
else {
header("Location: home.php?success");
exit;
}
mysqli_close($con);

How to display an image stored in Mysql database with special date not by id (php)

I am trying to display an image uploaded to my "upload" table in MySql. I've been reading a lot on how to do this but no luck.
"news_content" table is for uploading NEWS content to Mysql and has 6 columns: id,title, description, content_text, date, time
and "upload" table has 5 columns: id, name, size, image, date
In "news_content" table I upload the date and the time columns separately but the date column in "upload" table is a string concatenated with both date and time. For example if in "news_content" table the date is 2/3/2016 and the time is 5:30, in "upload" table the date is going to be 2/3/20165:30. I organized it that way in order to retrieve the image by its specific date and time that the related post uploaded.
I upload the image in news.php page with this following code:
news.php :
// Create connection
$connection = mysql_connect("localhost","root","p206405az");
// Check connection
if (!$connection) {
die("Connection failed: " . mysql_error());
}
//select a database to use
$db_select = mysql_select_db( "news" , $connection) ;
if (!$db_select) { die("Selection faild:" . mysql_error()) ;
}
//uploading the content of news and date and time
if(isset($_POST["submit"])){
$title = $_POST["title"] ;
$description = $_POST["description"] ;
$content_text = $_POST["content_text"] ;
$date = $_POST["date"] ;
$time = $_POST["time"] ;
//perform mysql query
$result = mysql_query("INSERT INTO news_content (title, description, content_text, date, time)
VALUES ('$title', '$description', '$content_text' ,'$date' , '$time' )") ;
if (!$result) {
die("Insert failed: " . mysql_error());
$submitMessage = "Problem with updating the post, please try again" ;
} else if ($result){
$submitMessage = "Your post succsessfully updated" ;
}
}
// uploading the image
if(isset($_POST['submit']) && $_FILES['image']['size'] > 0)
{
$fileName = $_FILES['image']['name'];
$tmpName = $_FILES['image']['tmp_name'];
$fileSize = $_FILES['image']['size'];
$fileType = $_FILES['image']['type'];
$filedate = "$date" . "$time" ;
$fp = fopen($tmpName, 'r');
$content2 = fread($fp, filesize($tmpName));
$content3 = addslashes($content2);
fclose($fp);
if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
}
$query = "INSERT INTO upload (name, size, type, image, date ) ".
"VALUES ('$fileName', '$fileSize', '$fileType', '$content3', '$filedate')";
mysql_query($query) or die('Error2, query failed');
}
And I want to retrieve that image by getImage.php page to use it as source page later by this following code but it seems it can't retrieve the blob data:
P.S. The image is successfully uploaded but I can't retrieve it with specific date that I Posted lately
getImage.php :
// Create connection
$connection = mysql_connect("localhost","root","p206405az");
// Check connection
if (!$connection) {
die("Connection failed: " . mysql_error());
}
//select a database to use
$db_select = mysql_select_db( "news" , $connection) ;
if (!$db_select) { die("Selection faild:" . mysql_error()) ;
}
//perform mysql query
$result = mysql_query("SELECT * FROM news_content" , $connection);
if (!$result) {
die("read failed: " . mysql_error());
}
//useing returned data
while ($content = mysql_fetch_array($result)){
$date = $content["date"];
$time = $content["time"] ;
}
$filedate = "$date" . "$time" ;
$result2 = mysql_query("SELECT image FROM upload WHERE date='$filedate'" , $connection);
if (!$result2) {
die("read failed: " . mysql_error());
};
$row = mysql_fetch_assoc($result2);
mysql_close($connection);
header("Content-type: image/jpeg");
echo $row['image'];
And I want to display the image in index.php page with this following HTML code:
index.php :
<img src="getImage.php?date=<?php echo $filedate ; ?>" width="175" height="200" />
How can I retrieve that data in getImage.php page and then use that page az source page to display the image in index.php page?
Any help would be appreciated.
cant figure out the error unless php throws an error. but i would save the images as files instead of db and keep its name if news table's row, unless there are multiple images per news.
in case of multimple image per news, i would just match the image id to news id.
schema for news.db
id, title, description, content_text, date, time
schema for upload.db:
id, image, newsid
my image html link would have been:
<img src="getImage.php?id=<?php echo $newsid; ?>" width="175" height="200" />
and then my getimage.php would have been like this:
$connection = mysql_connect("localhost","root","p206405az");
if (!$connection) {
die("Connection failed: " . mysql_error());
}
$db_select = mysql_select_db( "images" , $connection) ;
if (!$db_select) {
die("Selection faild:" . mysql_error()) ;
}
$id=$_GET["id"];
$result = mysql_query("SELECT image FROM upload WHERE newsid='$id' LIMIT 1" , $connection);
if (!$result) {
die("read failed: " . mysql_error());
};
$row = mysql_fetch_assoc($result);
mysql_close($connection);
header("Content-type: image/jpeg");
print $row['image'];
To show errors:
add error_reporting(E_ALL); ini_set('display_errors', '1'); at top of your page;
temporarily comment the header line: header("Content-type: image/jpeg");;
retrieve image directly from browser address bar (see image below);
If you obtain a “500 Server Error” check your Apache error log (compile errors are not displayed even with error_reporting enabled);

Unable to Store Base64 Data in MySql Database

I am trying to store an Base64 string to my MySql database using PHP. Here is my code.
<?PHP
//Store Image
$photoData = $_POST['PhotoData'];
//Database connection details
$db_url = "192.168.1.140";
$db_user_name = "easyblogadmin";
$db_password = "admin";
$db_name = "easyblog";
$con = mysqli_connect($db_url, $db_user_name, $db_password);
$sql = "insert into temptable (photodata) values('$photoData')";
if(mysqli_connect_errno()){
echo "Failed to Connect Database";
echo mysqli_connect_errno();
die();
} else {
//Connecting to Application Database
$db_selected = mysqli_select_db($con, $db_name);
if(!$db_selected){
echo "Failed to Connect Application Database";
die();
} else {
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
mysqli_close($con);
echo "Successfully Added photo".strlen($photoData);
}
}?>
Here the $photoData is my Base64 encoded string and I am storing this in my DB. When i am trying to retrieve this data from DB some data in my string is missing. I don't understand why this is happening. Can any one help me out.
regards.
chnage the sql query as below mentioned
$sql = "insert into databasename.temptable (photodata) values('$photoData')";
also please make sure if the encoded value has any single quotes,if it is then replace the data as mentioned below .
$photoData =str_replace("'","\'",$_POST['PhotoData']);

Categories