i'm trying to use a get statement in a variable to add data to a data base, when i try to do this nothing is added under folder however if i add plain text it is added. (i'm trying to add to the folder section)
My entire html document is provided below:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="newfile.css">
<title>Folder</title>
</head>
<body>
<?php
include_once 'dbh.php';
echo $_GET["data"];
if(isset($_GET["data"])) {
$location = $_GET["data"];
$sql = "SELECT * FROM posts WHERE folder LIKE '%$location%'";
$result = mysqli_query($conn, $sql);
$queryResult = mysqli_num_rows($result);
if($queryResult > 0) {
while ($row = mysqli_fetch_assoc($result))
{
echo $row['content'];
}
} else {
echo "There are no results matching your search!";
}
}
?>
<?php
$uploadpath = 'postimages/'; // directory to store the uploaded files
$max_size = 3116718; // maximum file size, in KiloBytes
$alwidth = 100000; // maximum allowed width, in pixeli
$alheight = 100000; // maximum allowed height, in pixeli
$allowtype = array('bmp', 'gif', 'jpeg', 'jpg', 'jpe', 'png', 'docx', 'psd', 'pdf', 'pptx', 'html', 'php', 'css', 'js', 'mp4', 'mp3'); // allowed extensions
if(isset($_FILES['fileup'])) {
$uploadpath = $uploadpath . basename( $_FILES['fileup']['name']);
$name = basename( $_FILES['fileup']['name']);
$type = end(explode('.', strtolower($_FILES['fileup']['name'])));
list($width, $height) = getimagesize($_FILES['fileup']['tmp_name']); // gets image width and height
$err = '';
// Checks if the file has allowed type, size, width and height (for images)
if(!in_array($type, $allowtype)) $err .= 'The file <b>'. $_FILES['fileup']['name']. '</b> not has the allowed extension type.';
if($_FILES['fileup']['size'] > $max_size*900000) $err .= '<br/>Maximum file size must be: '. $max_size. ' KB';
if(isset($width) && isset($height) && ($width >= $alwidth || $height >= $alheight)) $err .= '<br/>The maximum Width x Height must be: '. $alwidth. ' x
'. $alheight;
// If no errors, upload the image, else, output the errors
if($err == '') {
if(move_uploaded_file($_FILES['fileup']['tmp_name'], $uploadpath)) {
$content = $name;
$realfiledest = $uploadpath;
$username = 'user';
$folder = $_GET['data'];
$sql = "INSERT INTO posts (content, img, folder, date) VALUES ('$content', '$realfiledest', '$folder', NOW());";
$result = mysqli_query($conn, $sql);
if($result !== false) {
header("Location: fold.php?data=Math");
}else{
echo "fail";
}
}
else echo '<b>Unable to upload the file.</b>';
}
else echo $err;
}
?>
<div class="upform">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST" enctype="multipart/form-data">
<div class="image-upload">
<label for="file-input">
<img src="add-file.png" />
</label>
<input id="file-input" type="file" name="fileup"/>
</div>
<input class="noshow" type="text" id="wow" placeholder="<?php echo $_GET['data']; ?>" name='name'>
<input type="submit" id="submit" name='submit' value="U P L O A D" />
</form>
</div>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(
function(){
$('input:file').change(
function(){
if ($(this).val()) {
$("#submit").show();
// or, as has been pointed out elsewhere:
// $('input:submit').removeAttr('disabled');
}
}
)
});
</script>
</body>
</html>
url= http://localhost/smart%20assist/fold.php?data=Math
Any help would be awesome, Thanks
So, if you doing file uploading you are using post method in your form with multi-part, right.
now, if you want to send something with your url as query params, then you have to use $_REQUEST. In your case,
if(move_uploaded_file($_FILES['fileup']['tmp_name'], $uploadpath)) {
$content = $name;
$realfiledest = $uploadpath;
$username = 'user';
$folder = $_REQUEST['data'];
$sql = "INSERT INTO posts (content, img, folder, date) VALUES ('$content', '$realfiledest', '$folder', NOW());";
$result = mysqli_query($conn, $sql);
If you facing the same problem, I need to check your HTML form, to help you in a better way.
I think you made below mistakes.
You are not posting "data" field value in your HTML.
You must put the name field for get data.
You are posting the form for using post method. So you should be used $_POST[] or $_REQUEST[].
please verify your HTML.
Related
could you help me pass a variable that was taken from a html form into javascript.
The form asks for the tablename
<br>
New tablename:<br>
<input type="text" name="table">
It is passed through PHP:
if (isset($_POST['submit'])) {
$user = $_POST['user'];
$password = $_POST['password'];
$table = $_POST['table'];
$geometry = $_POST['geom'];
}
A first action is underway, and created successfully: the Geoserver postgis table is created through PHP curl (entire code below)
then the javascript tries to get $table with a PHP insert; this will help it load the newly created postgis Geoserver table from the PHP, into the WFST javascript ;
<?php
echo "var thedata = " .$table. ";\n";
?>
...
var wfstPoly = new L.WFST({
url: 'https://mappingforyou.eu/geoserver/ows',
typeNS: 'opendata',
typeName: thedata,
But this code doesn't work:
<?php
echo "var thedata = " .$table. ";\n";
?>
--
The code works fine except for the thedata javascript variable.
The entire form:
<!DOCTYPE html>
<html>
<body>
<h2>PG GS input test</h2>
<form method="POST" action="test1.php">
User:<br>
<input type="text" name="user">
<br>
Password:<br>
<input type="password" name="password">
<br>
New tablename:<br>
<input type="text" name="table">
<input type="radio" name="geom" id="Point" value="Point" />
<label for="Point">Point</label>
<input type="radio" name="geom" id="MultiLineString" value="MultiLineString" />
<label for="MultiLine">Line</label>
<input type="radio" name="geom" id="MultiPolygon" value="MultiPolygon" />
<label for="MultiPolygon">Area</label>
<br><br>
<input type="submit" name="submit">
</form>
</body>
</html>
Into this javascript test1.php page:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.2.0/leaflet.css"/>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css"/>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet.toolbar.js/0.3.0/leaflet.toolbar.css" />
<style>
html, body, #map {
margin: 0;
height: 100%;
width: 100%;
}
</style>
<title>Leaflet-WFST polygon demo</title>
</head>
<body>
<div id="map"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.2.0/leaflet.js"></script>
<link rel="stylesheet" href="https://mappingforyou.eu/javascript/leaflet.draw.css" />
<script src="https://mappingforyou.eu/javascript/leaflet.draw-src.js"></script>
<link type="text/css" rel="stylesheet" href="https://mappingforyou.eu/javascript/leaflet-easybutton.css" />
<script type="text/javascript" src="https://mappingforyou.eu/javascript/leaflet-easybutton.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/proj4js/2.4.4/proj4.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/proj4leaflet/1.0.2/proj4leaflet.js"></script>
<script src="https://mappingforyou.eu/javascript/leaflet-wfst.src.js"></script>
<script>
function jsFunction(){
<?php
echo "var thedata = " .$table. ";\n";
?>
var map = L.map('map', {editable: true}).setView([48.5, 2], 10);
// add an OpenStreetMap tile layer
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors'
}).addTo(map);
var wfstPoly = new L.WFST({
url: 'http://localhost:8080/geoserver/ows',
typeNS: 'workspace',
typeName: thedata,
crs: L.CRS.EPSG4326,
geometryField: 'geom',
style: {
color: 'blue',
weight: 2
}
}).addTo(map)
.once('load', function () {
map.fitBounds(wfstPoly);
});
////// draw and edit
var drawControl = new L.Control.Draw({
draw:{circle:false, circlemarker:false, rectangle:false,
},
edit:{featureGroup: wfstPoly } });
map.addControl(drawControl);
map.on('draw:created', function (e) {
var layer = e.layer;
wfstPoly.addLayer(layer)});
map.on('draw:edited', function (e) {
var layers = e.layers;
layers.eachLayer( function (layer) {
wfstPoly.editLayer(layer);
})
});
// Save button
L.easyButton('fa-save', function () {
wfstPoly.save();
}, 'Save changes').addTo(map);
}
</script>
<?php
// Open log file
$logfh = fopen("GeoserverPHP.log", 'w') or die("can't open log file");
// Initiate cURL session
$service = "http://localhost:8080/geoserver/rest"; // replace with your URL
$ws = "workspace";
$ds = "database";
$request = "/workspaces/" . $ws . "/datastores/" . $ds . "/featuretypes";
$url = $service . $request;
$ch = curl_init($url);
if (isset($_POST['submit'])) {
$user = $_POST['user'];
$password = $_POST['password'];
$table = $_POST['table'];
$geometry = $_POST['geom'];
}
define("GEOSERVER_REST_HOST", "http://localhost:8080/geoserver/rest");
define("GEOSERVER_USER", "admin:password");
// Optional settings for debugging
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //option to return string
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_STDERR, $logfh); // logs curl messages
//Required POST request settings
curl_setopt($ch, CURLOPT_POST, True);
//$passwordStr = "admin:geoserver"; // replace with your username:password
curl_setopt($ch, CURLOPT_USERPWD, GEOSERVER_USER);
//POST data
curl_setopt($ch, CURLOPT_HTTPHEADER,
array("Content-type: text/xml"));
$xmlStr = "<featureType>";
$xmlStr .= "<name>".$table."</name>";
$xmlStr .= "<nativeName>".$table."</nativeName>";
$xmlStr .= "<title>".$table."</title>";
$xmlStr .= "<srs>EPSG:4326</srs>";
$xmlStr .= "<attributes>";
$xmlStr .= "<attribute>";
$xmlStr .= "<name>geom</name>";
$xmlStr .= "<binding>com.vividsolutions.jts.geom.".$geometry."</binding>";
$xmlStr .= "</attribute>";
$xmlStr .= "<attribute>";
$xmlStr .= "<name>description</name>";
$xmlStr .= "<binding>java.lang.String</binding>";
$xmlStr .= "</attribute>";
$xmlStr .= "<attribute>";
$xmlStr .= "<name>timestamp</name>";
$xmlStr .= "<binding>java.util.Date</binding>";
$xmlStr .= "</attribute>";
$xmlStr .= "</attributes>";
$xmlStr .= "</featureType>";
curl_setopt($ch, CURLOPT_POSTFIELDS, $xmlStr);
//POST return code
$successCode = 201;
$buffer = curl_exec($ch); // Execute the curl request
// Check for errors and process results
$info = curl_getinfo($ch);
if ($info['http_code'] != $successCode) {
$msgStr = "# Unsuccessful cURL request to ";
$msgStr .= $url." [". $info['http_code']. "]\n";
fwrite($logfh, $msgStr);
} else {
$msgStr = "# Successful cURL request to ".$url."\n";
fwrite($logfh, $msgStr);
}
fwrite($logfh, $buffer."\n");
curl_close($ch); // free resources if curl handle will not be reused
fclose($logfh); // close logfile
echo '<script type="text/javascript">jsFunction();</script>';
return $success;
?>
</body>
</html>
In the code you provided, this:
if (isset($_POST['submit'])) {
$user = $_POST['user'];
$password = $_POST['password'];
$table = $_POST['table'];
$geometry = $_POST['geom'];
}
...comes after this:
echo "var thedata = " .$table. ";\n";
The initial assignment of PHP variable $table needs to come before it is used.
And if the table name, provided by the form text input, is a string, $table needs to be quoted for when it gets assigned to the Javascript variable thedata:
For example:
function jsFunction(){
<?php
if (isset($_POST['submit'])) {
$user = $_POST['user'];
$password = $_POST['password'];
$table = $_POST['table'];
$geometry = $_POST['geom'];
}
// ...
echo "var thedata = \"" .$table. "\";\n";
?>
<!-- ... -->
Keep in mind, PHP executes on the server, and the resulting text, containing HTML, Javascript, CSS, is sent to the browser through HTTP. The browser never gets PHP code. The browser only gets HTML, Javascript, and CSS. Once the browser gets these from the server it evaluates the Javascript and renders the HTML and CSS.
This, on the server:
function jsFunction(){
<?php
if (isset($_POST['submit'])) {
$user = $_POST['user'];
$password = $_POST['password'];
$table = $_POST['table'];
$geometry = $_POST['geom'];
}
// ...
echo "var thedata = \"" .$table. "\";\n";
?>
<!-- ... -->
...is executed resulting in this:
function jsFunction(){
var thedata = "user provided table name";
<!-- ... -->
...which is then sent as text to the browser.
I elaborate further on the distinct PHP and Javascript execution contexts here: https://stackoverflow.com/a/72023066/2743458
Try below
var thedata = <?php echo $table; ?>+"\n";
I currently have a loginsystem where a user is able to register and login as a user.
When the user is logged in they should be able to upload a profile image.
The problem that i have is that when i press the Signup button, i gets rediretec to this URL (http://localhost/php51/login.php) Instead of this (http://localhost/php51/index.php).
The thing is that when the user has been registered, then the user should pop up on index.php and show a default profile pic for the user.
Instead i just get a blank page on (http://localhost/php51/login.php).
This is my database with the columns:
I have two tables in my Database called (loginsystem)
the two tables are:
table "profileimg" with the columns (id, status, userid)
and the table "users" with columns (user_email, user_id, user_name, user_password, user_phone, user_zip)
This is my code:
INDEX.php
<?php
session_start();
include_once 'dbh.php';
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<?php
// Check if there is users
$sql = "SELECT * FROM users";
$result = mysqli_query($conn, $sql);
if(mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$id = $row['user_id'];
$sqlImg = "SELECT * FROM profileimg WHERE userid='$id'";
$resultImg = mysqli_query($conn, $sqlImg);
while ($rowImg = mysqli_fetch_assoc($resultImg)) {
echo "<div>";
if($rowImg['status'] == 0) {
echo "<img src='uploads/profile".$id.".jpg'";
} else {
echo "<img src='uploads/profiledefault.jpg'";
}
echo $row['name'];
echo "</div>";
}
}
} else {
echo "No registered users :";
}
//Her checker vi for om man er logget ind,
//og viser herefter upload FORM
if (isset($_SESSION['id'])) {
if ($_SESSION['id'] == 1) {
echo " You are logged in!";
}
//If the user is logged in, we allow the user to upload a profile image
echo "<form action = 'upload.php' method='POST' enctype = 'multipart/form-data'>
<input type = 'file' name = 'file'>
<button type = 'submit' name = 'submit'>UPLOAD FILE</button>
</form>";
} else {
echo " You are not logged in!";
echo "<form action='login.php' method='POST'>
<input type='text' name='name' placeholder='Name'>
<input type='text' name='phone' placeholder='phone'>
<input type='text' name='email' placeholder='email'>
<input type='text' name='zip' placeholder='zip'>
<input type='password' name='password' placeholder='password'>
<button type ='submit' name='submitSignup'>Signup</button>
</form>";
}
?>
<!--We use HTML forms when we want to upload images or files-->
<!--The form HAS to be set as a POST method, and it needs the "enctype" attribute, which specifies that the content we are submitting using the form is a file-->
<p> Login as user </p>
<form action="login.php" method="POST">
<button type="submit" name="submitLogin"> Login </button>
</form>
<p> Logout as user </p>
<form action="logout.php" method="POST">
<button type="submit" name = "submitLogout">Logout</button>
</form>
</body>
</html>
LOUGOUT.php
<?php
session_start();
session_unset();
session_destroy();
header("Location: index.php");
UPLOAD.php
<?php
//First we check if the form has been submitted
if (isset($_POST['submit'])) {
//Then we grab the file using the FILES superglobal
//When we send a file using FILES, we also send all sorts of information regarding the file
$file = $_FILES['file'];
//Here we get the different information from the file, and assign it to a variable, just so we have it for later
//If you use "print_r($file)" you can see the file info in the browser
$fileName = $file['name'];
$fileType = $file['type'];
//The "tmp_name" is the temporary location the file is stored in the browser, while it waits to get uploaded
$fileTempName = $file['tmp_name'];
$fileError = $file['error'];
$fileSize = $file['size'];
//Later we are going to decide the file extensions that we allow to be uploaded
//Here we are getting the extension of the uploaded file
//First we split the file name into name and extension
$fileExt = explode('.', $fileName);
//Then we get the extention
$fileActualExt = strtolower(end($fileExt));
//Here we declare which extentions we want to allow to be uploaded (You can change these to any extention YOU want)
$allowed = array("jpg", "jpeg", "png", "pdf");
//First we check if the extention is allowed on the uploaded file
if (in_array($fileActualExt, $allowed)) {
//Then we check if there was an upload error
if ($fileError === 0) {
//Here we set a limit on the allowed file size (in this case 500mb)
if ($fileSize < 500000) {
//We now need to create a unique ID which we use to replace the name of the uploaded file, before inserting it into our rootfolder
//If we don't do this, we might end up overwriting the file if we upload a file later with the same name
//Here we create a unique ID based on the current time, meaning that no ID is identical. And we add the file extention type behind it.
$fileNameNew = uniqid('', true).".".$fileActualExt;
//Here we define where we want the new file uploaded to
$fileDestination = 'uploads/'.$fileNameNew;
//And finally we upload the file using the following function, to send it from its temporary location to the uploads folder
move_uploaded_file($fileTempName, $fileDestination);
//Going back to the previous page
header("Location: index.php");
}
else {
echo "Your file is too big!";
}
}
else {
echo "There was an error uploading your file, try again!";
}
}
else {
echo "You cannot upload files of this type!";
}
}
SIGNUP.php
<?php
include_once 'dbh.php';
$name = $_POST['name'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$zip = $_POST['zip'];
$password = $_POST['password'];
$sql = "INSERT INTO users (name, phone, email, zip, password)
VALUES ('$name', '$phone', '$email', '$zip', '$password')";
mysqli_query($conn, $sql);
$sql = "SELECT * FROM users WHERE name = '$name' AND phone='$phone'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$userid = $row['user_id'];
$sql = "INSERT INTO profileimg (userid, status)
VALUES ('$userid', 1)";
mysqli_query($conn, $sql);
header("Location: index.php");
}
} else {
echo "Error";
}
DBH.PHP
<?php
$conn = mysqli_connect("localhost", "root", "", "loginsystem");
LOGIN.PHP
<?php
session_start();
if (isset($_POST['submitLogin'])) {
$_SESSION['id'] = 1;
header("Location: index.php");
}
In your file index.php you need to change the line
echo "<form action='login.php' method='POST'>
to
echo "<form action='signup.php' method='POST'>
Right now you're sending your signup data to the wrong place
I am having issues displaying image on the website i am developing. It a website that users can change their profile picture, as well as their basic profile information. bellow is my sample code.
profile.php
<?php
$studpix=$row_rsp['pix'];
$propix='<img class=
"profile-user-img img-responsive img-circle" src="...
/Student /imageupload/blank.png"
alt="profile picture">';
if($propix!=NULL)
{
$propix='<img class="profile-user-img
img-responsive img-circle" src="Student/imageupload/'.$studpix.'"
alt="profile picture">';
};
$profile_pic_btn =
' Profile pics';
$avatar_form = '<form id="avatar_form"
enctype="multipart/form-data" method="post" action="photoup.php">';
$avatar_form .= '<h4>Change your picture</h4>';
$avatar_form .= '<input type="file" name="avatar" required>';
$avatar_form .= '<p><input type="submit" value="Upload"></p>';
$avatar_form .= '</form>';
?>
<?php echo $propix?><?
php echo $avatar_form?><?php echo $profile_pic_btn;?>
//other codes goes here
imageupload.php
<?php
if (isset($_FILES["avatar"]["name"]) && $_FILES["avatar"]
["tmp_name"] != ""){
$fileName = $_FILES["avatar"]["name"];
$fileTmpLoc = $_FILES["avatar"]["tmp_name"];
$fileType = $_FILES["avatar"]["type"];
$fileSize = $_FILES["avatar"]["size"];
$fileErrorMsg = $_FILES["avatar"]["error"];
$kaboom = explode(".", $fileName);
$fileExt = end($kaboom);
list($width, $height) = getimagesize($fileTmpLoc);
if($width < 10 || $height < 10){
echo "ERROR: That image has no dimensions";
exit();
}
$db_file_name = rand(100000000000,999999999999).".".$fileExt;
if($fileSize > 1048576) {
echo "ERROR: Your image file was larger than 1mb";
exit();
} else if (!preg_match("/\.(gif|jpg|png)$/i", $fileName) ) {
echo "ERROR: Your image file was not jpg, gif or png type";
exit();
} else if ($fileErrorMsg == 1) {
echo "ERROR: An unknown error occurred";
exit();
}
$sql = "SELECT pix FROM studentdetails WHERE email='%s'";
$query = mysqli_query($myconn, $sql);
$row = mysqli_fetch_row($query);
$avatar = $row[0];
if($avatar != ""){
$picurl = "../Student/imageupload/$avatar";
if (file_exists($picurl)) { unlink($picurl); }
}
$moveResult = move_uploaded_file(
$fileTmpLoc, "../Student /imageupload /$db_file_name");
if ($moveResult != true) {
echo "ERROR: File upload failed";
exit();
}
include_once("../image_resize.php");
$target_file = "../Student/imageupload/$db_file_name";
$resized_file = "../Student/imageupload/$db_file_name";
$wmax = 200;
$hmax = 300;
img_resize($target_file, $resized_file, $wmax, $hmax, $fileExt);
$sql = "UPDATE studendetails SET pix='%s' WHERE email='%s' LIMIT 1";
$query = mysqli_query($myconn, $sql);
mysqli_close($myconn);
header("location: profile.php");
exit();
}
?>
Your help will be appreciated.
Try to debug your code step by step.
1. Check whether the file gets uploaded correctly and to the correct folder.
2. Check whether the data is updated correctly in the database.
3. Try to open the file by URL directly in the browser.
4. Check whether your HTML code is outputted correctly on the webpage and debug the outputted source code.
5. Make sure that your HTML code works properly.
There may be more steps to take, but this might give you some direction.
My test.php page is as under:
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<h3>Setting</h3>
<form>
<p>Name:<input type="text" id="updatetherone1"/></p>
<p>Email:<input type="text" id="updateotherone2"/></p>
<p><input id="updateone" type="button" value="Save"/></p>
</form>
<span id="updateotherotherone"></span>
<script src="js/jquery.js"></script>
<script src="js/ajax.js"></script>
</body>
</html>
My ini.php page is as under:
<?php
session_start();
$_SESSION['state'] ='2';
$conn=new mysqli('localhost','root','','people');
?>
My test1.php page is as under:
<?php
include 'ini.php';
if (isset($_POST['name'], $POST['email'])){
$name = mysqli_real_escape_string(htmlentities($POST['name']));
$email = mysqli_real_escape_string(htmlentities($POST['email']));
$update = mysqli_query("UPDATE state SET Name='$name', email='$email' WHERE Id=".$_SESSION['state']);
if($update === true){
echo 'Setting have been updated.';
}else if ($update === false){
echo 'There was an error updating your setting.';
}
}
?>
My ajax.js page is as under:
$('[id=updateone]').click(function(){
var name=$('[id=updateotherone1]').val();
var email=$('[id=updateotherone2]').val();
$('[id=updateotherotherone]').text('Loading...');
$.post('test1.php',{name:name,email:email},function(data){
$('[id=updateotherotherone]').text(data);
});
});
Ultimately code is not working nor do it is displaying any error, I suspect there is something wrong with test1.php page, can anybody guide please:
Take note that the procedural interface of mysqli_query(), the first parameter need the connection.
$update = mysqli_query($conn, "UPDATE state SET Name='$name', email='$email' WHERE Id=".$_SESSION['state']);
If these are typos $POST, then it should be fixed in your code. It's supposed to read as $_POST. (unless its a typo on the question.) It is a superglobal.
I suggest you just use the object oriented interface. So that you wouldn't need to add it everytime:
<?php
include 'ini.php';
if (isset($_POST['name'], $_POST['email'])){
$name = $conn->real_escape_string(htmlentities($_POST['name']));
$email = $conn->real_escape_string(htmlentities($_POST['email']));
$update = $conn->query("UPDATE state SET Name='$name', email='$email' WHERE Id = " . $_SESSION['state']);
if($conn->affected_rows > 0) {
echo 'Setting have been updated.';
} else {
echo 'There was an error updating your setting.';
}
}
?>
Might as well use prepared statements since mysqli supports it:
if (isset($_POST['name'], $_POST['email'])){
$name = htmlentities($_POST['name']);
$email = htmlentities($_POST['email']);
$sql = 'UPDATE state SET Name = ?, email = ? WHERE Id = ?';
$update = $conn->prepare($sql);
$update->bind_param('ssi', $name, $email, $_SESSION['state']);
$update->execute();
if($update->affected_rows > 0) {
echo 'Setting have been updated.';
} else {
echo 'There was an error updating your setting.';
}
}
On the JS part:
You also have a typo on the form id and the JS:
<p>Name:<input type="text" id="updatetherone1"/></p> <!-- missing o -->
var name=$('[id=updateotherone1]').val();
Should be: <p>Name:<input type="text" id="updatetherone1"/></p>
Sidenote:
If you want to avoid those kind of silly typos, just id and label them properly. Example:
<p>Name:<input type="text" id="name_field"/></p>
<p>Email:<input type="text" id="email_field"/></p>
i've successfully uploaded my image into folder and successfully saved my path into database now as i tried to show pic into browser it's showing error:
Warning: mysql_query() expects parameter 2 to be resource, object given in C:\Users\Raj\PhpstormProjects\image\upload_file.php on line 6
Warning: mysql_num_rows() expects parameter 1 to be resource, null given in C:\Users\Raj\PhpstormProjects\image\upload_file.php on line 7
File name not found in database
here is my code for form:
<?php
// Assigning value about your server to variables for database connection
$hostname_connect= "localhost";
$database_connect= "photo";
$username_connect= "root";
$password_connect= "Bhawanku";
$connect_solning = mysql_connect($hostname_connect, $username_connect, $password_connect) or trigger_error(mysql_error(),E_USER_ERROR);
#mysql_select_db($database_connect) or die (mysql_error());
if($_POST)
{
// $_FILES["file"]["error"] is HTTP File Upload variables $_FILES["file"] "file" is the name of input field you have in form tag.
if ($_FILES["file"]["error"] > 0)
{
// if there is error in file uploading
echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
}
else
{
// check if file already exit in "images" folder.
if (file_exists("images/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{ //move_uploaded_file function will upload your image. if you want to resize image before uploading see this link http://b2atutorials.blogspot.com/2013/06/how-to-upload-and-resize-image-for.html
if(move_uploaded_file($_FILES["file"]["tmp_name"],"images/" . $_FILES["file"]["name"]))
{
// If file has uploaded successfully, store its name in data base
$query_image = "insert into acc_images (image, status, acc_id) values ('".$_FILES['file']['name']."', 'display','')";
if(mysql_query($query_image))
{
echo "Stored in: " . "images/" . $_FILES["file"]["name"];
}
else
{
echo 'File name not stored in database';
}
}
}
}
}
?>
<html>
<body>
<form action="upload_file.php" method="post"enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>
and here is my code for showing pics:
<?php
$con=mysqli_connect("localhost","root","Bhawanku","photo");
// Check connection
$query_image = "SELECT * FROM acc_images";
// This query will show you all images if you want to see only one image pass acc_id='$id' e.g. "SELECT * FROM acc_images acc_id='$id'".
$result = mysql_query($query_image, $con);
if(mysql_num_rows($result) > 0)
{
while($row = mysql_fetch_array($result))
{
echo '<img alt="" src="images/'.$row["image"].'">';
}
}
else
{
echo 'File name not found in database';
}
?>
In the second script, you're connecting as mysqli but then using mysql_query, mysql_num_rows and mysql_fetch_array. MySQLi and MySQL aren't interchangeable.
$result = mysqli_query($query_image, $con);
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
echo '<img alt="" src="images/'.$row["image"].'">';
}
}
else
{
echo 'File name not found in database';
}
You should consider changing the first script to MySQLi too, and use prepared statements instead of concatenating variables into the query.
In first row you use mysqli extension, but in all other - mysql.
Try to change:
<?php
$con=mysql_connect("localhost","root","Bhawanku");
mysql_select_db("photo", $con);
// Check connection
$query_image = "SELECT * FROM acc_images";
// This query will show you all images if you want to see only one image pass acc_id='$id' e.g. "SELECT * FROM acc_images acc_id='$id'".
$result = mysql_query($query_image, $con);
if(mysql_num_rows($result) > 0)
{
while($row = mysql_fetch_array($result))
{
echo '<img alt="" src="images/'.$row["image"].'">';
}
}
else
{
echo 'File name not found in database';
}
?>