Insert Images at Database PHPMYSQL - php

So im trying to upload/host images at my database but for some reason i cant archieve it.
Insert the Image:
<form method="post" action="actions/dados_insert.php" enctype="multipart/form-data">
<input type="file" name="imagem" />
</form>
dados_insert.php
<?php
if ( ! empty( $_POST ) ) {
$mysqli = new mysqli( 'localhost', 'root', '', 'valsil' );
$mysqli->set_charset("utf8");
if ( $mysqli->connect_error ) {
die( 'Connect Error: ' . $mysqli->connect_errno . ': ' . $mysqli->connect_error );
}
$sql = "INSERT INTO dados ( id_proposta, quantidade, posicao, unitario, titulo, `desc`, imagem ) VALUES ( '{$mysqli->real_escape_string($_POST['id_proposta'])}', '{$mysqli->real_escape_string($_POST['quantidade'])}', '{$mysqli->real_escape_string($_POST['posicao'])}', '{$mysqli->real_escape_string($_POST['unitario'])}', '{$mysqli->real_escape_string($_POST['titulo'])}', '{$mysqli->real_escape_string($_POST['desc'])}', '{$mysqli->real_escape_string($_FILES['imagem'])}' )";
$insert = $mysqli->query($sql);
if ( $insert ) {
header("Location: ". $_SERVER['HTTP_REFERER']);
exit();
} else {
die("Error: {$mysqli->errno} : {$mysqli->error}");
}
$mysqli->close();
}
?>
Update the Image:
<form method="post" action="actions/dados_update.php?id=<?php echo $row['id']; ?>" enctype="multipart/form-data">
<input type="file" name="imagem" />
</form>
dados_update.php
<?php
if ( ! empty( $_POST ) ) {
$mysqli = new mysqli( 'localhost', 'root', '', 'valsil' );
$mysqli->set_charset("utf8");
$id = $_GET['id'];
if ( $mysqli->connect_error ) {
die( 'Connect Error: ' . $mysqli->connect_errno . ': ' . $mysqli->connect_error );
}
$sql = "UPDATE dados SET quantidade = '{$mysqli->real_escape_string($_POST['quantidade'])}', posicao = '{$mysqli->real_escape_string($_POST['posicao'])}', unitario = '{$mysqli->real_escape_string($_POST['unitario'])}', titulo = '{$mysqli->real_escape_string($_POST['titulo'])}', `desc` = '{$mysqli->real_escape_string($_POST['desc'])}', imagem = '{$mysqli->real_escape_string($_FILES['imagem'])}' WHERE id =".$id;
$insert = $mysqli->query($sql);
if ( $insert ) {
header("Location: ". $_SERVER['HTTP_REFERER']);
exit();
} else {
die("Error: {$mysqli->errno} : {$mysqli->error}");
}
$mysqli->close();
}
?>
I would appreciate any help, theres something missing for sure, first time trying to upload images and already readed tutorials but still couldnt get the answer.
Cumps.

Related

How I See my Result in Select from Where MYSQL using PHP?

I have this code, i try to call my data from table database mysql , but didn't see any result. always go to else , not go to the process. what would i do?
<?php
require('connectDB.php');
$nama = $_GET['nama'];
echo $nama;
$query = "SELECT * FROM pesan
WHERE nama = '%" . mysqli_real_escape_string($connection, $nama) . "%'
";
$results = mysqli_query($connection, $query);
$baris = mysqli_num_rows($results);
if (!$results) {
die('Invalid query: ' . mysql_error());
}
if ( $baris > 0) {
while($row = mysqli_fetch_assoc($results)) {
?>
<h3>Nama Mobil : <?php echo $row['mobil'] ?></h3>
<h3>ID Pembelian : <?php echo $row['id']; ?></h3>
<h3>Nama anda : <?php echo $row['nama']; ?></h3>
<h3>Alamat : <?php echo $row['alamat']; ?></h3>
<h3>Tanggal Masuk : <?php echo $row['tgl_masuk']; ?></h3>
<?php
}
}else{
echo "error";
}
?>
What wrong with my code?
Thanks!
im sorry , this is my ConnectDB.php , i include in my html.
<?php
$connection = mysqli_connect('localhost', 'root', '', 'dealermobil');
if (!$connection){
die("Database Connection Failed" . mysqli_error());
}
// $db = new PDO ('mysql:host=localhost;dbname=db_login;charset=utf8mb4','root','');
?>
Your connection check and result check is incorrect.
$connection = mysqli_connect('localhost', 'root', '', 'dealermobil');
if (!$connection){
die("Database Connection Failed" . mysqli_connect_error());
}
Also
$results = mysqli_query($connection, $query);
$baris = mysqli_num_rows($results);
if (!$results) {
die('Invalid query: ' . mysqli_error($connection));
}
use this you are using = it should be LIKE when you are trying to search a field in database.
$query = "SELECT * FROM `pesan` WHERE `nama` LIKE '%". mysqli_real_escape_string($connection, $nama) ."%'";

How to use Insert query in PHP code

I do not understand what is going wrong with code. The result is get is "connected successfully success Query failed". I tried few combinations and I get the same result. Please help me in solving this. Thanks in advance.
<?php
$link = mysql_connect('localhost', 'root1', '')
or die('Could not connect: ' . mysql_error());
if ($link) {
echo 'connected successfully';
}
$l = mysql_select_db('vtflix', $link) or die ('Could not select the database');
if ($l) {
echo ' success';
}
/*$varCNAME = 'John';
$varCONTENT = '4';
$varVID = '1';*/
$sql = "INSERT INTO mpaa(C_Name, ContentRating, V_ID) VALUES ('Jon', 4, 3)";
mysql_query($sql, $link) or die("Query failed");
$que = "SELECT * FROM mpaa";
$query = mysql_query($que, $link);
if (!$query) {
echo 'query failed';
}
while ($sqlrow = mysql_fetch_array($query, MYSQL_ASSOC)) {
$row = $sqlrow['C_Name'];
$nrow = $sqlrow['Content Rating'];
$mrow = $sqlrow['V_ID'];
echo "<br>" . $row . " " . $nrow . " " . $mrow . "<br>";
}
mysql_close($link);
?>
1.Don't use mysql_* library (deprecated from php5 onward + removed from php7) .Use mysqli_* OR PDO.
2.An example of mysqli_*(with your code)is given below:-
<?php
error_reporting(E_ALL); // check all type of error
ini_set('display_errors',1); // display those errors
$link = mysqli_connect('localhost', 'root1', '','vtflix');
if($link){
echo 'connected successfully';
$sql= "INSERT INTO mpaa(C_Name,ContentRating,V_ID) VALUES ('Jon', 4, 3)";
if(mysqli_query($link,$sql)){
$query = "SELECT * FROM mpaa";
$res = mysqli_query($link,$query);
if($res){
while($sqlrow=mysqli_fetch_assoc($query))
{
$row= $sqlrow['C_Name'];
$nrow= $sqlrow['Content Rating'];
$mrow= $sqlrow['V_ID'];
echo "<br>".$row." ".$nrow." ".$mrow."<br>";
}
mysqli_close($link);
}else{
echo die('Query error: ' . mysqli_error($link));
}
}else{
echo die('Query error: ' . mysqli_error($link));
}
}else{
echo die('Could not connect: ' . mysqli_connect_error());
}
?>
Note:- To check php version (either on localhost or on live server) create a file with name phpInfo.php, and just write one line code in that file:-
<?php
phpinfo();
?>
Now run this file and you will get the current php version.
Like this:- https://eval.in/684551
Here it seems that you are using deprecated API of mysql_* .
1) Check your PHP version
<?php phpinfo();exit;//check version ?>
2) avoid the usage of mysql use mysqli or PDO
3) change your db connection string with this :
new Mysqlidb($hostname, $username, $pwd, $dbname);
example with you code
<?php
$link = mysqli_connect('localhost', 'root1', '','vtflix');
if($link){
echo 'connected successfully';
$sql= "INSERT INTO mpaa(C_Name,ContentRating,V_ID) VALUES ('Jon', 4, 3)";
if(mysqli_query($link,$sql)){
$query = "SELECT * FROM mpaa";
$res = mysqli_query($link,$query);
if($res){
while($sqlrow=mysqli_fetch_assoc($query))
{
$row= $sqlrow['C_Name'];
$nrow= $sqlrow['Content Rating'];
$mrow= $sqlrow['V_ID'];
echo "<br>".$row." ".$nrow." ".$mrow."<br>";
}
mysqli_close($link);
}else{
echo die('Query error: ' . mysqli_error($link));
}
}else{
echo die('Query error: ' . mysqli_error($link));
}
}else{
echo die('Could not connect: ' . mysqli_connect_error());
}
?>

error in image_address and name insertion in mysql

i use this code for insert data in mysql but it directly shows error
" Could not enter data: "......
else
{
$image=$_FILES['img']['name'];
$tmp_name=$_FILES['img']['tmp_name'];
$path= "/var/www/html/uploads/".$image;
if(move_uploaded_file($name,$path))
{
$sql = "INSERT INTO form1 ". "(fname,lname,username,password,age,email,branch,college,
gender,image_p,) ". "VALUES('$fname','$lname','$username','$password','$age','$mail','$branch','$college','$gender','$image')";
$retval = mysql_query( $sql, $conn );
}
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
else
{
echo "Entered data successfully\n"."\n ";
echo "you are now a registered user.";
mysql_close($conn);
}
$sql = "INSERT INTO form1 (fname,lname,username,password,age,email,branch,college,
gender,image_p) VALUES ('".$fname."','".$lname."','".$username."','".$password."','".$age."','".$mail."','".$branch."','".$college."','".$gender."','".$image."')";
$retval = mysql_query( $sql, $conn );
$image=$_FILES['img']['name'];
$tmp_name=$_FILES['img']['tmp_name'];
$path= "/var/www/html/uploads/".$image;
move_uploaded_file($name,$path);
if(! $retval ){
die('Could not enter data: ' . mysql_error());
}else{
echo "Entered data successfully\n"."\n ";
echo "you are now a registered user.";
mysql_close($conn);
}

How to get notification when insert new value in db?

Hi i am inserting value in data base in php i want that when i insert value in database then my div color should be change
insert.php
include('conn.php');
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$id=2;
//$sql="insert into messages (message,number,service) values ('dd',".$urlstring.",'ds')";
$sql = 'INSERT INTO messages '.
'(message,number,service) '.
'VALUES ( "'.$message.'", "'.$urlstring.'", "'.$service.'" )';
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
echo ("Records affcted: ". mysql_affected_rows());
//echo "Entered data successfully\n";
mysql_close($conn);
index.php
<div id="div1" style="height=200px;width=300px;">
</div>
here i want when insert.php execute then div section should change color in another file
How can i achieve this
Any help will be appreciated
You can use timer on javascript and create a ajax function to retrieve all inserted data on the database.
try this:
include('conn.php');
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$id=2;
//$sql="insert into messages (message,number,service) values ('dd',".$urlstring.",'ds')";
$sql = 'INSERT INTO messages '.
'(message,number,service) '.
'VALUES ( "'.$message.'", "'.$urlstring.'", "'.$service.'" )';
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
echo ("Records affcted: ". mysql_affected_rows());
//echo "Entered data successfully\n";
?>
<style>
#div1{
backgroud-color="yourcolor";
}
</style>
<?php
mysql_close($conn);
ah i see.
maybe this can help you: http://www.barelyfitz.com/projects/csscolor/?

Need help inserting into MySQL database table using PDO

The database table only contains the four fields that the query is attempting to insert into. For some reason I get the error: Query failed: SQLSTATE[HY093]: Invalid parameter number: parameter was not defined.
I have troubleshot by echoing the output of the foreach loops and it always returns four items, I'm not sure what parameter isn't defined. I have also played around with including the field names in the $sql string as well as not including them. Same results either way. Please help if you can.
<?php
class DB {
private $_conn;
public function openDB() {
$dsn = "mysql:host=localhost;dbname=news";
$username = "root";
$password = "password";
try {
$this->_conn = new PDO( $dsn, $username, $password );
$this->_conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
} catch ( PDOException $e ) {
echo "Connection failed: " . $e->getMessage();
}
}
public function closeDB() {
$this->_conn = null;
}
public function selectData( $myQuery ) {
$rows = $this->_conn->query( $myQuery );
foreach ( $rows as $row ) {
echo "Index: " . $row['id'] . "<br />";
echo "Title: " . $row['title'] . "<br />";
}
}
public function insertData( $tableName ) {
$q = $this->_conn->prepare("DESCRIBE " . $tableName);
$q->execute();
$getFields = $q->fetchAll(PDO::FETCH_COLUMN);
$dbFieldCount = count( $getFields );
$implodedFields = implode( ", :", $getFields );
//$sql = "INSERT INTO " . $tableName . " ( " . implode( ", ", $getFields ) . " ) VALUES ( :" . $implodedFields . " )";
$sql = "INSERT INTO " . $tableName . " VALUES ( :" . $implodedFields . " )";
echo "$sql<br />";
try {
$insert = $this->_conn->prepare( $sql );
foreach ( $getFields as $dbKey => $dbValue ) {
foreach( $_POST as $formKey => $formValue ) {
if ( $dbValue == 'id' ) {
$insert->bindValue( '\":' . $dbValue . '\"', null, PDO::PARAM_INT );
echo "$dbValue<br />";
break;
} else if ( is_int( $formValue ) && $dbValue == $formKey ) {
$insert->bindValue( '\":' . $dbValue . '\"', $formValue, PDO::PARAM_INT );
echo "$formValue<br />";
break;
} else if ( is_string( $formValue ) && $dbValue == $formKey ) {
$insert->bindValue( '\":' . $dbValue . '\"', $formValue, PDO::PARAM_STR );
echo "$formValue<br />";
break;
}
}
}
$insert->execute();
} catch ( PDOException $e ) {
echo "Query failed: " . $e->getMessage();
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
</head>
<body>
<?php
if ($_POST) {
$conn = new DB();
$conn->openDB();
$conn->insertData( 'login' );
$conn->closeDB();
}
?>
<form action="#" method="POST" name="register">
<label for="username">Username</label><br />
<input type="text" id="username" name="username"><br />
<label for="password">Password</label><br />
<input type="password" id="password" name="password"><br />
<label for="email">Email Address</label><br />
<input type="text" id="email" name="email"><br />
<input type="submit" value="Submit" />
</form>
</body>
</html>
$sql = "INSERT INTO " . $tableName . " VALUES ( :" . $implodedFields . " )";
Here you're adding all columns into your SQL statement, but later you only add values that are sent when the form is submitted. It's possible that you have columns in your database that aren't in the form, so you're coming up with a statement like:
INSERT INTO someTable VALUES (:id, :value1, :value2)
And then you only bind :id and :value1, leaving MySQL confused about what :value2 is supposed to be.

Categories