PHP and MySQL help needed - php

I have 2 tables in my database. categories and products. in categories there are 2 fields. catid and catname. and in products also there are 3 fields. id, catid and name.
in my submit form im fetching the catname in to a sector. what i wanna do is get value of the selector and save the catid in to products table catid field. instead of categories name. can anyone explain me how to do this. Thanks in advance.
Here is the code of submit form.
include("db.php");
$result = mysql_query("SELECT * FROM categories")
or die (mysql_error());
?>
<!--SubmitForm-->
<form method="post" action="add_products.php">
<select name="cat">
<?php
while($row = mysql_fetch_array($result))
{echo "<option value='".$row[catid]."'>".$row[catname]."</option>";}
?>
</select><br/>
<input type="text" name="name" value=""><br/>
<input type="submit" value="submit"/>
</form>
add_products.php Code
<?php
include("db.php");
$cat = $_POST['catid'];
$query = "SELECT * FROM categories WHERE catname='$cat'";
$result= mysql_query($query) or die ('Mysql Error');
while($row = mysql_fetch_array($result)){
$catn = $row['catid'];
}
$name = mysql_real_escape_string($_POST['name']);
$query="INSERT INTO products(catid, name)VALUES ('".$catn."','".$name."')";
mysql_query($query) or die ('Error Updating');
echo "Product Added";
?>

You already seem to have the right values, just need to put them in the correct spot, if you need the 'catid', you can just put it in the id tag of the select.
When you echo the you just need to do this,
echo "<option id='".$row[catid]."' value='".$row[cat]."'>".$row[catname]."</option>";
For more info refer to the w3school manual for , at this link.

Some unrelated, but very important things:
you should escape $cat before it goes into the query
you should always escape strings that go out to HTML with htmlspecialchars
you should always use $row['keyname'], not the deprecated $row[keyname]
Now for your question. The code seems correct on first glance, but I don't have PHP right now so I can't test it. Is there anything in particular that is not working as expected?

You already have it in??
$cat = $_POST['catid'];
If you only want to insert IF they $cat exists, then:
<?php
include("db.php");
$cat = $_POST['catid'];
$query = "SELECT * FROM categories WHERE catname='$cat'";
$result= mysql_query($query) or die ('Mysql Error');
if($result)
{
$name = mysql_real_escape_string($_POST['store']);
$query="INSERT INTO products(catid, name)VALUES ('".$catn."','".$name."')";
mysql_query($query) or die ('Error Updating');
echo "Product Added";
}
?>

You are already assigning the category ID to the category name in the select menu. The variable of the select menu is $_REQUEST['cat'], which holds the ID of the selected category after submitting the form. You can save this value directly to the product table.
However, the while loop in add_products.php is of no use, since you are always assigning the last ID in the table to the variable $catn. Replace this while loop with $catn = $_REQUEST['cat'] (while cat is the name of the select menu).

seem many mistakes here:
select name="cat"
and your try to receive $cat = $_POST['catid']; the correct is $cat = $_POST['cat'];
then you tries to select by catname
$query = "SELECT * FROM categories WHERE catname='$cat'";
when you need to compare ids catid='$cat'";
and what for to assign meny times if the result is single?:
if ( ($row = mysql_fetch_array($result)) ){
$catn = $row['catid'];
}

Your select field is names 'cat', so it should be $_POST['cat'] (or better, rename the select field to 'catid'). And it alreay contains the catid, so there's no need to get it from the DB again (unless you want to make sure it does in fact exist).
Finally, you should escape the $_POST['cat'] parameter as you do the name.
So this is sufficient:
$catid = mysql_real_escape_string($_POST['cat']);
$name = mysql_real_escape_string($_POST['store']);
$query="INSERT INTO products(catid, name) VALUES ('".$catid"','".$name."')";
mysql_query($query) or die ('Error Updating');
echo "Product Added";
Please also look into PDO for the best way to handle DB queries like this.

try change this
"INSERT INTO products(catid, name)VALUES ('".$catn."','".$name."')";
to
"INSERT INTO products(catid, name)VALUES ('".$cat."','".$name."')";

Related

how to make the value from the drop-down list remembered and entered into the database after the confirmation button?

I have a list code but it didn't get further)
<?
include("connect.phtml");
$r= mysql_query("SELECT name_goods FROM goods")
or die ("!1");
echo "<select name='product'>";
while($row=mysql_fetch_array($r))
{
echo "<option value='".$row['name_goods']."'>".$row['name_goods']."</option>";
}
mysql_close();
?>
You should put your name_goods id into your option value instead of the name.
Then you will need to insert a $_POST['product'] (which will be the selected value) to your database with the appropriated query.
Something like :
$good_id = $_POST['product']
$query = $pdo->prepare("INSERT INTO table(good_id) VALUES (".$good_id.")");
$query->execute();

Can't check which check list is checked

I'm trying to delete multiple pictures using checkbox item. But somehow pictures are not deleted from database.
the coderuns without mistake. Page is being redirected but the delete query is not executed.
I believe there is somethong to do with passing picture id to query $List[1] but i really can't understand what.It seems I'm doing everything ok.
Thanks for any help in advance.
That's the code:
<?php
$Connection = mysql_connect( $Host, $User, $Pass ) or die('ERROR: '.mysql_error());
mysql_select_db( $DataBase )or die('ERROR: '.mysql_error());
$Query = "SELECT * FROM pictures WHERE folder_id = ".$FolId.";";
$Picture = mysql_query($Query, $Connection)or die('ERROR: '.mysql_error());
?>
<form name='Photos' method='POST' >
<?php
while($List = mysql_fetch_array($Picture)){
echo "<input type='checkbox' name='photoList[]' value='".$List[1]."'> <span> ".$List[4]."</span>";
}
?>
<input type='submit' name='Delit' value='DELETE' >
</form>
<?php
if(isset($_POST['Delit'])){
foreach($_POST['photoList'] as $item){
$Query="DELETE FROM pictures WHERE picture_id =".$item;
mysql_query($Query, $Connection)or die("ERROR: ".mysql_error());
header('Location: photos.php');
}
}
?>
My guess is that $List[1] doesn't contain your picture_id. It's probably $List[0].
Using fetch_array is not a great way to get data from a DB using SELECT *, as your columns may change position, and an index doesn't clearly say which column you're retrieving.
Try using fetch_assoc instead, to get the column names associated with the data.
<?php
// Change `picture_name` below to the name of the column storing your picture's name
while ($List = mysql_fetch_assoc($Picture)) {
echo "<input type='checkbox' name='photoList[]' value='{$List['picture_id']}'> <span> {$List['picture_name']}</span>";
}
?>
Also, try this for your DELETE logic:
Checking if photoList is set (vs. Delit)
Looping through your photo list and casting the values to (int) to prevent SQL Injection
Concatenating the list of IDs into a comma-delimited list using implode
Doing a DELETE... WHERE IN query, providing the photo ID list - this is much faster than looping through and doing several DELETE... WHERE = statements
Code:
<?php
if (isset($_POST['photoList']) && !empty($_POST['photoList'])) {
$photoIds = array();
foreach ($_POST['photoList'] as $photoId) {
$photoIds[] = (int) $photoId;
}
$photoIds = implode(',', $photoIds);
$Query = "DELETE FROM pictures WHERE picture_id IN ({$photoIds})";
mysql_query($Query, $Connection)or die("ERROR: ".mysql_error());
header('Location: photos.php');
}
?>

PHP not displaying data

Any ideas why this simple php code won't display results when trying to echo the data.
<?php
{
mysql_connect("localhost" , "" , "") or die (mysql_error());
mysql_select_db("") or die(mysql_error());
$pid=intval($_SESSION["User_id"]);
$query = "SELECT `car`, `details`, `price` FROM `Car``";
//executes query on the database
$result = mysql_query ($query) or die ("didn't query");
//this selects the results as rows
$num = mysql_num_rows ($result);
while($row=mysql_fetch_assoc($result))
{
$_SESSION['car'] = $row['car'];
$_SESSION['details'] = $row['details'];
$_SESSION['price'] = $row['price'];
}
}
?>
<?php echo $_SESSION['car']; ?>
<?php echo $_SESSION['details']; ?>
<?php echo $_SESSION['price']; ?>
Just testing at the moment to see if the car, price and details display from the database and they don't seem to.
You missed session_start(); at start of page and change
$query = "SELECT `car`, `details`, `price` FROM `Car``";
^
to
$query = "SELECT `car`, `details`, `price` FROM `Car`";
Are you expecting one or many results for this query ?
If many results, you are saving the last entry in the session.
If only one, just do : $row=mysql_fetch_assoc($result) instead of this while.
Check the query.Try to echo it, copy, paste in MySQL and run it. But you have $pid, have you put it in the query?
$query = "SELECT car, details, price FROM Car WHERE id = $pid ";
I rather remove all backticks since non of those identifiers are reserved keywords.
$query = "SELECT car, details, price FROM Car";

Displaying user's SQL query using PHP

Please can anyone help me with this?
I have 2 tables, location and tickets and what I have built so far is a form in a div that users enter the name of the city or town where they would like to see a live music performance. This form is submitted and an SQL statement is passed querying the location table. In another div, the users search query appears in a box on the screen. What I would like to do next is to write an SQL statement that will lookup the user's query and dynamically display the relevant ticket information from the ticket table based on the location ID.
For example, the user types in 'Newcastle' as their search query, the location table finds the city of Newcastle and displays the user's result in a div called 'tickets'..I would like to display all the fields that correspond with 'Newcastle' from the ticket table.
The locationID is the primary key in the location table and has 3 other column, city, town and postcode.
The ticket table consists of ticketID being the primary key, the locationID being the foreign Key and the other fields i.e venue, tPrice, date and time. I think the problem im having is im not passing through the variable from the users query so that the ticket table can look it up and display the relevant information.
Here is the code for the form:
<div id="search">
<form name="searchForm" id="searchForm" class="searchForm" method="post">
<input type="text" name="citySearch" id="citySearch" class="citySearch" placeholder="Enter name city/town..." autofocus="autofocus" />
<input type="submit" name="ticketSearch" id="ticketSearch" class="ticketSearch" value="Search" />
</form>
</div>
Here is the code to display the user's query:
<div id="locationResult">
<?php
include( 'classes/database_connection.php' );
$cSearch = $_POST['citySearch'];
$sql = "SELECT DISTINCT city FROM location WHERE city = '$cSearch'";
mysql_query($sql) or die (mysql_error());
$queryresult = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_assoc($queryresult)) {
$city = $row['city'];
echo $row["city"];
}
mysql_free_result($queryresult);
mysql_free_result($qResult);
mysql_close($conn);
?>
</div>
</div>
This is where I want to display the ticket results from the ticket table:
<div id="ticketsResults">
<table class="ticketResult" border="0" cellspacing="5">
<tr>
<td><b>Venue</b></td>
<td><b>Price</b></td>
<td><b>Date</b></td>
<td><b>Time</b></td>
<td><b>Street View</b></td>
</tr>
<?php
include( 'classes/database_connection.php' );
$locID = $_POST['locationID'];
$citySearch = $_POST['citySearch'];
$sQL = "SELECT locationID FROM location";
//Here is where I want it to display dynamic information rather than manually type the location
$ticketSQL = "SELECT * FROM ticket NATURAL JOIN location WHERE city = 'Newcastle' ";
mysql_query($sQL) or die (mysql_error());
$qResult = mysql_query($sQL) or die(mysql_error());
mysql_query($ticketSQL) or die (mysql_error());
$result = mysql_query($ticketSQL) or die(mysql_error());
while ($row = mysql_fetch_assoc($result)) {
// $ticketID = $row['ticketID'];
$venue = $row['venue'];
$ticketPrice = $row['tPrice'];
$date = $row['date'];
$time= $row['time'];
echo "<tr>\n";
echo "<td>$venue</td>\n";
echo "<td>&pound$ticketPrice</td>\n";
echo "<td>$date</td>\n";
echo "<td>$time</td>\n";
echo "<td>Click to see</td>\n";
echo "</tr>\n";
}
mysql_free_result($qResult);
mysql_free_result($result);
mysql_close($conn);
?>
</table>
</div>
So basically, I'm wanting an SQL statement that dynamically displays the tickets according to the user's query. Sorry about the copious amount of code! Any help given is greatly appreciated.
Before you do anything else I think you should work on your coding style, specifically your indentation. A quick google search should do the trick. Next look into mysql prepared statements because currently your code is unsafe. Like jordanm said, it is subject to SQL injection.
For example, if someone entered blah' OR 'x'='x as a city name. Your query would become
SELECT DISTINCT city FROM location WHERE city = 'blah' OR 'x'='x';
Basically it allows the user to do naughty things with your query, and you don't want that.
Below is a sample of how you can avoid this using mysql prepared statements:
// basic quick raw example
$mysqli = new mysqli('localhost', 'user', 'password', 'database');
$stmt = $mysqli->prepare('SELECT DISTINCT city FROM location WHERE city = ?');
$stmt->bind_param('s',$city_name);
$stmt->execute();
$stmt->bind_result($city);
while ($stmt->fetch())
{
echo $city;
}
That's all I'm going to leave you with because I feel like to answer the actual question (?) I will need to write the code for you. Goodluck

Inserting Data from dropdown into database with PHP

First I needed a dropdown list that I could update easily so I created a database called
manufacturers where I list manufacturers to be selected in a form.
I finally accomplished this with this code:
<?php
// Connect to the test datbase on localhost
// That's where we created the countries table above
mysql_connect('localhost','##user##','##pass##'); mysql_select_db('wordpress');
// Query the countries table and load all of the records
// into an array.
$sql = 'select * FROM manufacturers';
$res = mysql_query($sql) or die(mysql_error());
while ($rec = mysql_fetch_assoc($res))
$manufacturers[] = $rec;
?>
<form action="select.php" method="post">
<?php
echo '<select name="dropdown">';
foreach ($manufacturers as $c)
{
if ($c['id'] == $_GET['id'])
echo "<option value=\"{$c['meta_id']}\" selected=\"selected\">{$c['meta_value']} </option>\n";
else
echo "<option value=\"{$c['meta_id']}\">{$c['meta_value']}</option>\n";
}
echo '</select>';
?>
<input type="submit" value="Submit" name="submit"/>
</form>
This worked out great I now have a dropdown list that is populated from my
database manufacturers.
Now I need to send this to an existing database call post_meta so that from there I can display the users selection permanently.
I have tried a couple of different options but I am trying to use the following code to send this to my post_meta database.
<?php
$con = mysql_connect("localhost","##user##","##pass##");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("wordpress", $con);
$sql="INSERT INTO wp_postmeta (meta_id, post_id, meta_key, meta_value)
VALUES
('$_POST['meta_id']}','$_POST[post_id]','$_POST[meta_key]','$_POST[meta_value]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
?>
This actually inserts into the database but doesn't record any values.
Please help me figure out what I'm doing wrong.
The proper way to do this is to A: escape all those $_POST superglobals.
and B. Write a query as shown below.
Here's the tabledef for wp_postmeta:
http://codex.wordpress.org/Database_Description#Table:_wp_postmeta
Because meta_id is an auto_increment primary key, you do not provide it, MySQL does.
//$meta_id = mysql_real_escape_string($_POST['meta_id']); <<-- not needed.
$post_id = mysql_real_escape_string($_POST['post_id']);
$meta_key = mysql_real_escape_string($_POST['meta_key']);
$meta_value = mysql_real_escape_string($_POST['meta_value']);
$sql=" INSERT INTO wp_postmeta
(post_id, meta_key, meta_value)
VALUES
('$post_id','$meta_key','$meta_value') "; //<<-- don't forget the quotes!
if ($result = mysql_query($sql)) {
//You can get the new meta_id using:
$new_meta_id = mysql_insert_id($result);
} else {
die ("could not insert ".mysql_error());
}
Do none of your values show up? It looks like you're missing quotes around your key values. For example, shouldn't it be :
$_POST['post_id']
To do a sanity check, just echo your $_POST variables as opposed to doing the insert right away. This will help you figure out if you've got some syntax wrong. Also I'd read Brad's comment and keep it in mind for the future.
Try this query:
$sql="
INSERT INTO wp_postmeta
(meta_id, post_id, meta_key, meta_value)
VALUES
(
'{$_POST['meta_id']}',
'{$_POST['post_id']}',
'{$_POST['meta_key']}',
'{$_POST['meta_value']}'
)
";
And, as people say in comments, this code is very vulnerable, please consider to find better option to pass variables into query.

Categories