PHP MySqli query didn't work - php

I want to insert data to my DB, but the query didn't work. I was using this code in another page, but it work. And for this page it seems didn't work.
This my upload.php
<?php
include_once("connect.php");
//Fetching Values from URL
if (isset($_POST['submit'])) {
$nama_program=$_POST['nama_program'];
$deskripsi=$_POST['deskripsi'];
$code=$_POST['link_youtube'];
$link_youtube="<iframe width='420' height='315' src='https://www.youtube.com/embed/".$code."' frameborder='0' allowfullscreen></iframe>";
$link_twitter=$_POST['link_twitter'];
$rating=$_POST['rating'];
$image=$_POST['uploafimage'];
$target_dir = "images/";
$target_file = $target_dir . basename($_FILES["uploadimage"]["name"]);
$result=$mysqli->query("INSERT INTO program(nama, deskripsi, link_youtube, link_twitter, image, rating, slider, twtiter) VALUES('$nama_program','$deskripsi','$link_youtube','$link_twitter','$target_file','$rating', 0, 0)");
if($result === TRUE){
echo "Congrats Your data hase been saved";
} else{
echo"There is eror here".$result;
}
} else{
echo "Error";
}
?>
This is my form look like
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="text" class="form-control" id="nama_program" name="nama_program">
<textarea class="form-control textarea" name="deskripsi" id="deskripsi"></textarea>
<textarea class="form-control textarea" name="link_youtube" id="link_youtube"></textarea>
<textarea class="form-control textarea" name="link_twitter" id="link_twitter"></textarea>
<select name="rating" id="rating" class="form-control">
<option>Rating</option>
<option>1</option>
<option>2</option>
<option>3</option>
<input type="file" name="uploadimage" id="uploadimage">
<button type="submit" class="btn btn-info">
submit
</button>
</form>
What's wrong with mysqli ? I use this enctype="multipart/form-data" because i want to upload image, but first the query didn't work.
This is my connect.php
<?php
$host = "localhost";
$user = "*****";
$pass = "****";
$dbnm = "*******";
$mysqli = new mysqli($host, $user, $pass, $dbnm);
if($mysqli->connect_errno > 0){
die('Unable to connect to database [' . $mysqli->connect_error . ']');
}
?>

mysqli_query($yourcon,"INSERT INTO program(nama, deskripsi, link_youtube, link_twitter, image, rating, slider, twtiter) VALUES ('$nama_program','$deskripsi','$link_youtube','$link_twitter','$target_file','$rating', 0, 0)");
Give more Explanation about question and errors you getting for batter
solution.

Related

Have a Insert and a Edit button in the same form using PHP and SQL

I've been going at this for a couple of hours now (searching here and google) but nothing I find helped me to get this to work.
I'm trying to make one form and have a Insert INTO and UPDATE $table SET function in the same form, using buttons.
But whatever I try the Update doesn't copy the data from the form. INSERT INTO works. But when I try to edit the form, no data is copied.
HTML:
<form id="contact-form" method="post" action="cms_data.php" role="form">
<div class="col-sm-12">
<h2>id</h2>
<input name="id" type="text" placeholder="<?php echo $id;?>" value="1">
</div>
<div class="col-sm-12">
<h2>Omschrijving</h2>
<textarea name="omschrijving" type="text" style="height:220px;width:100%;resize:none;"><?php echo $omschrijving;?></textarea>
</div>
<div class="col-sm-12">
<h2>Datum</h2>
<input name="datum" type="text" value="<?php echo $datum;?>">
</div>
<div class="col-sm-12">
<h2>Tijd</h2>
<input name="tijd" type="text" value="<?php echo $tijd;?>">
</div>
<div class="col-sm-12">
<h2>Locatie</h2>
<input name="locatie" type="text" value="<?php echo $locatie;?>">
</div>
<div class="col-sm-12">
<h2>Dresscode</h2>
<input name="dresscode" type="text" value="<?php echo $dresscode;?>">
</div>
<div class="col-sm-12 text-right">
<input type="submit" class="btn btn-success btn-send" value="Versturen" id="sent" <?php // echo $_SESSION['disabled']; ?>>
Update
</div>
</form>
CMS_DATA.php
<?php session_start();?>
<?php
$servername = "localhost";
$username = "xxx";
$password = "xxx";
$dbname = "xxx";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
//echo '<div style="width:100%;background:green;color:#FFF;font-size:2rem;text-align:center;">Connected to '. $dbname. '</div>';
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$id = $_POST['id'];
$omschrijving = $_POST["omschrijving"];
$datum = $_POST["datum"];
$item = $_POST["tijd"];
$locatie = $_POST["locatie"];
$dresscode = $_POST["dresscode"];
$quote = iconv("UTF-8", "WINDOWS-1252//TRANSLIT");
$date = date('Y-m-d');
date_default_timezone_set("Europe/Amsterdam");
$time = date("h:i:sa");
$sql = "INSERT INTO $table (ID, Omschrijving, Datum, Tijd, Locatie, Dresscode )
VALUES ('" .$id."','" .$omschrijving."','".$datum."',' ".$item."','".$locatie."','".$dresscode."')";
if ($conn->query($sql) === TRUE) {
echo "";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
UPDATE-CMS.php
<?php session_start();?>
<?php
$servername = "localhost";
$username = "xxx";
$password = "xxx";
$dbname = "xxx";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
//echo '<div style="width:100%;background:green;color:#FFF;font-size:2rem;text-align:center;">Connected to '. $dbname. '</div>';
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$id = $_POST['id'];
$omschrijving = $_POST["omschrijving"];
$datum = $_POST["datum"];
$item = $_POST["tijd"];
$locatie = $_POST["locatie"];
$dresscode = $_POST["dresscode"];
$quote = iconv("UTF-8", "WINDOWS-1252//TRANSLIT");
$date = date('Y-m-d');
date_default_timezone_set("Europe/Amsterdam");
$time = date("h:i:sa");
$sql = "UPDATE $table SET
Omschrijving = '$omschrijving', Datum = '$datum', Tijd = '$item', Locatie = '$locatie', Dresscode = '$dresscode' WHERE ID = '1'";
if ($conn->query($sql) === TRUE) {
echo "Done";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Like I said, the INSERT INTO works fine. But no data (values) are copied when using the update. I just overrides ID 1 with empty rows... I hope someone can help me... thanks in advance.
You have defined action on your form action="cms_data.php", so your button that is responsible for submitting that form works correctly, but on the other hand you've defined another button (anchor tag), that only has href (hence points to another page), so if you click on it, you won't pass any arguments with it.
My suggestion here is, as I mentioned in comment below your question, to use two buttons, both with submit property, but then handle clicking on them via JavaScript.
When you capture submitment, you can dinamically change action on your form, so your data will be passed to desired script.
Handling multiple buttons in a form:
Process a Form Submit with Multiple Submit Buttons in Javascript
Manipulating form's action property:
How to use JavaScript to change the form action
Another suggestion would be that you use prepared statements in your query, so you wouldn't be vulnerable to SQL injections (from the comments section, I see you'll only be using this locally, but this is a good practice).
Using Mysqli prepared statements:
https://stackoverflow.com/a/24989090/5018750
Echo only prints value on the screen in your respective textbox and does not assign that value to your actual field.
Instead what you can do is start the session in the start of your contact form and store those fields in session variable.
When user selects UPDATE option he will get redirected to UPDATE-CMS.php page. In UPDATE-CMS.php you can retrieve your stored session variables and assign them to your actual variables. In this way you can carry forward your old as well as new values.
anchor just links the page it will not pass data
you are trying to have submit and update button in one form
solution:
in html5 button has formaction attribute .formaction specifies page data to be transferred .so that different button can have different action page
<form id="contact-form" method="post" action="cms_data.php" role="form">
<div class="col-sm-12">
<h2>id</h2>
<input name="id" type="text" placeholder="<?php echo $id;?>" value="1">
</div>
<div class="col-sm-12">
<h2>Omschrijving</h2>
<textarea name="omschrijving" type="text" style="height:220px;width:100%;resize:none;"><?php echo $omschrijving;?></textarea>
</div>
<div class="col-sm-12">
<h2>Datum</h2>
<input name="datum" type="text" value="<?php echo $datum;?>">
</div>
<div class="col-sm-12">
<h2>Tijd</h2>
<input name="tijd" type="text" value="<?php echo $tijd;?>">
</div>
<div class="col-sm-12">
<h2>Locatie</h2>
<input name="locatie" type="text" value="<?php echo $locatie;?>">
</div>
<div class="col-sm-12">
<h2>Dresscode</h2>
<input name="dresscode" type="text" value="<?php echo $dresscode;?>">
</div>
<div class="col-sm-12 text-right">
<buttin formaction="CMS-DATA.php" type="submit" class="btn btn-success btn-send" value="Versturen" id="sent" <?php // echo $_SESSION['disabled']; ?>>
<button formaction="UPDATE-CMS.php" >Update </button>
</div>
</form>

when saving text and images in the database undefined variable error occur.How to solve?

I am new to php. So some person, this question may be very childish.But still I can't solve this. I want to save image path in database and save user's other text inputs in a same table.But it gives this error **Notice: Undefined index: age in **.Can you please help me?
<?php
// Create database connection
$db = mysqli_connect("localhost", "root", "", "construction");
// Initialize message variable
$msg = "";
// If upload button is clicked ...
if (isset($_POST['upload'])) {
// Get image name
$image = $_FILES['image']['name'];
// Get text
$image_text = mysqli_real_escape_string($db, $_POST['image_text']);
$age = mysqli_real_escape_string($db, $_POST['age']);
// image file directory
$target = "uploads/".basename($image);
$sql = "INSERT INTO images (image_path, description,age) VALUES ('$image', '$image_text','$age')";
// execute query
mysqli_query($db, $sql);
if (move_uploaded_file($_FILES['image']['tmp_name'], $target)) {
$msg = "Image uploaded successfully";
}else{
$msg = "Failed to upload image";
}
}
?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form method="POST" action="imageUpload.php" enctype="multipart/form-data">
<input type="hidden" name="size" value="1000000">
<div>
<input type="file" name="image">
</div>
<div>
<textarea id="text" cols="40" rows="4" name="image_text" placeholder="Say something about this image..."></textarea>
<input type="text" name="age">
</div>
<div>
<button type="submit" name="upload">POST</button>
</div>
</form>
</div>
</body>
</html>

Cant Update SQL data using this code, checked code so many times

I wrote this code to update entry in my sql table, but i don't what is wrong.
Here is my form
<form action="" method="POST">
<center>
Alumni_ID :
<input type="text" name="valueh">
<br>
<input type="text" name="name" placeholder="name">
<input type="text" name="phone" placeholder="contact details">
<input type="text" name="details" placeholder="details">
<input type="text" name="address" placeholder="address">
<input type="submit" value="update data">
</center>
</form>
And this is php page,
<?php if (isset($_POST['submit'])) {
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "tssolutions";
$ab = $_POST['name'];
$bc = $_POST['phone'];
$cd = $_POST['details'];
$de = $_POST['address'];
$posted = $_POST['valueh'];
//create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
//check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//echo "connected successfully";
$sql = " UPDATE phone SET name='".$ab."', phone='".$bc."', details='".$cd."', address='".$de."' WHERE name = '".$posted."' ";
if(mysqli_query($conn, $sql)) {
echo "<hr>";
echo "<h3 class='w3-center' style='text-color:black'>Record Successfully Updated</h3>";
} else {
echo "<hr>";
echo "<h3 class='w3-center' style='text-color:black'>Error While Updating, Try Again</h3>";
}
mysqli_close($conn);
} ?>
Both the code are on same page Update.php, i wish to send alumni_id so that i can update that record where alumni_id = name in table phone, and then send new values of the row .
You forgot to name the submit button
Instead of
<input type="submit" value="update data">
Try this
<input type="submit" name="submit" value="update data">
To debug your code you can echo your SQL statement
echo $sql = "UPDATE phone SET name='".$ab."', phone='".$bc."', details='".$cd."', address='".$de."' WHERE name = '".$posted."';
You can then see if you have correct syntax and your values are sent correctly
try this code, maybe this helps
$sql = " UPDATE phone SET `name` ='$ab', `phone` ='$bc', `details` ='$cd', `address`='$de' WHERE `name` = '$posted' ";

Insert images into a database

Im trying to upload an image to a mysql database, but when I upload the image I receive the message of confirmation, but when i check my database the image row is empty, what am I doing wrong?
<?php include "connection.php"; ?>
<?php
$n=$_POST["num"];
$t=$_POST["texto"];
$i=$_POST["imagem"];
$image = addslashes(file_get_contents($_FILE['$i']['tmp_name']));
if ($connect->connect_error){
die("Connection failed: " . $connect->connect_error);
}
$sql = "UPDATE servicos SET texto='$t', imagem='{$image}' where nmr=$n" ;
if ($connect->query($sql) === TRUE) {
echo "informação atualizada";
} else {
echo "Error: " . $sql . "<br>" . $connect->error;
}
$connect->close();
?>
<html>
<body>
<div class="formulario" style="width: 100%; height: 100%;">
<form enctype="multipart/form-data" name="form1" target="apresenta" method="post" action="menu2.php" style="position:absolute; top:70;left:10
border:thin; border-style:none;">
<label> Atualizar dados </label><br>
Numero: <input type="text" name="num" value=""><br>
Texto: <input type="text" name="texto" value=""><br>
Imagem: <input type="file" name="imagem" value=""><br>
<input type="submit" name="submit" value="enviar">
<input type="reset" value="limpar">
</form>
</div>
</body>
</html>
Besides all the comments stating "You shouldn't store files in tables because...", this is what works (with PHP 7):
<?php
if(isset($_POST['submit'])) {
var_dump($_FILES);
$dbh = new PDO("mysql:host=127.0.0.1;dbname=test", "root", "");
$stm = $dbh->prepare("INSERT INTO test_img (cont) VALUES (?)");
$stm->execute(array(file_get_contents($_FILES['fileinput']['tmp_name'])));
}
?>
<form method="post" enctype="multipart/form-data">
File: <input type="file" name="fileinput"><br>
<button name="submit">Upload</button>
</form>
Possible error sources:
$connect->query($sql) === TRUE should be $connect->query($sql) !== false
The entry you want to UPDATE does not exist
imagem='{$image}' is a rather "hacky" way do insert variables, use concatenation: $sql = "UPDATE servicos SET texto='".$t."', imagem='".$image."' where nmr=".$n;
Hope this helps.

Bootstrap form submission not able to use $_POST data

My code in not entering any data from the boostrap form into MySQL table, if I hard code the values instead of using $login and $score, the data shows up in my table.
Here's my form (index.php)
<form action="insert.php" method="post">
<div class="input-group">
<span class="input-group-addon">NA</span>
<input type="text" id = "login" name = "login" class="form-control" placeholder="Name" />
<span class="input-group-addon">-</span>
<input type="int" id = "score" name = "score" class="form-control" placeholder="Score: (0-10)"/>
<span class="input-group-btn">
<a class="btn btn-success" type="submit" id="submit" href = "/insert.php">Rate!</a>
</span>
</form>
and my php (insert.php)
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "data";
$login=$_POST['login'];
$score=$_POST['score'];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
print("name data: $login");
$sql = "INSERT INTO table (name, score)
VALUES ('$login', '$score')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
both name and score are empty in each addition of my data.
edit: fixed, thank you
<button id="submit" name="submit" class="btn btn-lg btn-success">Rate</button>
you have to use button for submit instead of using a href link
try this
<button id="submit" type="submit" name="submit" class="btn btn-lg btn-success">Rate!</button>
Or you can use
<input type="submit" id="submit" name="submit" class="btn btn-lg btn-success" value ="Rate">

Categories