Changing product picture - php

<?php
$Name=$_POST['txtName'];
$Desc=$_POST['txtDesc'];
$path1 = $_FILES["txtFile"]["name"];
move_uploaded_file($_FILES["txtFile"]["tmp_name"],"../Products/" .$_FILES["txtFile"]["name"]);
//** Establish Connection with MYSQL
$con = mysql_connect("localhost","root");
// Select Database
mysql_select_db("jmmc", $con);
// Specify the query to Update Record
$sql = "Update admin_category set CategoryName='".$Name."',Description='".$Desc."',Image='".$path1."' where CategoryId=".$Id."";
// Execute query
mysql_query($sql,$con);
// Close The Connection
mysql_close($con);
?>

Send me error you are getting from code.
Check your file location path that is not true
or
may be you did not create folder Product and check your database make confirm you have right column names
Check Your all Variables like $Id,$Name,$Desc have a proper values
like
(where CategoryId=".$Id."")
you need to define enctype,method type(get or post) in form and make html like this:
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="txtFile" >
<input type="hidden" name="txtDesc" value="aaaaa">
<input type="hidden" name="txtName" value="naveed">
<input type="submit" name="submit_button">
</form>
You need to define PHP code in isset statement like this:
<?php
if (isset($_POST['submit_button'])) {
$fileName = $_FILES["txtFile"] ["name"];
if (isset($fileName)) {
$Name=$_POST['txtName'];
$Desc=$_POST['txtDesc'];
$path1 = $_FILES["txtFile"]["name"];
move_uploaded_file($_FILES["txtFile"]["tmp_name"],"../Products/" .$_FILES["txtFile"]["name"]);
//** Establish Connection with MYSQL
$con = mysql_connect("localhost","root");
// Select Database
mysql_select_db("stackoverflow", $con);
// Specify the query to Update Record
$sql = "Update admin_category set CategoryName='".$Name."',Description='".$Desc."',Image='".$path1."' where CategoryId=".$Id."";
// Execute query
mysql_query($sql,$con);
// Close The Connection
mysql_close($con);
}
}
?>

Related

Search by PHP Mysql

I want to get some variables from a form and i will use those variables to make a search bar for example:
$var=$_POST['var']
I want to put this variable in a request like this:
$SQL = 'SELECT * FROM Table ORDER By $var'
Any suggestions please? How can I transform this request to a dynamic request? thank you :)
The code is:
<form>
<lable for="Variable">
<input type ="text" name="variable" placeholder="Search by : ">
</form>
<?php
$variable = $_POST['variable']
sql = 'SELECT * FROM Total ORDER BY $variable';
?>
Please refer to PDO and for order by review.
your select query would be
SELECT * FROM yourtable ORDER BY DATABASE_FIELD;
At first,
use method="POST" and action="file.php" (but action is not strictly needed, in some cases like processing by AJAX)
<form method="POST" action="file.php">
<lable for="Variable">
<input type ="text" name="variable" placeholder="Search by : ">
</form>
At second you need sanitize input taken from form (it means, you have to eliminate anything that would harm your pages - with this PDO or else layer can help).
At third, you need to rewrite
sql = 'SELECT * FROM Total ORDER BY $variable'
to
sql = "SELECT * FROM Total ORDER BY $variable"
or
sql = 'SELECT * FROM Total ORDER BY '.$variable
because else used variable would be used as is written, instead its content (given by form).
Since you're new it would be wise to embed some good practices from the start. Documentation for reference would be PDO and Prepared Statements.
An example PDO tutorial can be found on W3Schools, along with a tutorial on handling form data with PHP.
This is an example of a simple search
PHP:
<?php
$search = $_POST["search"];
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM `profile` WHERE `email`='$search'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
HTML:
<form action="profile.php" method="post">
<input type="text" name="search"><br>
<input type="submit">
</form>
Hope it helps

Opencart Custom mysql search form

I am creating a simple custom search form. This form searches the table 'oc_product' where i created a new column 'gcode'. I have inserted a sample data in this column for one of the products. Is it necessary to make a new db/mysql connect in php within a new tpl file i created just like 'information/contact'. I call this 'gcode/gcode'.
I tried but unable to get result form the search. It redirected to index.php.
My code is:
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" id="searchform">
<input type="text" name="name">
<input type="submit" name="submit" value="Search">
</form>
if(isset($_POST['submit'])){
if(isset($_GET['go'])){
if(preg_match("/^[ a-zA-Z]+/", $_POST['name'])){
$name=$_POST['name'];
//connect to the database
$db=mysql_connect ("localhost", "username_demo", "pwddemo123") or die ('I cannot connect to the database because: ' . mysql_error());
//-select the database to use
$mydb=mysql_select_db("db_demo");
//-query the database table
$sql="SELECT * FROM oc_product WHERE gcode LIKE '%" . $name . "%'";
//-run the query against the mysql query function
$result=mysql_query($sql);
//-create while loop and loop through result set
while($row=mysql_fetch_array($result)){
$gcode =$row['gcode'];
//-display the result of the array
echo '<span>'."This product is genuine".$gcode.'</span>';
}
}
else{
echo "<p>Please enter a search query</p>";
}
}
}
Any example to search a column and fetch data from a column.
Don't quite understand your question. Do you want to fetch data from ONE column? Also use mysql_fetch_assoc instead mysql_fetch_array
And replace $_GET with $_POST
Also your select statement is wrong, so do this:
<?
$sql="SELECT * FROM oc_product WHERE gcode LIKE '%$name%'";
$result = mysql_query($sql);
$results = mysql_num_rows($result);
for($i=0; $i<$results; $i++)
{
$row = mysql_fetch_assoc($result);
$gcode = $row['gcode'];
// Here list it the way you want
echo $gcode.'<br>';
}
?>
you would need to create a model or simply add this field in the search model to be searched by it. i am not sure if that is what you want to accomplish, also you would want to make sure to sanitize the request and escape it before you get one of the SQL injection attacks.

PHP can't update SQL

I'm using a php part in my site, where I have a textarea that get a text from a database. The user can edit this text and after he finish press the save button, and using UPDATE I will change the text in the database.
Here is my code:
<?php
$con=mysqli_connect("localhost","userdb","codedb","projectdb");
mysqli_set_charset($con, 'utf8');
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$myQueryfac="SELECT text FROM main WHERE id=1";
$result = mysqli_query($con,$myQueryfac);
while($row = mysqli_fetch_array($result)) {
$t1=$row['text'];
}
$form="<form action='adminindex.php' method='post'>
<textarea name='area1' maxlength='1500' cols='50' rows='10'>$t1</textarea>
<input type='submit' name='enter' value='Save'>
</form>";
if($_POST['enter']) {
$t1=$_POST['area1'];
mysqli_query($con,"UPDATE main SET text='$t1' WHERE id='1'");
}
echo $form;
mysqli_close($con);
?>
My problem is in the UPDATE query it seems like it ignores $t1 and nothing change in database. But if I put something random in there, "RANDOM TEXT", change it successful.
This is how you do it:
test.php
// DB Connect
$con=mysqli_connect("localhost","userdb","codedb","projectdb");
mysqli_set_charset($con, 'utf8');
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Handle POST
if (count($_POST))
{
// Save In DB
mysqli_query($con, sprintf("UPDATE main SET `text`='%s' WHERE id=%d",
mysqli_real_escape_string($con, $_POST['area1']),
1)); // id
// Success
echo "<p>Data updated.</p>";
}
// Load Existing Data
$myQueryfac="SELECT `text` FROM main WHERE id=1";
$result = mysqli_query($con, $myQueryfac);
$row = mysqli_fetch_array($result);
// Display Form
echo "<form action='test.php' method='post'>
<textarea name='area1' maxlength='1500' cols='50' rows='10'>". $row['text'] ."</textarea>
<input type='submit' name='enter' value='Save'>
</form>";
// DB Close
mysqli_close($con);
?>
What I've changed
Moved the post hander up (above the select statement), so that if an update occurs, the form will show the latest updated data
Your update query was treating the id as string, I formatted it to be a digit (%d)
Removed the while loop, you don't need it as it is a single row being returned
added sql-injection prevention (using sprintf and mysqli_real_escape_string)
added backticks `` around the db field name text (wasn't sure if this is a reserved word, because it's one of the sql data types)
Try to do
mysqli_query($con,"UPDATE main SET text='$t1' WHERE id=1");
Instead
mysqli_query($con,"UPDATE main SET text='$t1' WHERE id='1'");
It could be the WHERE condition that bring your problems
You are checking the $_POST array for a value not existing. enter is your submit button and will not send a value.
Try this:
if($_POST['area1']) {
$t1=$_POST['area1'];
mysqli_query($con,"UPDATE main SET text='$t1' WHERE id='1'");
}

Update certain column of recordset from textbox value

room.php
<input name = "room" type = "text" size="70"/>
Update
updateroom.php
<?php
mysql_connect('localhost','athirahhazira','1234');
mysql_select_db("dbcollege");
session_start();
$sql = "UPDATE studentsroom set room='$strroom' WHERE roomid='$_GET[roomid]'";
mysql_query($sql) or die('Error updating room status');
header('Location:staff/room-staff.php');
?>
i can update if there is a default value such as :
$sql = "UPDATE studentsroom set room='A206' WHERE roomid='$_GET[roomid]'";
but not the value from a textbox. could u help me with what i am missing here?
try this
$sql = "UPDATE studentsroom set room='A206' WHERE roomid='".$_REQUEST['roomid']."'";
Note: your code can be sql injection. also mysql_* is deprecated use mysqli_* or PDO
Update2:
add a form and submit button instead of hyperlink
<form method="post" action="updateroom.php" >
<input name = "room" type = "text" size="70"/>
<input type="hidden" name="roomid" value="<?php echo $row_Recordsetroomid['roomid'];?>" />
<input type="submit" name="submit" value="Update" />
</form>
AND update.php
<?php
mysql_connect('localhost','athirahhazira','1234');
mysql_select_db("dbcollege");
session_start();
$room = $_REQUEST['room'];
$roomid = $_REQUEST['roomid'];
$room = mysql_real_escape_string($room);
$roomid = mysql_real_escape_string($roomid);
$sql = "UPDATE studentsroom set room='$room' WHERE roomid='$roomid'";
mysql_query($sql) or die('Error updating room status');
header('Location:staff/room-staff.php');
?>
The quotes for the index in the $_GET is missing. Trying to access array variables like $array[key] instead of $array['key'], will trigger an error in most cases. So always try to use quotes for array indexes.
You can try with this.
$sql = "UPDATE studentsroom set room='A206' WHERE roomid='".$_GET['roomid']."'";

PHP Search and Query Results

Here is my issue. I have a database I want to search by name only. If there are similar names I want it to pop up and give an option to pick which one. Once you do and click search it goes into a search.php file... I want to display results but the GET method does not seem to work.
Here is my form.
<form action="search.php" method="GET">
<input type="text" name="query" />
<input type="submit" value="Search" />
Here is my PHP search
<?php
mysql_connect("localhost", "dbname", "password") or die("Error connecting to database: ".mysql_error());
/*
localhost - it's location of the mysql server, usually localhost
root - your username
third is your password
if connection fails it will stop loading the page and display an error
*/
mysql_select_db("ambassador") or die(mysql_error());
/* tutorial_search is the name of database we've created */
$query = $_GET['query'];
// gets value sent over search form
$min_length = 3;
// you can set minimum length of the query if you want
if(strlen($query) >= $min_length){ // if query length is more or equal minimum length then
$query = htmlspecialchars($query);
// changes characters used in html to their equivalents, for example: < to >
$query = mysql_real_escape_string($query);
// makes sure nobody uses SQL injection
$raw_results = mysql_query("SELECT * FROM member
WHERE (`Name` LIKE '%".$query."%')") or die(mysql_error());
if(mysql_num_rows($raw_results) > 0){ // if one or more rows are returned do following
while($results = mysql_fetch_array($raw_results)){
}
}
else{ // if there is no matching rows do following
echo "No results";
}
}
else{ // if query length is less than minimum
echo "Minimum length is ".$min_length;
}
?>
Then I try to use this method to get results from database.
<?php echo $_GET['Name']; ?>
Thanks for all your help!
This is not an answer , i put code here because it's not well formated in the comment.
So , try this part of code ,it should display result according to the name in the form :
HTML:
<form action="search.php" method="GET">
<input type="text" name="name" />
<input type="submit" value="Search" />
</form>
PHP:
<?php
mysql_connect("localhost", "dbname", "password") or die("Error connecting to database: ".mysql_error());
mysql_select_db("ambassador") or die(mysql_error());
//check if variable $_POST['name'] has a value
if(isset($_GET['name'])) $name=$_GET['name'];
else $name="";
$raw_results = mysql_query("SELECT * FROM member where name='".$name."'") or die(mysql_error());
while($results = mysql_fetch_array($raw_results,MYSQL_ASSOC)){
echo $results['name'].'<br/>';
}
?>

Categories