Need to Update the data from mysql - php

<?php
if(isset($_POST['Search']))
{
$num = $_POST['num'];
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
$dbname = 'vasuki';
mysql_select_db($dbname);
$Result = mysql_query("SELECT id, name, age FROM details WHERE id = '$num'");
while($row = mysql_fetch_array($Result)) {
$name = $row['name'] ;
$age = $row['age'];
echo "<div style='top: 273px;
margin-left: 60px;
position: absolute;left: 30px;'>
<table border='1'><tr><th>Name</th>
<th> Age </th></tr>
<tr><td>".$name."</td>
<td>".$age."</td>
<td>Edit</td></tr>
</table></div>";
}
I will explain the concept first :
In first page I insert the person details. and In second page in need to update the details. The above program is for my second page. To update I am searching data using the name and age. If I get the particular person data I need to click Edit and It should go to my 1st page and I need to Update the data.
I completed my html codes. I need to know php code to connect SQL.
Can anyone help on this ?

If you want to redirect to another page, in form you need to add action="otherpage.php" and in that other file you need to write something like:
if (!empty($_GET['newValue']) {
mysql_query("update details set name='".$_GET['name']."', age='".$_GET['age']."' WHERE id=".$_GET['id']."");
header("location: index.php");
exit;
}
This is approximate approach and there a few things you should change like mysql to mysqli or PDO (because deprecated) with prepared statements and escape all inputs.

Related

How can I get a specific data using SQL select query?

I am trying to make a blog site.For this purpose I need to use a specific data from a specific field from my database table.To do that I wrote these code.
<?php
$host = "localhost";
$user = "root";
$pass = "12345";
$db = "bnsb";
$conn = mysql_connect($host, $user, $pass) or die("Connection Failed!");
mysql_select_db($db, $conn) or die("Database couldn't select!");
$img = "select image from news where uid=1";
echo $img;
?>
My database connection is OK.It should print like this user_img1.jpg. But it prints the whole sql query like select image from news where uid=1. I run this code on phpmyadmin. It works! But it does not work in my php script.How can I do now?
You can not give the query as it is and expect result like in phpadmin.
For this first of all you have to connect to your DB like this
$con = mysqli_connect("localhost","my_user","my_password","my_db");
execute required query like this
$query22 = "select image from news where uid = 1";
$result22 = mysqli_query($con, $query22) or die (mysqli_error());
Get the result and display like this
while($rows = mysqli_fetch_array($result22, MYSQLI_BOTH))
{
echo "<br>Values in db: " . $rows['columnname'];
}
Also i advice you to take a look at these tutorials
http://codular.com/php-mysqli
http://www.dreamincode.net/forums/topic/54239-introduction-to-mysqli-and-prepared-statements/
Please read some PHP 101 kind of tutorials on how to use PHP.
To get data from DB (in almost any language)
You need to connect to a DB. The connection gets you some sort of resource
You formulate your query (which you seem to have done)
You execute the query against the DB that you connected to (step #1)
You get a result (set)
You iterate over the result set to get the individual result(s); in your case the result set would be just one result (or row).
The examples to do this in PHP are very basic; please do your own lookup on net. This one seems good enough to get you started - http://www.w3schools.com/php/php_mysql_intro.asp
Try this,
<?php
$host = "localhost";
$user = "root";
$pass = "12345";
$db = "bnsb";
$conn = mysql_connect($host, $user, $pass) or die("Connection Failed!");
mysql_select_db($db, $conn) or die("Database couldn't select!");
$img = "select image from news where uid=1";
$result=mysql_query($img);
while($row=mysql_fetch_array($result)){
echo '<img src="your_path_to_image/'.$row['image'].'" /> - '.$row['image'];
}
?>

Trying to search ID and Display selected information

I have made a search box so that you can enter the product id that you wish to gain the information of. When i input data in the product id box, there are no results returned, anyone know what im doing wrong? I think that 'while ($row = mysql_fetch_array($result)) {' is wrong but not too sure as everything ive tried didn't work.
<div class="searchbox">
<form action="Search.php" method="get">
<fieldset>
<input name="search" id="search" placeholder="Search for a Product" type="text" />
<input id="submit" type="button" />
</fieldset>
</form>
</div>
<div id="content">
<ul>
<?php
// connect to the database
include('base.php');
$search = mysql_real_escape_string($_GET['search']);
$query = "SELECT * FROM Product WHERE ProductID LIKE '%{$search}%'";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
echo "<li><span class='name'><b>{$row['ProductID']}</b></span></li>";
}
Don't use mysql specific syntax, It's outdated and can get you into real trouble later on, especially if you decide to use sqlite or postgresql.
Use a PDO connection, you can init one like this:
// Usage: $db = connectToDatabase($dbHost, $dbName, $dbUsername, $dbPassword);
// Pre: $dbHost is the database hostname,
// $dbName is the name of the database itself,
// $dbUsername is the username to access the database,
// $dbPassword is the password for the user of the database.
// Post: $db is an PDO connection to the database, based on the input parameters.
function connectToDatabase($dbHost, $dbName, $dbUsername, $dbPassword)
{
try
{
return new PDO("mysql:host=$dbHost;dbname=$dbName;charset=UTF-8", $dbUsername, $dbPassword);
}
catch(PDOException $PDOexception)
{
exit("<p>An error ocurred: Can't connect to database. </p><p>More preciesly: ". $PDOexception->getMessage(). "</p>");
}
}
And then init the variables:
$host = 'localhost';
$user = 'root';
$dataBaseName = 'databaseName';
$pass = '';
Now you can access your database via
$db = connectToDatabase($host , $databaseName, $user, $pass); // You can make it be a global variable if you want to access it from somewhere else.
Then you should make sure that you actually have the variable:
$search = isset($_GET['search']) ? $_GET['search'] : false;
So you can actually skip the database thing if something, somehow, fails.
if(!$search)
{
//.. return some warning error.
}
else
{
// Do what follows.
}
Now you should construct a query that can be used as a prepared query, that is, it accepts prepared statements so that you prepare the query and then you execute an array of variables that are to be put executed into the query, and will avoid sql injection in the meantime:
$query = "SELECT * FROM Product WHERE ProductID LIKE :search;"; // Construct the query, making it accept a prepared variable search.
$statement = $db->prepare($query); // Prepare the query.
$statement->execute(array(':search' => $search)); // Here you insert the variable, by executing it 'into' the prepared query.
$statement->setFetchMode(PDO::FETCH_ASSOC); // Set the fetch mode.
while ($row = $statement->fetch())
{
$productId = $row['ProductID'];
echo "<li class='name><strong>$productId</strong></li>";
}
Oh yes, don't use the b tag, it's outdated. Use strong instead (It's even smarter to apply font-weight: bold; to .name in a separate css file.
Feel free to ask questions if anything is unclear.
remove the {} before and after $search.
should be:
$query = "SELECT * FROM Product WHERE ProductID LIKE '%$search%'";
You can use:
$result = mysql_query($query) or die($query."<br/><br/>".mysql_error());
To confirm that the data is returning.

How to show image using php?

I am just starting to use html, php, and mysql. I've successfully logged into my database using php, and formed a query. I now want to go a step further and show a picture instead of just strings or numbers.
The variable 'result' will be returning a string that has a url to an image i want to display on this webpage. How would I do this?
<html>
<head>
<title>My First Question</title>
</head>
<body>
<?php
$dbhost = 'someURL.com';
$dbname = 'user';
$dbuser = 'user';
$dbpass = 'password';
$mysql_handle = mysql_connect($dbhost, $dbuser, $dbpass)
or die("Error Connecting To Database Server");
mysql_select_db($dbname, $mysql_handle)
or die("Error selecting database: $dbname");
echo 'Successfully connected to database!';
$first = 'bobbie';
$query = sprintf("SELECT image FROM Player
p WHERE name='%s'", mysql_real_escape_string($first));
$result = mysql_query($query);
mysql_close($mysql_handle);
?>
</body>
</html>
Inside PHP, This will turn your SQL response into a usable variable.
$result = mysql_fetch_assoc(mysql_query($query));
Outside of your PHP tags, Echo the URL from the table into the SRC of an IMG element.
<img src="<?= $result['url_column_name'] ?>"/>
This will create a new IMG element with the source being the URL that you have fetched from your SQL query.
Short tags are also a way of echoing PHP variables in HTML.
<?= $var1, $var2 ?>
is the equivalent of using
<?php echo $var; echo $var2; ?>
This is a simple case of echoing the relevant HTML. You'll also have to fetch the results after you execute the query -
$result = mysql_query($query);
$data = mysql_fetch_assoc($result);
echo '<img src="'.$data['image'].'" />;
For added security, a good practice would be to escape any possible unwanted HTML content in your images path - htmlspecialchars($data['image']).
It should also be noted here that you are using a very old deprecated method to access your database. You might want to think about updating your code to use more modern PDO methods.
So what? simply use it as a source to your image
<?php $imgname = mysqli_fetch_array($connection, $result); ?>
<img src="<?php echo $imgname['image_column_name']; ?>" />
And btw use mysqli_() or PDO instead of using mysql_() as community is not maintaining it anymore
Once you update your mysql to mysqli you can echo the image's url in an html img tag as so:
echo '<img src="'.$result['image'].'"/>';
<?php
$dbhost = 'someURL.com';
$dbname = 'user';
$dbuser = 'user';
$dbpass = 'password';
$mysql_handle = mysql_connect($dbhost, $dbuser, $dbpass)
or die("Error Connecting To Database Server");
mysql_select_db($dbname, $mysql_handle)
or die("Error selecting database: $dbname");
$first = 'bobbie';
$query = sprintf("SELECT image FROM Player
p WHERE name='%s'", mysql_real_escape_string($first));
$result = mysql_query($query);
mysql_close($mysql_handle);
header("Location: $result");
?>
should work

simple php - Mysql search not working properly

I have this code:
<?php
// Make a MySQL Connection
$dbhost = 'xxx';
$dbuser = 'xxx';
$dbpass = 'xxx';
$dbname = 'xxx';
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
mysql_select_db($dbname);
// Retrieve all the data from the "example" table
$result = mysql_query("SELECT * FROM clients WHERE FNAME='".$_POST['clientsearch']."' OR LNAME='".$_POST['clientsearch']."' OR MAIL='".$_POST['clientsearch']."' OR TEL='".$_POST['clientsearch']."'"")
or die(mysql_error());
// store the record of the "example" table into $row
$row = mysql_fetch_array( $result );
// Print out the contents of the entry
echo "FName: ".$row['FNAME'];
echo "LNAME: ".$row['LNAME'];
echo "FName: ".$row['MAIL'];
echo "LNAME: ".$row['TEL'];
?>
The goal is to search my mysql database to find the result of $_POST['clientsearch'] in one of the fields and return the lines that have that word in it (it is always 1 word)
If I use this:
$result = mysql_query("SELECT * FROM clients WHERE FNAME='".$_POST['clientsearch']."'"")
it seems to work. but it only searches in the FNAME column, not all of them. Also I only get the first result back. not all.
I'm starting php/mysql so I'm a little lost and don't know all functions yet. Could someone explain how I could fix my code up?
Thanks a lot for your help :)
For starters, you'll need to loop through each row in your result set if you're expecting more than 1 row. I illustrate how to do this with your original code.
<?php
// Make a MySQL Connection
$dbhost = 'xxx';
$dbuser = 'xxx';
$dbpass = 'xxx';
$dbname = 'xxx';
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
mysql_select_db($dbname);
// Retrieve all the data from the "example" table
$result = mysql_query("SELECT * FROM clients WHERE FNAME='".$_POST['clientsearch']."' OR LNAME='".$_POST['clientsearch']."' OR MAIL='".$_POST['clientsearch']."' OR TEL='".$_POST['clientsearch']."'"")
or die(mysql_error());
// Print out the contents of the entry for each row in result
while( $row = mysql_fetch_array( $result, MYSQL_ASSOC ) ) {
echo "FName: ".$row['FNAME'];
echo "LNAME: ".$row['LNAME'];
echo "FName: ".$row['MAIL'];
echo "LNAME: ".$row['TEL'];
}
?>
Take a look in the PHP documentation on mysql_real_escape_string for starters on the injection stuff.
Also, as others stated you may be looking for the LIKE instead of = SQL syntax. Also, look into the % wild card for LIKE.
Not an answer to the question, but hopefully helpful. Try writing code like this:
$cs = mysql_escape_string($_POST['clientsearch']);
$result = mysql_query("
SELECT
*
FROM clients
WHERE
FNAME='$cs'
OR LNAME='$cs'
OR MAIL='$cs'
OR TEL='$cs'
");
Exactly how you indent is up to you. This approach helps a great deal with readability, and hence also debugging :)

How does one implement a MySQL database into a webpage?

I am a complete database newbie. So far, I know that I can connect to MySQL using PHP's mysql_connect() command, but apart from that, I really don't see how to take that data and put it onto a web page.
a) are there ways other than mysql_connect()
b) lets say I had a table of data in mysql and all I wanted was for that table (for example: list of names and telephone numbers) to now appear on my web page. I can't for the life of me find a tutorial for this.
<?
$database_name = "dbname";
$mysql_host = "localhost"; //almost always 'localhost'
$database_user = "dbuser";
$database_pwd = "dbpass";
$dbc = mysql_connect($mysql_host, $database_user, $database_pwd);
if(!$dbc)
{
die("We are currently experiencing very heavy traffic to our site, please be patient and try again shortly.");
}
$db = mysql_select_db($database_name);
if(!$db)
{
die("Failed to connect to database - check your database name.");
}
$sql = "SELECT * FROM `table` WHERE `field`= 'value'";
$res = mysql_query($sql);
while($row = mysql_fetch_assoc($res)) {
// code here
// access variables like the following:
echo $row['field'].'<br />';
echo $row['field2'];
}
?>
Check out mysql_fetch_assoc mysql_fetch_array and mysql_fetch_object
This is the very basics, you will want to search for tutorials. There are many about.

Categories