I am trying to update 3 tables and insert on 2. The thing is I get errors and I get some tables to update and insert, I am thinking there is a better way to put this. Please give me some wonderful input. Sorry that this is horrible coding. :(
<?php
require 'includes/db_connect.php';
if ( !empty($_POST)) {
// keep track validation errors
$vehiclenumError = null;
$chauffeuridError = null;
// keep track post values
$alias = $_POST['alias'];
$vehiclenum = $_POST['vehiclenum'];
$chauffeurid = $_POST['chauffeurid'];
// validate input
$valid = true;
if (empty($vehiclenum)) {
$vehiclenumError = 'Please select a Vehicle #';
$valid = false;
}
if (empty($chauffeurid)) {
$chauffeuridError = 'Please select a Chauffeur #';
$valid = false;
}
// insert data
if ($valid) {
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO unit_logs (alias,vehiclenum,chauffeurid,status) values (?, ?, ?, 1)";
$sql1 = "INSERT INTO active_units (alias,vehiclenum,chauffeurid,status) values (?, ?, ?, 1)";
$sql2 = "UPDATE ipads SET status='1' WHERE alias=$alias";
$sql3 = "UPDATE vehicles SET active='1' WHERE vehiclenum=$vehiclenum";
$sql4 = "UPDATE chauffeurs SET active='1' WHERE chauffeurid=$chauffeurid";
$q = $pdo->prepare($sql);
$l = $pdo->prepare($sql1);
$x = $pdo->prepare($sql2);
$z = $pdo->prepare($sql3);
$h = $pdo->prepare($sql4);
$q->execute(array($alias,$vehiclenum,$chauffeurid));
$l->execute(array($alias,$vehiclenum,$chauffeurid));
$x->execute(array($alias));
$z->execute(array($vehiclenum));
$h->execute(array($chaffeurid));
Database::disconnect();
header("Location: testing.php");
}
}
?>
<code>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link href="css/bootstrap.min.css" rel="stylesheet">
<script src="js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="span10 offset1">
<div class="row">
<h3>Tablet Check Out</h3>
</div>
<?php
mysql_connect('localhost', 'allen', 'w0wr0cks');
mysql_select_db('wcldb');
$sql = "SELECT alias FROM ipads WHERE status = 0 ORDER BY alias ASC";
$result = mysql_query($sql);
?>
<form class="form-horizontal" action="checkout.php" method="post">
<div class="control-group">
<label class="control-label">Tablet Alias</label>
<div class="controls">
<select name="alias">
<?php
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['alias'] ."'>" . $row['alias'] ."</option>";
} ?>
</select>
</div>
</div>
<?php
mysql_connect('localhost', 'allen', 'w0wr0cks');
mysql_select_db('wcldb');
$sql = "SELECT vehiclenum FROM vehicles WHERE ownertype = 'JKS' AND active = '0' ORDER BY vehiclenum ASC";
$result = mysql_query($sql);
?>
<div class="control-group <?php echo !empty($vehiclenumError)?'error':'';?>">
<label class="control-label">Vehicle #</label>
<div class="controls">
<select name="vehiclenum">
<?php
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['vehiclenum'] ."'>" . $row['vehiclenum'] ."</option>";
}
echo '</select>';
?>
</div>
</div>
<?php
mysql_connect('localhost', 'allen', 'w0wr0cks');
mysql_select_db('wcldb');
$sql = "SELECT chauffeurid FROM chauffeurs WHERE ownertype = 'JKS' AND active='0' ORDER BY chauffeurid ASC";
$result = mysql_query($sql);
?>
<div class="control-group <?php echo !empty($chauffeuridError)?'error':'';?>">
<label class="control-label">Driver #</label>
<div class="controls">
<?php
echo "<select name='chauffeurid'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['chauffeurid'] ."'>" . $row['chauffeurid'] ."</option>";
}
echo '</select>';
?>
</div>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-success">Create</button>
<a class="btn" href="testing.php">Back</a>
</div>
</form>
</div>
</div> <!-- /container -->
</body>
</html>
Related
I am working on a school assignment and I have run into some issues. I have PHP code for a form that, when selected, sends the selected result to a MySQL database and then loops through and displays the results. The only problem is that, instead of showing the selected <option>, it shows all four of the options.
Here is my code:
<?php
include_once (connection.php);
if (($_SERVER["REQUEST_METHOD"] == "POST") && (isset($_POST['card_catalog_form']))) {
$card_name = mysqli_real_escape_string($conn, $_POST['card_name']);
$card_label = mysqli_real_escape_string($conn, $_POST['card_label']);
$insert_card_genre_query = sprintf("INSERT into card_catalog (card_name, card_label) VALUES ('%s', '%s')",
$card_name,
$card_label);
$insert_card_genre = mysqli_query($conn, $insert_card_genre_query) or die (mysqli_error($conn));
$last_record = mysqli_insert_id($conn);
}
$card_genre_query = "SELECT card_genre.genre_id, card_label from `card_genre` order by card_label asc";
$card_genre = mysqli_query($conn, $card_genre_query) or die(mysqli_error($conn));
$get_card_genre_query = "SELECT card_catalog.id, card_catalog.card_name, card_catalog.card_label, card_genre.genre_id from card_catalog right join card_genre on card_catalog.card_label = card_genre.card_label";
$get_card_genre = mysqli_query($conn, $get_card_genre_query) or die(mysqli_error($conn));
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>The Marketplace By The Mana Club</title>
<link rel="stylesheet" type="text/css" href="stylesheets/tmp.css">
</head>
<body>
<?php include(templatestuff/top_of_tmp.php); ?>
<main>
<h1>Products:</h1>
<section>
<ul id="products_list">
<li><b>Product 1: "Jack-In-The-Mox"</b></li>
<li><b>Product Description: "Roll a six-sided die for Jack-in-the-Mox. On a 1, sacrifice Jack-in-the-Mox and lose 5 life. Otherwise, Jack-in-the-Mox has one of the following effects. Treat this ability as a mana source..."</b></li>
<img src="productimages/jackinthemox.jpeg" alt="Jack In The Mox"/>
</ul>
</section>
<div>
<h2>What Card Are You Looking For?</h2>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post" enctype="multipart/form-data">
<fieldset>
<p><b>What's The Card Name? <input type="text" name="card_name"></b></p>
<p>
<p><b>Card Type:</b></p>
<select name="card_genre">
<?php while ($row_card_genre = mysqli_fetch_assoc($card_genre)) { ?>
<option value="<?php echo $row_card_genre['genre_id'];?>"><?php echo $row_card_genre['card_label'];?></option>
<?php } ?>
</select>
</p>
<p><input type="submit"></p>
<input type="hidden" name="card_catalog_form">
</fieldset>
</form>
<?php
if ($last_record) {
echo "<p><b>You just created form query #" . $last_record ."</b><p>";
}
?>
<p>You are submitting your form at
<?php
date_default_timezone_set('America/New_York');
echo date('g:i a \o\n l, F j, Y');
?>
</p>
</div>
<?php
$query = "SELECT card_catalog.card_name, card_catalog.card_label, card_genre.genre_id FROM card_catalog, card_genre";
$result = mysqli_query($conn, $query) or die(mysqli_error($conn));
while($row = mysqli_fetch_array($result)){
echo $row['card_name']. " - ". $row['genre_id'];
echo "<br />";
}
?>
</main>
<?php include('templatestuff/bottom_of_tmp.php'); ?>
</body>
</html>`
(If you want to see the website that contains the problem, you can go here)
Any help, or constructive criticism, would be greatly appreciated.
Thanks
This might point you in the right direction:
if (isset($_POST['card_genre'])) {
$query = "SELECT card_catalog.card_name, card_catalog.card_label, card_genre.genre_id FROM card_catalog, card_genre WHERE card_genre.genre_id = ?";
$stmt = mysqli_prepare($conn, $query);
$stmt->bind_param('s', $_POST['card_genre']);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
echo $row['card_name']." - ".$row['genre_id'];
echo "<br />";
}
} else {
$query = "SELECT card_catalog.card_name, card_catalog.card_label, card_genre.genre_id FROM card_catalog, card_genre";
$result = mysqli_query($conn, $query) or die(mysqli_error($conn));
while ($row = mysqli_fetch_array($result)) {
echo $row['card_name']." - ".$row['genre_id'];
echo "<br />";
}
}
first of all, there are 3 table in my database which is:-
te_event, te_venue, te_category.
the te_event table display the categoryID, venueID, event description, title, date and price.
the te_venue table having venueID, venueName and location
the te_category having catID and catDesc.
here is the first page that admin need to select an event in order to update.
<!DOCTYPE html>
<html lang="en">
<html>
<head>
<link rel="stylesheet" type="text/css" href="test1.css">
<meta charset = "utf-8">
<title>
</title>
</head>
<body>
<div id="title">
<p><h1>Tyne Events</h1></p>
</div>
<div id="wrapper">
<div id="navbar" >
<ul class="nav">
<li>Home</li>
<li>Find out more</li>
<li>Offer</li>
<li>Credit</li>
<li>Admin</li>
<li>
<form class="formright">
<input type="text" placeholder="Search">
<button type="submit">Search</button>
</form>
</li>
</ul>
</div>
<div id= "detailCenter">
<?php
include "database_conn.php";
$sqlEvent = "SELECT * FROM te_events
INNER JOIN te_venue ON te_events.venueID = te_venue.venueID
INNER JOIN te_category ON te_events.catID = te_category.catID
ORDER by eventTitle ";//select all event record
//query the statement
$event= mysqli_query ($conn , $sqlEvent)
or die (mysqli_error($conn));
?>
<h1>Select Event To Modify</h1>
<table border = "1" cellpadding="10" width=100% >
<thead>
<th>Title</th>
<th>Category</th>
<th>Venue Name</th>
<th>Location</th>
<th>Start Date</th>
<th>End Date</th>
<th>Price</th>
</thead>
<?php
//display all the event record
while ($row = mysqli_fetch_assoc ($event)){
//extract the field
$id = $row ["eventID"];
$title = $row ["eventTitle"];
$desc = $row ["eventDescription"];
$venue = $row ["venueName"];
$location = $row ["location"];
$category = $row ["catDesc"];
$eStart = $row ["eventStartDate"];
$eEnd = $row ["eventEndDate"];
$ePrice = $row ["eventPrice"];
//start a row
echo"<tr>\n";
//output the URL
echo "<td>\n";
echo "<div> <a href = \"allDetails.php?eventID=$id\">
$title</a></div>\n";
echo "</td>\n";
echo "<td>\n";
echo "<div> $category</div>\n";
echo "</td>\n";
echo "<td>\n";
echo "<div> $venue</div>\n";
echo "</td>\n";
echo "<td>\n";
echo "<div> $location</div>\n";
echo "</td>\n";
echo "<td>\n";
echo "<div>$eStart</div> \n";
echo "</td>\n";
echo "<td>\n";
echo "<div>$eEnd</div>\n";
echo "</td>\n";
echo "<td> \n";
echo "<div>$ePrice</div>\n";
echo "</td>\n";
}
?>
</table>
</div>
</body>
</html>
<?php
mysqli_close($conn);
?>
here is the page that admin can edit the event details
<?php
include "database_conn.php";
if(isset($_GET['eventID'])){
$id = $_GET["eventID"]; //get event id
}
else {
header ("Refresh : 3; url=admin.php");//redirect to choose title
die ("Please use the Choose Event Title List");
}
//get event id
$id = $_GET["eventID"];//get event id
//select event
$sqlEvent =" SELECT * FROM te_events
INNER JOIN te_venue ON te_events.venueID = te_venue.venueID
INNER JOIN te_category ON te_events.catID = te_category.catID
WHERE te_events.eventID =".$id;
//excute sql statemente
$event = mysqli_query($conn , $sqlEvent) or die (mysqli_error($conn));
$_GET = mysqli_fetch_assoc($event) or die (mysqli_error($conn));
//extract each field$
$title = $_GET ["eventTitle"];
$desc = $_GET ["eventDescription"];
$venueId = $_GET ["venueID"];
$venue = $_GET ["venueName"];
$location = $_GET ["location"];
$categoryId = $_GET ["catID"];
$category = $_GET ["catDesc"];
$eStart = $_GET ["eventStartDate"];
$eEnd = $_GET ["eventEndDate"];
$ePrice = $_GET ["eventPrice"];
?>
<!DOCTYPE html>
<html lang="en">
<html>
<head>
<link rel="stylesheet" type="text/css" href="test1.css">
<meta charset = "utf-8">
<title>
</title>
</head>
<body>
<div id="title">
<p><h1>Tyne Events</h1></p>
</div>
<div id="wrapper">
<div id="navbar" >
<ul class="nav">
<li>Home</li>
<li>Find out more</li>
<li>Offer</li>
<li>Credit</li>
<li>Admin</li>
<li>
<form class="formright">
<input type="text" placeholder="Search">
<button type="submit">Search</button>
</form>
</li>
</ul>
</div>
<div id= "detailCenter">
<form id="updateEventDetail" method ="get" action ="updateEventDetail.php">
<fieldset>
<legend>Event details</legend>
<div><p>
<input type ="hidden" name ="eventID" value="<?=$eventID?>"/>
</p></div>
<div><p>
<label class="field" for="eTitle">Event title</label>
<input type ="text" name ="eventTitle" value="<?=$title?>"/>
</p></div>
<div><p>
<label class="field" for="cat">Category</label>
<?php
$sqlCategory ="SELECT DISTINCT catDesc FROM te_category ORDER BY 1";
//query sqlVenue
$rsCategory = mysqli_query ($conn ,$sqlCategory)
or die ("SQL ERROR :".mysqli_error($conn));
//create select item
echo"<select name=\"catDesc\">\n";
//iterate venue record
while ($_GET = mysqli_fetch_assoc($rsCategory)){
//populate select item
$category = $_GET[catDesc]; //get each venueName record
if($category==$category)
echo "<option value =\"$category\" selected>
$category</option>\n";
else{
echo "<option value =\"$venue\">
$category</option>\n";
}
}
echo"</select>\n";
?>
</p></div>
<div><p>
<label class="field" for="desc">Description</label>
<textarea style="resize:none" name="eventDescription" rows="10" cols="40" value="<?=$desc?>"><?=$desc?> </textarea>
</p></div>
<div>
<p>
<label class ="field" for="venue">Venue</label>
<?php
$sqlVenue ="SELECT DISTINCT venueName FROM te_venue ORDER BY 1";
//query sqlVenue
$rsVenue = mysqli_query ($conn ,$sqlVenue)
or die ("SQL ERROR :".mysqli_error($conn));
//create select item
echo"<select name=\"venueName\">\n";
//iterate venue record
while ($_GET = mysqli_fetch_assoc($rsVenue)){
//populate select item
$eVenue = $_GET[venueName]; //get each venueName record
if($eVenue==$venueName)
echo "<option value =\"$eVenue\" selected>
$eVenue</option>\n";
else{
echo "<option value =\"$venue\">
$eVenue</option>\n";
}
}
echo"</select>\n";
?>
</p>
</div>
<div><p>
<label class="field" for="location">Location</label>
<?php
$sqlLocation ="SELECT DISTINCT location FROM te_venue ORDER BY 1";
//query sqlLocation
$rsLocation = mysqli_query ($conn ,$sqlLocation)
or die ("SQL ERROR :".mysqli_error($conn));
//create select item
echo"<select name=\"location\">\n";
//iterate venue record
while ($_GET = mysqli_fetch_assoc($rsLocation)){
//populate select item
$eLocation = $_GET[location]; //get each location record
if($eLocation==$location)
echo "<option value =\"$eLocation\" selected>
$eLocation</option>\n";
else{
echo "<option value =\"$location\">
$eLocation</option>\n";
}
}
echo"</select>\n";
?>
</p></div>
<div><p>
<label class="field" for="sDate">Event Start Date</label>
<input name="eventStartDate" type="date" value="<?=$eStart?>"/>
</p></div>
<div><p>
<label class="field" for="eDate">Event End Date</label>
<input name="eventEndDate" type="date" value="<?=$eEnd?>"/>
</p></div>
<div><p>
<label class="field" for="ePrice">Event Price</label>
<input type="text" name="eventPrice" value="<?=$ePrice?>"readonly/>
</p></div>
<div><p>
<input type="submit" id="floatright" value="Update Event"/>
</p></div>
</fieldset>
</form>
</div>
</body>
</html>
<?php
mysqli_close($conn);
?>
the following code shows updatedetail.php
<?php
include "database_conn.php";
if(isset($_GET['eventID'])){
$id = $_GET["eventID"]; //get event id
}
//get all data submited
$id = $_GET ["eventID"];
$title = $_GET ["eventTitle"];
$desc = $_GET ["eventDescription"];
$venue = $_GET ["venueName"];
$location = $_GET ["location"];
$category = $_GET ["catDesc"];
$eStart = $_GET ["eventStartDate"];
$eEnd = $_GET ["eventEndDate"];
$ePrice = $_GET["eventPrice"];
$sqlUpdateEvent = " UPDATE te_event SET
eventTitle = '$title'
eventDescription = '$desc'
catDesc = '$category'
venueName = '$venue'
location = '$location'
eventStartDate = '$eStart'
eventEndDate = '$eEnd'
eventPrice = '$ePrice'
WHERE eventID = $id";
mysqli_query ($conn , $sqlUpdateEvent)
or die ("SQL ERROR :".mysqli_error($conn));
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>update mvie comfirmmation</title>
<meta charset="utf-8">
</head>
<body>
<h1>update mvoie detials</h1>
<?php
echo "Title : $eventTitle \n";
echo "Category : $catDesc \n";
echo "Description : $eventDescription \n";
echo "Venue : $venueName \n";
echo "Location : $location \n";
echo "Start Date : $eventStartDate \n";
echo "End Date : $eventEndDate \n";
echo "Price : $eventPrice \n";
if(mysqli_affected_rows($conn)>0)
echo "<p> Event update successfully </p>\n";
else
echo "<p> Update Fail</p>\n";
?>
Choose Event
</body>
</html>
<?php
mysqli_close($conn);
?>
the error i get is
SQL ERROR :You have an error in your SQL syntax; check the manual that
corresponds to your MariaDB server version for the right syntax to use
near 'eventDescription = 'The PLAYHOUSE Whitley Bay is delighted to
announce that Litt' at line 3
i edited my question by adding some code
i hopes it helps
thank you for helping.
Your each columns are missing comma separators(,) in your query, so add them like below:-
$sqlUpdateEvent = "UPDATE te_event SET eventTitle = '$title', eventDescription = '$desc',catDesc = '$category',venueName = '$venue',location = '$location',eventStartDate = '$eStart',eventEndDate = '$eEnd',eventPrice = '$ePrice' WHERE eventID = $id";
Suggestion:- Your query is open to SQL Injection, so try to read about prepared statements and use them.
Code enhancement:-
<?php
include "database_conn.php";
if(isset($_GET['eventID']) && isset($_GET["eventTitle"]) && isset($_GET["eventDescription"]) && isset($_GET["venueName"]) && isset($_GET["location"]) && isset($_GET["catDesc"]) && isset($_GET["eventStartDate"]) && isset($_GET["eventEndDate"]) && isset($_GET["eventPrice"]) ){
$id = $_GET["eventID"];
$title = $_GET["eventTitle"];
$desc = $_GET["eventDescription"];
$venue = $_GET["venueName"];
$location = $_GET["location"];
$category = $_GET["catDesc"];
$eStart = $_GET["eventStartDate"];
$eEnd = $_GET["eventEndDate"];
$ePrice = $_GET["eventPrice"];
$sqlUpdateEvent = " UPDATE te_event SET eventTitle = '$title',eventDescription = '$desc',catDesc = '$category',venueName = '$venue',location = '$location',eventStartDate = '$eStart',eventEndDate = '$eEnd',eventPrice = '$ePrice' WHERE eventID = $id";
mysqli_query ($conn , $sqlUpdateEvent) or die ("SQL ERROR :".mysqli_error($conn));
}else{
echo "all data is required";
}
?>
You are not using comma here is the query
$sqlUpdateEvent = " UPDATE te_event SET
eventTitle = '$title',
eventDescription = '$desc',
catDesc = '$category',
venueName = '$venue',
location = '$location',
eventStartDate = '$eStart',
eventEndDate = '$eEnd',
eventPrice = '$ePrice'
WHERE eventID = $id";
I want to update 3 fields in a row in 3 columns but I don't know how to do it. I already searched google and searcedh here but couldn't find any solution for it. I want to change title, paragraph and category of a blog post using $_GET using this way:
<?php
$id = $_GET['id'];
?>
<div class="middle">
<div class="content" style="width:100%;">
<div class="context" style="width:100%">
<?php
if(isset($_POST['submit'])){
$title = $_POST['title'];
$txt = $_POST['txt'];
$query = ("UPDATE tbl_post SET title='$title' WHERE id=$id");
$query = ("UPDATE tbl_post SET txt='$txt' WHERE id=$id");
when I use only one of $_title or $_txt, it works. But I couldn't find a way to update both fields together and couldnt update category selection.
full code of update.php page :
<?php require_once("config.php"); ?>
<?php require_once("header.php"); ?>
<?php
$id = $_GET['id'];
?>
<div class="middle">
<div class="content" style="width:100%;">
<div class="context" style="width:100%">
<?php
if(isset($_POST['submit'])){
$title = $_POST['title'];
$txt = $_POST['txt'];
$query = ("UPDATE tbl_post SET title='$title' WHERE id=$id");
$query = ("UPDATE tbl_post SET txt='$txt' WHERE id=$id");
$query = ("UPDATE tbl_post SET cat='$cat' WHERE id=$id");
mysql_query($query,$con);
header("location:insert.php");
exit();
}
?>
<form action="" method="post">
<?php
$id = $_GET['id'];
$query = "SELECT * FROM `tbl_post` WHERE(id=$id)";
$res = mysql_query($query,$con);
while($rows = mysql_fetch_array($res,MYSQL_ASSOC)){
?>
<p>عنوان مطلب</p>
<input type="text" name="title" style="width:200px; border:1px solid #8C8C8C" value="<?php echo $rows['title'] ?>">
<p>محتوای پست</p>
<textarea name="txt" style="width:300px"><?php echo $rows['txt'] ?></textarea>
<div class="clear"></div>
<?php } ?>
<p>دسته بندی</p>
<select name="cat" style="width:200px">
<?php
$query = "SELECT * FROM `tbl_cat` ORDER BY `id` ASC";
$res = mysql_query($query,$con);
while($rows = mysql_fetch_array($res,MYSQL_ASSOC)){
?>
<option value="<?php echo $rows ['id'] ?>"><?php echo $rows ['name'] ?></option>
</li>
<?php } ?>
</select>
<input type="submit" name="submit" class="" value="ثبت در دیتابیس" style="width:200px; margin-top:15px;">
</form>
</div>
</div>
</div>
<?php require_once("footer.php"); ?>
and insert.php :
<?php require_once("config.php"); ?>
<?php require_once("header.php"); ?>
<div class="middle">
<div class="content" style="width:100%;">
<div class="context" style="width:100%">
<?php
if(isset($_POST['submit'])){
$title = $_POST['title'];
$cat = $_POST['cat'];
$txt = $_POST['txt'];
echo 'title = '.$title.'<br>'.'category ='.$cat.'<br>'.'txt = '.$txt;
$query = "INSERT INTO tbl_post(`title`,`txt`,`cat_id`) VALUES ('$title','$txt','$cat')";
mysql_query($query,$con);
header("location:insert.php");
exit();
}
?>
<form action="" method="post">
<p>عنوان مطلب</p>
<input type="text" name="title" style="width:200px; border:1px solid #8C8C8C;">
<p>دسته بندی</p>
<select name="cat" style="width:200px">
<?php
$query = "SELECT * FROM `tbl_cat` ORDER BY `id` ASC";
$res = mysql_query($query,$con);
while($rows = mysql_fetch_array($res,MYSQL_ASSOC)){
?>
<option value="<?php echo $rows ['id'] ?>"><?php echo $rows ['name'] ?></option>
</li>
<?php } ?>
</select>
<p>محتوای پست</p>
<textarea name="txt" style="width:300px"></textarea>
<div class="clear"></div>
<input type="submit" name="submit" class="" value="ثبت در دیتابیس" style="width:200px; margin-top:15px;">
</form>
</div>
</div>
</div>
<?php require_once("footer.php"); ?>
Combine all the fields into a single query:
$title = $_POST['title'];
$txt = $_POST['txt'];
$cat = $_POST['cat'];
$query = "UPDATE tbl_post SET title='$title', txt = '$txt', cat = '$cat' WHERE id = $id";
Also, you should switch to parametrized queries instead of substituting into the SQL; this means using PDO or mysqli. Otherwise you need to escape the input data. See
How can I prevent SQL injection in PHP?
i want to delete a table row from my database with MySQL and PHP. I have searched on the internet and I can't figure out what I'm doing wrong. I have the feeling I'm close.
If I go over the delete link there is a link showing with the ID number of the row to delete. But if I click it, it isn't working.
This is my code for admin.php
<?php
if(!isset($_COOKIE['E2ingelogd'])) {
header("location:../../index.php");
}
$username = "root";
$password = "";
$hostname = "localhost";
$dbhandle = mysql_connect($hostname, $username, $password) or die("Kan niet inloggen");
$selected = mysql_select_db("login", $dbhandle);
if(isset($_POST['team'])){
$team = $_POST['team'];
$ID = $_POST['id'];
$query = mysql_query("SELECT * FROM e2teams WHERE Team='$team' and ID='$ID'");
if(mysql_num_rows($query) > 0 ) { //check if there is already an entry for that username
echo "$team bestaat al!";
}
else{
mysql_query("INSERT INTO e2teams (Team) VALUES ('$team')");
header("location:e2admin.php");
}
}
mysql_close();
?>
<html><head>
<link href='http://fonts.googleapis.com/css?family=Montserrat' rel='stylesheet' type='text/css'>
<link href="../css/layout.css" rel="stylesheet" type="text/css"></head>
<body>
<div class="wrapper">
<div class="header">
<div class="logo"><img height="140" src="../images/boyslogo.png"> </div>
<div class="titelpagina">Vroomshoopse Boys E2 admin panel</div>
<div class="uitloggen">Uitloggen</div>
</div>
<div class="content">
<div class="teamstoevoegenvak">
<div class="titelbalk">
<h1>Voeg teams toe</h1>
<form style="border:0px; margin:0px; padding:0px"; action="e2admin.php" method="POST">
<input width="400" maxlength="400" type="text" name="team" placeholder="Team naam" /><br>
<input type="submit" value="Toevoegen" />
</form></div>
</div>
<div clas="toegevoegdeteamsvak">
<div class="titelbalktoege">
<h1>Toegevoegde teams</h1>
</div>
<div class="deteams">
<?php
$table = "e2teams";
$sql = "SELECT * FROM e2teams";
$result = mysql_query($sql, $dbhandle);
if(mysql_num_rows($result) > 0){
$team = array();
while($row = mysql_fetch_array($result)) {
echo "<table><tr><td class='styled-td'>";
echo $row['Team']. '</td><td></td><td>Bewerk</td><td><a href="delete.php?del='.$row['ID'].'">Delete<br>';
echo "</td></tr></table>";
$team = $row['Team'];
}
}
mysql_data_seek($result, 0);
?>
</div>
</div>
</div>
<div id="volgendewedstrijd"> <form action="" method="post">
<select name="dropdown">
<?php
mysql_data_seek($result, 0);
if(mysql_num_rows($result) > 0){
while($row = mysql_fetch_array($result)) {
echo '<option value="">' . $row['Team'] . '</option>';
}
}
?>
</select>
</form></div>
</div>
</body>
</html>
The piece of code where the delete is, is this:
if(mysql_num_rows($result) > 0){
$team = array();
while($row = mysql_fetch_array($result)) {
echo "<table><tr><td class='styled-td'>";
echo $row['Team']. '</td><td></td><td>Bewerk</td><td><a href="delete.php?del='.$row['ID'].'">Delete<br>';
echo "</td></tr></table>";
$team = $row['Team'];
}
}
mysql_data_seek($result, 0);
?>
And this is my delete.php:
<?php
if(!isset($_COOKIE['E2ingelogd'])) {
header("location:../../index.php");
}
$username = "root";
$password = "";
$hostname = "localhost";
$dbhandle = mysql_connect($hostname, $username, $password) or die("Could not connect to database");
$selected = mysql_select_db("login", $dbhandle);
mysql_query("DELETE FROM e2teams WHERE ID = $_GET[id]");
echo "Team is deleted";
header('location: e2admin.php');
?>
What am I doing wrong?
You are using del as a param in the link
<a href="delete.php?del='.$row['ID'].'">Delete<br>
This needs to be closed as
Delete<br>
And in the delete script you need to get it as
$id = (int)$_GET["del"];
and use in the query as
mysql_query("DELETE FROM e2teams WHERE ID = $id");
This:
mysql_query("DELETE FROM e2teams WHERE ID = $_GET[id]");
Should be:
mysql_query("DELETE FROM e2teams WHERE ID = ".$_GET['del']."");
Because of:
<a href="del.php?del='.$row['ID'].'"> //the get var name is: del
You can access a variable inside a array between quotes:
Change the following line
mysql_query("DELETE FROM e2teams WHERE ID = $_GET[id]");
to
mysql_query("DELETE FROM e2teams WHERE ID = " . $_GET['id']);
This is a security risk and you are acceptable to SQL injections. Please google: "php sql injections".
Dear Friend i have two function and maybe i might have more in the future but the point is that i want when a user searches for hotel based on postal code on the same text field the function
hotel_by_postel_code($textvalue) should be called and when i search based on country then the function
hotel_by_country($textvalue) should be called. the following is the code that should displays the result however it is not displayong the result as it should at all.
<?php require_once("includes/header.php");?>
<?php require_once("includes/connection.php")?>
<?php
if(isset($_POST['submit'])){
$message ="";
$textvalue = $_POST['search'];
if(empty($allhotels = hotel_by_postel_code($textvalue)) || empty($allhotels = hotel_by_country($textvalue))){
$message = "There is no record in the database";
}
}else{
$allhotels = select_all_hotels();
}
?>
<div class="cBoth"></div>
<div id="sep"></div>
<div id="mainContentSection" class="Calign">
<div id="detaillist">
<div id="searching" class="Calign">
<form action="list2.php" method="POST" id="searchForm">
<fieldset>
<input type="text" name="search" />
<input type="submit" name ="submit" value="Search" /></fieldset>
</form>
</div><!--End of searching-->
<?php
if(isset($message)){
echo"<div id=\"listtitle\">";
echo"<h2>".$message."</h2>";
echo"</div>";//End of listtitle div
}else{
echo"<div id=\"listtitle\">";
echo"<h2>Property Name</h2> <h2>Location</h2> <h2>Guest Rating</h2><h2>Hotel Rank</h2><h2>Per night</h2>";
echo"</div>";
}
?><!--End of listtitle-->
<div class="cBoth"></div>
<?php
$i=0;
while($hotels_set = mysql_fetch_array($allhotels)){
$room_rate = rateforhotel($hotels_set['hotel_id']);
if(!empty( $hotels_set['hotel_name']) && ($room_rate['hotel_id'] == $hotels_set['hotel_id'] ) ){
if($i % 2 == 0) { echo "<div id=\"innerlisteven\">"; }
else
{
echo"<div id=\"innerlistodd\">";
}
echo"<h2>". $hotels_set['hotel_name'] ."</h2>";
echo"<h2>". $hotels_set['country'] ."</h2>";
if(!intval($hotels_set['star'])){
echo"<h2>". $hotels_set['star'] ."</h2>";
}else{
echo"<h2>". $hotels_set['star'] . "<img src=\"img/repetimg/star.png\"/></h2>";
}
echo"<h2>". $hotels_set['star'] . "</h2>";
echo"<h2>". $room_rate['rate'] . "</h2>";
echo"</div>";
$i++;
}//end of if()
}//end of hotel while
mysql_close($con);
?>
</div><!--End of details-->
<div id="advertlisting">
<div id="search">search menu</div>
</div><!--End of adverts left-->
</div><!--End of end of maincontent-->
<div class="cBoth"><!-- clear Both--></div>
<?php require_once("includes/footer.php"); ?>
and the following code is the function itself
function hotel_by_country($country){
global $connection;
$query = "SELECT * FROM Hotels WHERE country ='{$country}'";
$hotel_set = mysql_query($query,$connection);
confirm_query($hotel_set);
return $hotel_set;
}
function hotel_by_postel_code($postal){
global $connection;
$query = "SELECT * FROM Hotels WHERE hotel_postal_code ='{$postal}'";
$hotel_set = mysql_query($query,$connection);
confirm_query($hotel_set);
return $hotel_set;
}
function select_all_hotels(){
global $connection;
$query = "SELECT *
FROM Hotels";
$hotel_set = mysql_query($query,$connection);
confirm_query($hotel_set);
return $hotel_set;
}
You're missing closing (right) brackets ) of the empty functions - one before the OR and one at the end of the condition). Change:
if(empty($allhotels = hotel_by_postel_code($textvalue) OR empty($allhotels = hotel_by_country($textvalue))
to:
if(empty($allhotels = hotel_by_postel_code($textvalue)) OR empty($allhotels = hotel_by_country($textvalue))){
Next, I would break this line into a few lines:
$allhotels1 = hotel_by_postel_code($textvalue);
$allhotels2 = hotel_by_country($textvalue);
echo "allhotels1 = $allhotels1; allhotels1 = $allhotels1\n";//for debug
if(empty($allhotels1) OR empty($allhotels2){...
and one last thing - are you sure it should be OR and not AND ?
if(is_numermic($textvalue))
hotel_by_postel_code($textvalue)
else
hotel_by_country($textvalue)
I think your problem lies in this code
if(empty($allhotels = hotel_by_postel_code($textvalue)) || empty($allhotels = hotel_by_country($textvalue))){
$message = "There is no record in the database";
}
First you fill $allhotels with hotel_by_postel_code($textvalue). Then you overwrite it with $allhotels = hotel_by_country($textvalue).
Also, you should replace the || with && because you only want the message when both functions return no values.
Try
$allhotels = hotel_by_postel_code($textvalue);
if(empty($allhotels)) {
$allhotels = hotel_by_country($textvalue);
if(empty($allhotels)) {
$message = "There is no record in the database";
}
}
After many trail and error i was able to come to the solution and the following is the best option i found maybe in the future someone my come up with the same problem. one thing to keep in mind is that the options in IF and Else can easily be moved into a function on separate file. and i also added one more Html menu to select the type of option i am search for in this case it is the filter menu.
<?php
error_reporting(E_ALL);
ini_set('display_errors','1');?>
<?php require_once("includes/header.php");?>
<?php require_once("includes/connection.php")?>
<?php
if(isset($_POST['search']) && $_POST['search']!= "") {
if($_POST['filter'] == "HotelName"){
$search = $_POST['search'];
$sqlquery = "SELECT * FROM Hotels WHERE hotel_name LIKE '%$search%' OR description LIKE '%$search%'";
$allhotels = mysql_query($sqlquery, $connection) or die("Sorry Something wrong".mysql_error());
}else if($_POST['filter'] == "country"){
$search = $_POST['search'];
$sqlquery = "SELECT * FROM Hotels WHERE country LIKE '%$search%' OR hotel_address LIKE '%$search%'";
$allhotels = mysql_query($sqlquery, $connection) or die("Sorry Something wrong".mysql_error());
}else if($_POST['filter'] == "Postal"){
$search = $_POST['search'];
$sqlquery = "SELECT * FROM Hotels WHERE hotel_postal_code LIKE '%$search%'";
$allhotels = mysql_query($sqlquery, $connection) or die("Sorry Something wrong".mysql_error());
}
}
?>
<div class="cBoth"></div>
<div id="sep"></div>
<div id="mainContentSection" class="Calign">
<div id="detaillist">
<div id="searching" class="Calign">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST" id="searchForm">
<fieldset>
<input type="text" name="search" />
<select name="filter">
<option value="HotelName">Hotel Name</option>
<option value="country">Country</option>
<option value="Postal">Postal Code</option>
</select>
<input type="submit" name ="submit" value="Search" />
</fieldset>
</form>
</div><!--End of searching-->
<div id="listtitle">
<h2>Property Name</h2> <h2>Location</h2><h2>Hotel Rank</h2><h2>Guest Rating</h2><h2>Per night</h2>
</div><!--End of listtitle-->
<div class="cBoth"></div>
<?php
if(!isset($allhotels)){
$allhotels = select_all_hotels();
}
$i=0;
while($hotels_set = mysql_fetch_array( $allhotels)){
$room_rate = rateforhotel($hotels_set['hotel_id']);
if(!empty( $hotels_set['hotel_name']) && ($room_rate['hotel_id'] == $hotels_set['hotel_id'] ) ){
if($i % 2 == 0) { echo "<div id=\"innerlisteven\">"; }
else
{
echo"<div id=\"innerlistodd\">";
}
echo"<h2><a href=\"desti_list.php?details=" . urlencode($hotels_set["hotel_id"]).
"\">" . $hotels_set['hotel_name'] ."</a></h2>";
echo"<h2>". $hotels_set['country'] ."</h2>";
if(!intval($hotels_set['star'])){
echo"<h2>". $hotels_set['star'] ."</h2>";
}else{
echo"<h2>". $hotels_set['star'] . "<img src=\"img/repetimg/star.png\"/></h2>";
}
echo"<h2>". $hotels_set['star'] . "</h2>";
echo"<h2>". $room_rate['rate'] . "</h2>";
echo"</div>";
$i++;
/*
echo"<h3><a href=\"desti_list.php?details=" . urlencode($hotels_set["hotel_id"]).
"\">Find Out More</a></span></h3>";
*/
}//end of if()
}//end of hotel while
mysql_close($connection);
?>
</div><!--End of details-->
<div id="advertlisting">
<div id="search">search menu</div>
</div><!--End of adverts left-->
</div><!--End of end of maincontent-->
<div class="cBoth"><!-- clear Both--></div>
<?php require_once("includes/footer.php"); ?>