I am having a problem.
I am creating a script that allows a person to select a record by it's primary ID and then delete the row by clicking a confirmation button.
This is the code with the form:
"confirmdelete.php"
<?php
include("dbinfo.php");
$sel_record = $_POST[sel_record];
//SQL statement to select info where the ID is the same as what was just passed in
$sql = "SELECT * FROM contacts WHERE id = '$sel_record'";
//execute SELECT statement to get the result
$result = mysql_query($sql, $db) or die (mysql_error());//search dat db
if (!$result){// if a problem
echo 'something has gone wrong!';
}
else{
//loop through and get dem records
while($record = mysql_fetch_array($result)){
//assign values of fields to var names
$id = $record['ID'];
$email = $record['email'];
$first = $record['first'];
$last = $record['last'];
$status = $record['status'];
$image = $record['image'];
$filename = "images/$image";
}
$pageTitle = "Delete a Monkey";
include('header.php');
echo <<<HERE
Are you sure you want to delete this record?<br/>
It will be permanently removed:</br>
<img src="$filename" />
<ul>
<li>ID: $id</li>
<li>Name: $first $last</li>
<li>E-mail: $email</li>
<li>Status: $status</li>
</ul>
<p><br/>
<form method="post" action="reallydelete.php">
<input type="hidden" name="id" value="$id">
<input type="submit" name="reallydelete" value="really truly delete"/>
<input type="button" name="cancel" value="cancel" onClick="location.href='index.php'" /></a>
</p></form>
HERE;
}//close else
//when button is clicked takes user back to index
?>
and here is the reallydelete.php code it calls upon
<?php
include ("dbinfo.php");
$id = $_POST[id];//get value from confirmdelete.php and assign to ID
$sql = "SELECT * FROM contacts WHERE id = '$id'";//where primary key is equal to $id (or what was passed in)
$result=mysql_query($sql) or die (mysql_error());
//get values from DB and display from db before deleting it
while ($row=mysql_fetch_array($result)){
$id = $row["id"];
$email = $row["email"];
$first= $row["first"];
$last = $row["last"];
$status = $row["status"];
include ("header.php");
//displays here
echo "<p>$id, $first, $last, $email, $status has been deleted permanently</p>";
}
$sql="DELETE FROM contacts WHERE id = '$id'";
//actually deletes
$result = mysql_query($sql) or die (mysql_error());
?>
The problem is that it never actually ends up going into the "while" loop
The connection is absolutely fine.
Any help would be much appreciated.
1: It should not be $_POST[id]; it should be $_POST['id'];
Try after changing this.
if it does not still work try a var_dump() to your results to see if it is returning any rows.
if it is empty or no rows than it is absolutely normal that it is not working.
and make sure id is reaching to your php page properly.
Ok as you are just starting, take care of these syntax, and later try switching to PDO or mysqli_* instead of mysql..
Two major syntax error in your code:
Parameters must be written in ''
E.g:
$_POST['id'] and not $_POST[id]
Secondly you must use the connecting dots for echoing variables:
E.g:
echo "Nane:".$nane; or echo $name; but not echo "Name: $name";
Similarly in mysql_query
E.g:
$sql = "SELECT * FROM table_name WHERE id="'.$id.'";
I hope you get it..take care of these stuff..
Related
I need a help with my code; somehow my code creates two rooms (it inserts two rows into a table at once), I don't know why.
(I need to require an id for every insert to know in which house we create a new room. My database contains table 'house' and table 'room'. Table 'room' has a field 'house_id' which is a foreign key with a field 'id' in table 'house'.)
That is my php page:
<?php
// turn autocommit off
mysqli_autocommit($con, FALSE);
// fetch the houses so that we have access to their names and id
$query = "SELECT name, id
FROM house";
$result = mysqli_query($con, $query);
// check query returned a result
if ($result === false) {
echo mysqli_error($con);
} else {
$options = "";
// create an option
while ($row = mysqli_fetch_assoc($result)) {
// $options .= "".$row['name']."";
$options .= "<option value='".$row['id']."'>";
$options .= $row['name'];
$options .= "</option>";
}
}
include('templates/add_room.html');
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$price = mysqli_real_escape_string($con, $_POST["price"]);
$house = mysqli_real_escape_string($con, $_POST["house_id"]);
$query = "INSERT INTO room (price, house_id)
VALUES ('$price', '$house')";
// run the query to insert the data
$result = mysqli_query($con, $query);
// check if the query went ok
if ( $con->query($query) ) {
echo "<script type= 'text/javascript'>alert('New room created successfully with the id of {$con->insert_id}');</script>";
mysqli_commit($con);
} else {
echo "There was a problem:<br />$query<br />{$con->error}";
mysqli_rollback($con);
}
}
//free result set
mysqli_free_result($result);
?>
and that is my html template with form:
<h2>Add new room</h2>
<form action='' method='POST'>
<fieldset>
<label for='price'>Price:</label>
<input type='number' name='price'>
</fieldset>
<fieldset>
<label for='house_id'>House:</label>
<select name='house_id' required>
<option value='' disabled selected>Select house</options>
<?php echo $options; ?>
</select>
</fieldset>
<button type='submit'>Add</button>
</form>
It inserts 2 rows because of your using the query function twice:
$result = mysqli_query($con, $query);
// check if the query went ok
if ( $con->query($query) ) {
So you'll need to change that conditional statement to:
if ($result) {
By the way, use a prepared statement, it's safer than real_escape_string():
https://en.wikipedia.org/wiki/Prepared_statement
You are inserting it twice
first here:
// run the query to insert the data
$result = mysqli_query($con, $query);
then here:
// check if the query went ok
if ( $con->query($query) ) {
Remove the first one and you should be fine, or check on the result of the first one and remove the second one.
Not 100% certain, but it looks like you run INSERT query twice. Once here:
$result = mysqli_query($con, $query);
and once a moment later when you try to check for something. you inadvertently use the OOP style when you are apparently trying to check for something
if ( $con->query($query) ) {
Im making a list with names and links to full info about them. So, I've got simple search engine, which searching by the names or specific numbers. I use $_SESSION to get id of the people. The problem is, when there are more than 1 name and Im moving to the page of specific person appears the page of the last person in the list!
So, code of the search engine is:
if(isset($_POST['search'])){
$searchq = $_POST['search'];
$searchq = preg_replace("#[^0-9_a-z A-Z]#i","",$searchq);
$query = mysql_query("SELECT * FROM contract WHERE name LIKE '%$searchq%' OR student_code LIKE '%$searchq%'") or die("could not search");
$count = mysql_num_rows($query);
if($count == 0){
$output = 'There was no such results!';
}
else{
while($row = mysql_fetch_array($query)){
$name = $row['name'];
$student_code = $row['student_code'];
$_SESSION['users_id'] = $row['users_id'];
$output = '<table border ="1"><tr><td>'.$name.' '.$student_code.'
</td>
<td>
<form action="cont.php" method="post">
<label>Look at the contract:</label>
<input type="submit" name="submit" value=">>">
</form>
</td>
</tr>
</table><br \>
And another script in the page file:
$users_id = $_SESSION['users_id'];
$result = mysql_query("SELECT * FROM contract WHERE users_id = $users_id");
while($myrow = mysql_fetch_array($result)){
$output1 =
The way I understood your question is that you have two pages. One page that does the search, and another page that show the "more info" about a specific result.
What you're basically doing in the search is this:
Let's assume you have three results that got Id 1,4,7.
This is what's going to happen in your while loop
Set $name $student_code and $_SESSION['user_id'] ($_SESSION['user_id'] is now 1)
Prepare the first result
Set $name $student_code and $_SESSION['user_id'] ($_SESSION['user_id'] is now 4)
Prepare the second result
Set $name $student_code and $_SESSION['user_id'] ($_SESSION['user_id'] is now 7)
Prepare the third result
As you can see you're always overwriting the session key and therefore only the last one will be available when you get to the "cont.php" page (where I'm guessing the other code is?)
One simple solution would be to bake the id into the form and send it along in the request to the cont.php page. Something like this:
<form action="cont.php" method="post">
<label>Look at the contract:</label>
<input type="submit" name="submit" value=">>">
<input type="hidden" name="user_id" value="' . $row['users_id'] . '">
</form>
And then in the cont.php you simply change this:
$users_id = $_SESSION['users_id'];
to this
$users_id = $_POST['users_id'];
Hope that helps :)
I'm trying to input some values in event.php and store them in an array ($mem). I'm then passing this array in another eventregister.php file where I'm inserting it in MySQL table.
Starting lines in my event.php file:
<?php
session_start();
$slug = $_GET['slug'];
$sess_uid = $_SESSION['id'];
$sess_email = $_SESSION['email'];
$sess_name = $_SESSION['name'];
if(isset($_POST['submit'])&&$_POST['submit']=='register1')
require_once('13/functions/eventregister.php');
?>
In <body>:
...
...
$result = mysql_query("SELECT * FROM event WHERE slug = '".$slug."'");
if ($result == true){
$row=mysql_fetch_assoc($result);
$id=$row['id'];
}
$_SESSION['eventid']=$id;
$_SESSION['eventname']=$row['name'];
$_SESSION['max_members']=$row['members'];
php $mem=array_fill(0,$row['members'],'');?>
<form action="" method="post">
<?php for ($i=0;$i<$row['members']-1;$i++){
echo '<label>TRYST ID of Member '.($i+1).' :</label>';
echo '<input type="text" size="20" name="'.$mem[$i].'"><br>';
}
echo '<button type="submit" id="submit" value="Register" name="register1">Register</button>';?>
</form>
My eventregister.php file:
<?php
session_start();
foreach($_POST['mem'] as $key=>$value){
$value=mysql_real_escape_string($value);
if(strlen($value)==0)
$value="Null";
}
$sess_uid = $_SESSION['id'];
$sess_email = $_SESSION['email'];
$sess_name = $_SESSION['name'];
$e_id=$_SESSION['eventid'];
$e_name=$_SESSION['eventname'];
$e_max_mem=$_SESSION['max_members'];
mysql_query("INSERT INTO eventregister(event_id,event_name,max_number) VALUES('".$e_id."','".$e_name."','".$e_max_mem."')");
$url="events.php?slug=".$slug;
header('Location: ' . $url);
exit;
?>
The page doesn't show any error, redirects are working, its just that no rows get affected in SQL. I'm still in the learning process, hence using the old notations of PHP.
If you look closely at the INSERT statement, you see you have a stray comma at the end. Remove that:
mysql_query("INSERT INTO eventregister(event_id,event_name,max_number)
VALUES('".$e_id."','".$e_name."','".$e_max_mem."')");
You could also see the MySQL error in your server logs. Or call mysql_error to find out more if a query fails.
I also do not see a mysql_connect anywhere.
Your commas and brackets not organised
mysql_query("INSERT INTO eventregister(event_id,event_name,max_number) VALUES('".$e_id."','".$e_name."','".$e_max_mem."')");
I am new to php and programming,, I have been following a tutorial but I've ran into a problem when trying to display the products onto a web page, This is the code am testing
<?php
if (isset($_GET['id'])) {
include "storescripts/connect_to_mysql.php";
$id = preg_replace('#[^0-9]#i', '', $_GET['id']);
$sql = mysql_query("SELECT * FROM products WHERE id='$id' LIMIT 1");
$productCount = mysql_num_rows($sql);
if ($productCount > 0) {
while($row = mysql_fetch_array($sql)){
$product_name = $row["product_name"];
$price = $row["price"];
$details = $row["details"];
$category = $row["category"];
$subcategory = $row["subcategory"];
$date_added = strftime("%b %d, %Y", strtotime($row["date_added"]));
}
} else {
echo "That item does not exist.";
exit();
}
} else {
echo "Data to render this page is missing.";
exit();
}
mysql_close();
?>
When I try to view the page through my browser I get the message "Data to render this page is missing"
I understand that it''s something to do with
if (isset($_GET['id'])) {
And am assuming maybe it's something to do with the 'id' But I cant work out how to fix it. Any pointers and help would be appreciated, sorry if this seems basic but like I said I am new and cant work this problem out. I've been trying all day
Thanks
Obviously, $_GET['id'] isn't set. If your link was something like http://www.example.com/index.php?id=32, it would be set.
Second, do not use GET/POST variables in queries without sanitising them!
And third, don't use mysql_query in the first place, but PDO or mysqli instead
When you see $_GET it's looking for a parameter in the URL. So:
http://localhost/yourphpscript.php?id=123
...is what it's expecting. Some ID must be defined in the URL.
You could try this code:
<?php
if (isset($_GET['id'])){ //Someone submitted a form or just prepended parameter to link
include "storescripts/connect_to_mysql.php"; //Include script with mysql connection
$id = preg_replace('#[^0-9]#i', '', $_GET['id']); //Sanitize input - remove everything besides numbers
$result = mysql_query("SELECT * FROM products WHERE id='$id' LIMIT 1"); //Execute query. Only 1 product because of LIMIT 1
if (mysql_num_rows($result)==1){ //If the product is found
$product = mysql_fetch_assoc($result) ; //Take the product
foreach ($product as $property => $value){ //Go through each property of product
echo "<div> {$property} : {$value} </div>" ;
}
}
} else {?>
<form method="get" action="<?php $_SERVER['PHP_SELF'] ; ?>">
<input type="text" name="id" />
<input type="submit" value="Submit product ID"/>
</form>
<?php
}
?>
Just ask if you have any questions.
learn to track your id. sanitize and check the url sending the id for correct value passed and again in the begining check the value as in
<?php
echo $_GET['id'];
?>
use this to know what it is your id value
using a drop-down list that's populated from database fields, i need to select an option and then delete that from the database. i'm trying to do this by sending the form to a process php page where i pull in the select option from the post array and then delete it from the database and return to the index page.
having issues with getting the array variable from the post array. can anyone help with some code on how to get the variable and then delete the mysql title
<form method="post" action="deleteReview_process.php">
<select name="title">
<?php
while($row = mysql_fetch_array($sql_result)) {
$movieTitle = $row['title'];
?>
<option><?php echo $movieTitle; ?></option>
<?php } ?>
</select>
<input type="submit" name="delete" id="delete" value="delete" />
---- and the process page ---
include 'inc/db.inc.php';
if($_POST['delete']) {
$title = $_POST['title'][$movieTitle]; <------ NOT WORKING
$sql = "DELETE" . $title . "FROM pageTitle";
mysql_query($sql, $conn)
or die("couldn't execute query");
header("Location: http://localhost/cms/index.php");
}
else
{
header("Location: http://localhost/cms/deleteReview.php");
}
Because your SELECT element is named "title," it will be represented as $_POST["title"] when it arrives to the backend script:
$title = $_POST['title'];
Also, your query needs to be corrected:
$sql = "DELETE" . $title . "FROM pageTitle";
Should be:
$sql = "DELETE FROM tableName WHERE title = '{$title}'";
$title is going to be in $_POST['title'] ie. $title = $_POST['title']