Hi I am struggling to see why this isn't updating the database. It reloads the page directed to by the HEADER but does not update the any field. Any help would be grealty appreaciated.
Update Form
<?php
include("../script/dbconnect.php");
include("../script/addprodcat.php");
$post = get_posts($_GET['id']);
if ( isset($_POST['name'], $_POST['description'], $_POST['price'], $_POST['sale'], $_POST['picture'], $_POST['category']) ) {
$errors = array();
$name = trim($_POST['name']);
$description = trim($_POST['description']);
if ( empty($name) ) {
$errors[] = 'You need to supply a title';
} else if ( strlen($name) > 255 ) {
$errors[] = 'Title cannot be longer than 255 characters';
}
if ( empty($description) ) {
$errors[] = 'You need to supply text';
}
if ( empty($price) ) {
$errors[] = 'You need to supply text';
}
if ( empty($sale) ) {
$errors[] = 'You need to supply text';
}
if ( empty($picture) ) {
$errors[] = 'You need to supply text';
}
if (! category_exists('id', $_POST['category']) ) {
$errors[] = 'Category does not exist';
}
if ( empty($errors) ) {
edit_product($_GET['id'], $name, $description, $price, $sale, $picture, $_POST['category']);
header("Location: ../admin/edit_products.php?id={$post[0]['post_id']}");
die();
}
}
?>
<div style="width:100%; height:150px; background-color:white;"><span style="font-family:saxMonoRegular; letter-spacing:2px; display:block; font-size:4.5em; text-align:center; padding-top:15px;"> Edit <?php echo $post[0]['name']; ?> </span></div>
<div class="link" style="width:100%; background-color:#ccc;">
<form action="" method="post">
<?php
if ( isset($errors) && ! empty($errors) ) {
echo '<ul><li>', implode('</li><li>', $errors), '</li></ul>';
}
?>
<label for="name">Title</label>
<input type="text" name="name" value="<?php echo $post[0]['name']; ?>"><br/>
<label for="price">Price</label>
<input type="text" name="price" value="<?php echo $post[0]['price']; ?>"><br/>
<label for="sale">Sale</label>
<input type="text" name="sale" value="<?php echo $post[0]['sale']; ?>"><br/>
<label for="picture">Picture</label>
<input type="text" name="picture" value="<?php echo $post[0]['picture']; ?>"><br/>
<label for="description">Description</label>
<textarea name="description" rows="15" cols="50"><?php echo $post[0]['description']; ?></textarea><br/>
<label for="prod_id">Category</label>
<select name="prod_id">
<?php
foreach ( get_categories() as $category ) {
$selected = ( $category['name'] == $post[0]['name'] ) ? " selected" : '';
?>
<option value="<?php echo $category['id']; ?>" <?php echo $selected; ?>> <?php echo $category['name']; ?></option>
<?php
}
?>
</select><br/>
<input class="button-link" type="submit" value="Edit Post">
</form>
</div>
addprodcat.php
function edit_product($id, $prod_id, $prod_sub_id, $name, $description, $price, $sale, $picture, $category) {
$id = (int) $id;
$prod_id = (int) $prod_id;
$prod_sub_id = (int) $prod_sub_id;
$name = mysql_real_escape_string($name);
$description = mysql_real_escape_string($description);
$price = mysql_real_escape_string($price);
$sale = mysql_real_escape_string($sale);
$picture = mysql_real_escape_string($picture);
$category = (int) $category;
mysql_query("UPDATE `products` SET
`cat_id` = {$category},
`prod_id` = {$prod_id},
`prod_sub_id ` = '{$prod_sub_id}',
`name` = '{$name}',
`description` = '{$description}',
`price` = '{$price}',
`sale` = '{$sale}',
`picture` = '{$picture}'
WHERE `id` = {$id}");
echo mysql_error();
}
Your update form passes only 7 parameters to the edit_products function; this function, however, expects 9.
edit_product($_GET['id'], $name, $description, $price, $sale, $picture, $_POST['category']);
...
function edit_product($id, $prod_id, $prod_sub_id, $name, $description, $price, $sale, $picture, $category)
You need to pass $prod_id and $prod_sub_id as well.
As an extra note, it's worth commenting out any redirects when debugging code as any (non-fatal) errors/warnings that would otherwise be shown are missed.
Number of function parameters differ. The function expects 9 but you provided 7.
This is a common user error that happens in lengthy lines.
Use the coding standard like this:
function edit_product(
$id,
$prod_id,
$prod_sub_id,
$name,
$description,
$price,
$sale,
$picture,
$category
) {
/*function code */
}
Follow same standard when you 'call' the function too.
Related
All I am trying to do is escape html injection into my input text boxes. Am I not using htmlentities correctly?
Code:
<?php
require_once "pdo.php";
// Demand a GET parameter
if ( ! isset($_GET['name']) || strlen($_GET['name']) < 1 ) {
die('Name parameter missing');
} else {
$username = $_GET['name'];
}
// If the user requested logout go back to index.php
if ( isset($_POST['logout']) ) {
header('Location: index.php');
return;
}
$year = isset($_POST['year']) ? $_POST['year'] : '';
$mileage = isset($_POST['mileage']) ? $_POST['mileage'] : '';
$make = isset($_POST['make']) ? $_POST['make'] : '';
$failure = false;
$success = false;
if ( isset($_POST['make']) && isset($_POST['year'])
&& isset($_POST['mileage'])) {
//$year = $_POST['year'];
//$mileage = $_POST['mileage'];
//$make = $_POST['make'];
if ( strlen($make) < 1){
$failure = "Make is Required";
} else {
if (is_numeric($year) and is_numeric($mileage) ){
error_log("year is a number ".$_POST['year']);
error_log("Mileage is a number ".$_POST['mileage']);
$sql = "INSERT INTO autos (make, year, mileage)
VALUES (:make, :year, :mileage)";
$stmt = $pdo->prepare($sql);
$stmt->execute(array(
':make' => $make,
':year' => $year,
':mileage' => $mileage));
$success = "Record Inserted";
} else {
$failure = "Mileage and Year must be numeric";
error_log("year or mileage is not a number year=".$_POST['year']);
error_log("Mileage or year is not a number mileage=".$_POST['mileage']);
}
}
}
if ( isset($_POST['delete']) && isset($_POST['auto_id']) ) {
$sql = "DELETE FROM autos WHERE auto_id = :zip";
$stmt = $pdo->prepare($sql);
$stmt->execute(array(':zip' => $_POST['auto_id']));
}
$stmt = $pdo->query("SELECT make, year, mileage, auto_id FROM autos");
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html>
<head>
<title>Douglas Osborne's Automobile Tracker</title>
</head>
<body>
<table border="0">
<?php
foreach ( $rows as $row ) {
echo "<tr><td>";
echo($row['year']);
echo(" /");
echo("</td><td>");
echo($row['make']);
echo("</td><td>");
echo($row['mileage']);
echo(" miles");
echo("</td><td>");
echo('<form method="post"><input type="hidden" ');
echo('name="auto_id" value="'.$row['auto_id'].'">'."\n");
echo('<input type="submit" value="Del" name="delete">');
echo("\n</form>\n");
echo("</td></tr>\n");
}
?>
<body>
<div class="container">
<h1>
<?php
if ( isset($_REQUEST['name']) ) {
echo "<p>Tracking Autos for ";
echo htmlentities($_REQUEST['name']);
echo "</p>\n";
}
?>
</h1>
<p>
<?php
// Note triple not equals and think how badly double
// not equals would work here...
if ( $failure !== false ) {
// Look closely at the use of single and double quotes
echo('<p style="color: red;">'.htmlentities($failure)."</p>\n");
}
if ( $success !== false ) {
// Look closely at the use of single and double quotes
echo('<p style="color: green;">'.htmlentities($success)."</p>\n");
}
?>
</p>
<form method="post">
<p>Make:
<input type="text" name="make" size="60" value="<?= htmlentities($make) ?>"/>
</p>
<p>Year:
<input type="text" name="year" value="<?= htmlentities($year) ?>"/>
</p>
<p>Mileage:
<input type="text" name="mileage" value="<?= htmlentities($mileage) ?>"/>
</p>
<input type="submit" value="Add">
<input type="submit" name="logout" value="Logout">
</form>
<h2>Automobiles</h2>
<ul>
<p>
</ul>
</div>
</html>
Output wont escape see screenshot:
Adding htmlspecialchars to (make) gave me the result I was looking for. Thanks for anyone's attempt to help me.
I got this form for adding new posts and i can't get it to write to DB. I debugged it as much as i can and when i try to add i don't get any errors but also i don't see the post stored in my DB. Am i missing something? Code:
-This is the form
<form method = "post" action = "vpost.php" enctype="multipart/form-data">
<label>
<h5>Наслов</h5>
<input type="text" name="title" placeholder="Enter title" value = "<?php if(isset($_POST['title'])) { echo $post_title; } ?>">
</label>
<label>
<h5>Адреса</h5>
<input type="text" name="address" placeholder="Enter address" value = "<?php if(isset($_POST['address'])) { echo $post_address; } ?>">
</label>
<hr>
<label>
<h5>Цена</h5>
<input type="number" name="price" placeholder="Enter price" value = "<?php if(isset($_POST['price'])) { echo $post_price; } ?>">
</label>
<hr>
<label>
<h5>Тип</h5>
<input type="text" name="type" placeholder="Enter type" value = "<?php if(isset($_POST['type'])) { echo $post_type; } ?>">
</label>
</div>
<hr>
<div class="user-information-second">
<label>
<h5>Година на градба</h5>
<input type="number" name="year_built" placeholder="Year Built" <?php if(isset($_POST['year_built'])) { echo $post_yearbt; } ?>>
</label>
<hr>
<label>
<h5>Паркинг</h5>
<input type="text" name="parking" placeholder="parking" value = "<?php if(isset($_POST['parking'])) { echo $post_parking; } ?>">
</label>
<hr>
<label>
<h5>Квадратура</h5>
<input type="number" name="sqmeter" placeholder="sqmeter" value = "<?php if(isset($_POST['sqmeter'])) { echo $post_sqmeter; } ?>">
</label>
<br>
<hr>
<label>
<h5>Греење/Ладење</h5>
<input type="text" name="heat" placeholder="Heating" value = "<?php if(isset($_POST['heat'])) { echo $post_heat; } ?>">
</label>
<br>
<hr>
<label>
<h5>Галерија</h5>
<div class="file">
<input type="file" name="image" enctype="multipart/form-data" placeholder="Upload Image">
</div>
</label>
<br>
<hr>
<label>
<button type="submit" id="submit">Внеси Оглас</button>
</label>
</form>
-This is the validation and writing to base file
<?php
include('includes/general.php');
if (isset($_POST['title']) && isset($_POST['address']) && isset($_POST['price']) &&
isset($_POST['type']) && isset($_POST['year_built']) && isset($_POST['parking']) &&
isset($_POST['sqmeter']) && isset($_POST['heat']) && isset($_POST['image'])) {
require("GUMP-master/gump.class.php");
$gump = new GUMP();
$_POST = $gump->sanitize($_POST);
$gump->validation_rules(array(
'title' => 'required|max_len,120|min_len,15',
'address' => 'required|max_len,100|min_len,3',
'price' => 'required',
'type' => 'required',
'year_built' => 'required',
'parking' => 'required',
'sqmeter' => 'required',
'heat' => 'required',
));
$gump->filter_rules(array(
'title' => 'trim|sanitize_string',
'address' => 'trim|sanitize_string',
));
$validated_data = $gump->run($_POST);
if($validated_data === false) {
?>
<center><font color="red" > <?php echo $gump->get_readable_errors(true); ?> </font></center>
<?php
$post_title = $_POST['title'];
$post_address = $_POST['address'];
$post_price = $_POST['price'];
$post_type = $_POST['type'];
$post_yearbt = $_POST['year_built'];
$post_parking = $_POST['parking'];
$post_sqmeter = $_POST['sqmeter'];
$post_heat = $_POST['heat'];
}
else {
$post_title = $validated_data['title'];
$post_address = $validated_data['address'];
$post_price = $validated_data['price'];
$post_type = $validated_data['type'];
$post_yearbt = $validated_data['year_built'];
$post_parking = $validated_data['parking'];
$post_sqmeter = $validated_data['sqmeter'];
$post_heat = $validated_data['heat'];
if (isset($_SESSION['firstname'])) {
$post_author = $_SESSION['firstname'];
}
$post_date = date('Y-m-d');
$image = $_FILES['image']['name'];
$ext = $_FILES['image']['type'];
$validExt = array ("image/gif", "image/jpeg", "image/pjpeg", "image/png", "image/jpg");
if (empty($image)) {
echo "<script>alert('Attach an image');</script>";
}
else if ($_FILES['image']['size'] <= 0 || $_FILES['image']['size'] > 1024000 )
{
echo "<script>alert('Image size is not proper');</script>";
}
else if (!in_array($ext, $validExt)){
echo "<script>alert('Not a valid image');</script>";
}
else {
$folder = 'postpics/';
$imgext = strtolower(pathinfo($image, PATHINFO_EXTENSION) );
$picture = rand(1000 , 1000000) .'.'.$imgext;
if(move_uploaded_file($_FILES['image']['tmp_name'], $folder.$picture)) {
$query = "INSERT INTO posts (title,address,price,type,year_built,parking,sqmeter,heat,date,image) VALUES ('$post_title' , '$post_address' , '$post_price' , '$post_type' , '$post_yearbt' , '$post_parking', '$post_sqmeter','$post_heat','$post_date','$picture')";
$result = mysqli_query($conn , $query) or die(mysqli_error($conn));
if (mysqli_affected_rows($conn) > 0) {
echo "<script> alert('Posted!');
window.location.href='index.php';</script>";
}
else {
"<script> alert('Error while posting..try again');</script>";
}
}
}
}
}
?>
First i thought that i might be missing a field in my DB but i rechecked and i created the table again. If needed i will post a picture of my posts table and the columns.
Your issue I suspect is you are checking if your image file has been uploaded with $_POST['image']. This isn't how PHP handles file uploads - they are stored in $_FILES instead so your isset($_POST['image'] == false.
This should work:
<?php
include('includes/general.php');
if (isset($_POST['title']) && isset($_POST['address']) && isset($_POST['price']) &&
isset($_POST['type']) && isset($_POST['year_built']) && isset($_POST['parking']) &&
isset($_POST['sqmeter']) && isset($_POST['heat']) && isset($_POST['image']) && count($_FILES) > 0)
{
//Properly sanitise and validate your inputs and do what else you need to do
}
Tip: if you ever find a PHP file just isn't doing what it should be, a conditional statement you're using to validate data is a very likely culprit. Try debugging by putting die('OK up to here'); within your if blocks to pinpoint whether code is being executed.
For example, in your code if you had debugged with:
<?php
include('includes/general.php');
if (isset($_POST['title']) && isset($_POST['address']) && isset($_POST['price']) &&
isset($_POST['type']) && isset($_POST['year_built']) && isset($_POST['parking']) &&
isset($_POST['sqmeter']) && isset($_POST['heat']) && isset($_POST['image'])) {
die('OK up to here');
//Your code
}
Then the OK up to here message wouldn't have been displayed in your output and you would know there was a problem with the conditional statement.
I'm making a blog edit page, but my edit page doesn't do anything. Why doesn't my update query work? I'm collecting the data from an old blog and inserting it into my form. And then I'm trying to update it using my update query.
I think this is the code you need:
<?php
include_once('includes/connection.php');
include_once('includes/article.php');
$article = new Article;
if (isset($_POST['title'], $_POST['content'])) {
$title = $_POST['title'];
$content = nl2br($_POST['content']);
if (empty($title) or empty($content)){
$error ='All fields are required!';
} else {
$query = $pdo->prepare("UPDATE articles SET article_title = ?, article_content = ? WHERE id=:id");
$id = $_POST ['id'];
$query->bindValue(1, $title);
$query->bindValue(2 ,$content);
$query->bindValue ('id', $id);
$query->execute();
header('Location: index.php');
}
}
if (isset($_GET['id'])) {
$id = $_GET['id'];
$data = $article->fetch_data($id)
?>
<?php
} else {
header('Location: index.php');
exit();
}
?>
<form action="aanpassen.php" method="post" autocomplete="off">
<input type="" name="id" value="<?php echo $data['article_id']; ?>">
<input class="titleform" type="text" name="title" placeholder="Blog naam" value="<?php echo $data['article_title']; ?>" />
<textarea id="summernote" name="content" rows="15" cols="50">
<?php echo $data['article_content'] ?> </textarea>
<input class="buttonclass" type="submit" value="Aanmaken" /> </form>
You have a "Invalid parameter number: mixed named and positional parameters" error.
Change ? to placeholders, and change to bindValue():
$query = $pdo->prepare("UPDATE articles SET article_title = :title,
article_content = :content WHERE id=:id");
$id = $_POST ['id'];
$query->bindValue('title', $title);
$query->bindValue('content', $content);
$query->bindValue('id', $id);
$query->execute();
Or use only positional parameters.
The form element id was missing a type attribute - probably defaulted to text
Whilst probably not going to cause errors the mixing of placeholder types in the prepared statement is unusual. The id placeholder was missing the colon in the bindValue call - again possibly OK though to my mind it should always be used in named placeholders.
If the prepared statement failed the initial stage there was no logic to test for it.
<?php
$error=false;
include_once('includes/connection.php');
include_once('includes/article.php');
$article = new Article;
if( $_SERVER['REQUEST_METHOD']=='POST' && $pdo ){
if ( isset( $_POST ['id'], $_POST['title'], $_POST['content'] ) ) {
$id = $_POST ['id'];
$title = $_POST['title'];
$content = nl2br( $_POST['content'] );
if ( empty( $title ) or empty( $content ) or empty( $id ) ){
$error='All fields are required!';
} else {
$query = $pdo->prepare("UPDATE articles SET article_title = :title, article_content = :content WHERE id=:id");
if( $query ){
$query->bindValue( ':title', $title );
$query->bindValue( ':content' ,$content );
$query->bindValue( ':id', $id );
$result=$query->execute();
header( sprintf( 'Location: index.php?status=%s', $result ? 'ok' : 'failed' ) );
} else {
exit('bad foo - unable to prepare sql query');
}
}
} else {
exit( sprintf( "<pre>check all required fields are named correctly\n\n%s</pre>", print_r( $_POST, true ) ) );
}
}
if ( isset( $_GET['id'] ) && $article ) {
$id = $_GET['id'];
$data = $article->fetch_data( $id );
} else {
header('Location: index.php');
exit();
}
?>
<form action="aanpassen.php" method="post" autocomplete="off">
<input type="hidden" name="id" value="<?php echo $id; ?>" />
<input type="text" name="title" class="titleform" placeholder="Blog naam" value="<?php echo $data['article_title']; ?>" />
<textarea name="content" id="summernote" rows="15" cols="50"><?php echo $data['article_content'] ?></textarea>
<input type="submit" class="buttonclass" value="Aanmaken" />
</form>
<?php
if( $error )printf('<h1>%s</h1>',$error);
?>
I am in need of a little bit of help here, it is the only part missing on my website.
I have a newsletter script and on the first page I am using a multilanguage function that I got from codecanyon (PHPMLC) that works perfectly.
This is the index.php with the form ( I have stripped the unnecessary html).
<?php
require_once( "../PHPMLC/class/PHPMLC.php" );
$ml = new PHPMLC();
$ml_languages = $ml->getLanguages();
$ml_selected_language_code = $ml->getCurrentLanguageCode();
$ml_strings = $ml->getTranslatedStringsForCurrentLanguage();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title><?php echo $ml_strings['prereg_m_title']; ?></title>
<link href="/css/style.css" rel="stylesheet">
</head>
<body class="Site">
<form class="form-horizontal" id="newsletter" action="send.php" method="post" accept-charset="utf-8"
enctype="multipart/form-data">
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label">Email</label>
<div class="col-sm-6">
<input type="email" name="signup-email" class="form-control" id="signup-email" value=""
pattern="[A-Z-a-z-0-9-_#.]+" autocomplete="off" required />
<input type="hidden" name="signup-gender" id="signup-gender" value="female" />
</div>
</div>
<div class="form-group">
<label for="inputPassword3"
class="col-sm-2 control-label"><?php echo $ml_strings['prereg_country_label']; ?></label>
<div class="col-sm-6">
<select class="form-control" name="signup-country" required />
<option value="" disabled selected><?php echo $ml_strings['prereg_please_select']; ?></option>
<option value="Albania">Albania</option>
<option value="Andorra">Andorra</option>
<option value="Austria">Austria</option>
<option value="Belarus">Belarus</option>
<option value="Belgium">Belgium</option>
</select>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-6">
<button type="submit" class="btn btn-info"><?php echo $ml_strings['prereg_submit_button']; ?></button>
</div>
</div>
</form>
</body>
</html>
The form send the inputs to a file "send.php" which has the following code :
<?php
require 'inc/Database.class.php';
class Newsletter {
private static $email;
private static $gender;
private static $country;
private static $ip;
private static $datetime = null;
private static $valid = true;
public function __construct() {
die( 'Init function is not allowed' );
}
public static function register( $email ) {
if ( ! empty( $_POST ) ) {
self::$email = $_POST['signup-email'];
self::$gender = $_POST['signup-gender'];
self::$country = $_POST['signup-country'];
//Test if it is a shared client
if ( ! empty( $_SERVER['HTTP_CLIENT_IP'] ) ) {
self::$ip = $_SERVER['HTTP_CLIENT_IP'];
//Is it a proxy address
} elseif ( ! empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) {
self::$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
self::$ip = $_SERVER['REMOTE_ADDR'];
}
self::$datetime = date( 'Y-m-d H:i:s' );
if ( empty( self::$email ) ) {
$status = "error";
$message = "The email address field must not be blank";
self::$valid = false;
} else if ( ! filter_var( self::$email, FILTER_VALIDATE_EMAIL ) ) {
$status = "error";
$message = "You must fill the field with a valid email address";
self::$valid = false;
}
if ( self::$valid ) {
$pdo = Database::connect();
$pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$existingSignup = $pdo->prepare( "SELECT COUNT(*) FROM signups WHERE signup_email_address='$email'" );
$existingSignup->execute();
$data_exists = ( $existingSignup->fetchColumn() > 0 ) ? true : false;
if ( ! $data_exists ) {
$sql = "INSERT INTO signups (signup_email_address, signup_category, signup_country, signup_ip, signup_date) VALUES (:email, :gender, :country, :ip, :datetime)";
$q = $pdo->prepare( $sql );
$q->execute(
array( ':email' => self::$email,
':gender' => self::$gender,
':country' => self::$country,
':ip' => self::$ip,
':datetime' => self::$datetime
) );
if ( $q ) {
$status = "success";
$message = "Your registration was successful";
} else {
$status = "error";
$message = "An error occurred, please try again";
}
} else {
$status = "error";
$message = "This email is already registered";
}
}
$data = array(
'status' => $status,
'message' => $message
);
echo json_encode( $data );
Database::disconnect();
}
}
}
if ( ! empty( $_POST ) ) {
$email = $_POST['signup-email'];
$gender = $_POST['signup-gender'];
$country = $_POST['signup-country'];
Newsletter::register( $email );
}
?>
My problem is, I cannot translate the error/alert messages in send.php. I mean I cannot use the key $ml_strings['reg_successful']; instead of "Your registration was successful". It's driving me crazy because I am an amateur.
Many thanks in advance for your help.
The execution of send.php is completely separated from the execution of index.php, so you need to initialize the $ml_strings variable in both files. In other words, add the following line to the Newsletter class in send.php:
$ml_strings = $ml->getTranslatedStringsForCurrentLanguage();
I'm newbie with PDO and I'm trying to make an ads site. On a page with insert data from a form I receive this issue: "Fatal Error. Cannot use object of type ads as array". Before ask here I searched about this issue and I didn't find anything (maybe because I'm newbie???). Please don't vote me negative.
This is the PHP file with functions:
class ads{
private $db;
public function __construct($database) {
$this->db = $database;
}
public function insert_ads($categorie, $subcategorie, $userid, $site, $nume, $oras, $judet, $telefon, $email, $titlu_anunt, $text_anunt, $pret_anunt ){
$time = time();
$categorie = 'masini';
$subcategorie = 'dacia';
$email_code = $email_code = uniqid('code_',true);
$query = $this->db->prepare("INSERT INTO `ads` (`categorie`, `subcategorie`, `userid`, `site`, `nume`, `oras`, `judet`, `telefon`, `email`, `email_code`, `titlu_anunt`, `text_anunt`, `pret_anunt`, `data_adaugare`, `vizualizari`, `confirmed`, `platit`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ");
$query->bindValue(1, $categorie);
$query->bindValue(2, $subcategorie);
$query->bindValue(3, 0);
$query->bindValue(4, $site);
$query->bindValue(5, $nume);
$query->bindValue(6, $oras);
$query->bindValue(7, $judet);
$query->bindValue(8, $telefon);
$query->bindValue(9, $email);
$query->bindValue(10, $email_code);
$query->bindValue(11, $titlu_anunt);
$query->bindValue(12, $text_anunt);
$query->bindValue(13, $pret_anunt);
$query->bindValue(14, $time);
$query->bindValue(15, 1);
$query->bindValue(16, 0);
$query->bindValue(17, 0);
try{
$id_last = ("SELECT LAST_INSERT_ID()");
$result = $this->db->prepare($id_last);
$result->execute();
$last_id = $result->fetchColumn();
#code to deal with the picture uploads
#target folder
$target = 'image_uploads/';
if(isset($_FILES['image_name'])===true){
$files = $_FILES['image_name'];
for($x = 0 ; $x < count($files['name']); $x++){
$name = $files['name'][$x] ;
$temp_name = $files['tmp_name'][$x];
#extention filter it takes only the extension want
$allowed ='gif,png,jpg';
$extension_allowed= explode(',',$allowed );
$file_extention = pathinfo($name, PATHINFO_EXTENSION);
if(array_search($file_extention,$extension_allowed)){
}else {
echo 'We only allow gif, png ,jpg';
exit();
} #extention filter ends here
#check the size of the image
$file_size = $files['size'][$x];
if($file_size > 2097152){
echo 'The file should be lesS than 2MB';
exit();
}
#check the size of the image ends here
#Rename images
$sub = substr(md5(rand()),0,7);
#the above generates char and numbesr
$rand = rand(0,100000);
$rename = $rand.$sub.$name;
#Rename images ends here
$move = move_uploaded_file($temp_name,$target.$rename);
#code to deal with the picture uploads ends here
$images ="INSERT INTO ads_images(ads_id,image_name)
VALUES($last_id,:image_name)";
$images_insert = $this->db->prepare($images);
$images_insert->execute(array(
':image_name'=>$rename,
));
}}
$query->execute();
mail($email, 'Please activate your account', "Hello " . $nume. ",\r\nThank you for registering with us. Please visit the link below so we can activate your account:\r\n\r\nhttp://www.djmixtv.com/test/activate_ads.php?email=" . $email . "&email_code=" . $email_code . "\r\n\r\n-- Example team");
}catch(PDOException $e){
die($e->getMessage());
}
}
This is the PHP code:
if (isset($_GET['success']) && empty($_GET['success'])) {
echo '<h3>Your details have been updated!</h3>';
} else{
if(empty($_POST) === false) {
if (isset($_POST['nume']) && !empty ($_POST['nume'])){ // We only allow names with alphabets
if (ctype_alpha($_POST['nume']) === false) {
$errors[] = 'Please enter your Name only with letters!';
}
}
if (isset($_POST['oras']) && !empty ($_POST['oras'])){
if (ctype_alpha($_POST['oras']) === false) {
$errors[] = 'Please enter your city with only letters!';
}
}
if (isset($_POST['judet']) && !empty ($_POST['judet'])){
if (ctype_alpha($_POST['judet']) === false) {
$errors[] = 'Please enter your contry with only letters!';
}
}
if (isset($_POST['telefon']) && !empty ($_POST['telefon'])){
if (ctype_digit($_POST['telefon']) === false) {
$errors[] = 'Please enter your phone with only numbers!';
}
}
if (isset($_POST['telefon']) && !empty ($_POST['telefon'])){
if (ctype_digit($_POST['telefon']) === false) {
$errors[] = 'Please enter your phone with only numbers!';
}
}
if (filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) === false) {
$errors[] = 'Please enter a valid email address';
}
if (isset($_POST['titlu_anunt']) && !empty ($_POST['titlu_anunt'])){
if (ctype_alnum($_POST['titlu_anunt']) === false) {
$errors[] = 'Please enter your phone with only numbers!';
}
}
$site = htmlentities(trim($_POST['site']));
$nume = htmlentities(trim($_POST['nume']));
$oras = htmlentities(trim($_POST['oras']));
$judet = htmlentities(trim($_POST['judet']));
$telefon = htmlentities(trim($_POST['telefon']));
$email = htmlentities(trim($_POST['email']));
$titlu_anunt = htmlentities(trim($_POST['titlu_anunt']));
$text_anunt = htmlentities(trim($_POST['text_anunt']));
$pret_anunt = htmlentities(trim($_POST['pret_anunt']));
$ads->insert_ads($categorie, $subcategorie, $site, $nume, $oras, $judet, $telefon, $email, $titlu_anunt, $text_anunt, $pret_anunt);
header('Location: settings.php?success');
exit();
}
This is the form:
<form action="" method="post" enctype="multipart/form-data">
<div id="personal_info">
<h3 >Change Profile Information </h3>
<ul>
<li>
<h4>Site:</h4>
<input type="text" name="site" value="<?php if (isset($_POST['site']) ){echo htmlentities(strip_tags($_POST['site']));} else { echo $ads['site']; }?>">
</li>
<li>
<h4>Nume: </h4>
<input type="text" name="nume" value="<?php if (isset($_POST['nume']) ){echo htmlentities(strip_tags($_POST['nume']));} else { echo $ads['nume']; }?>">
</li>
<li>
<h4>Nume: </h4>
<input type="text" name="nume" value="<?php if (isset($_POST['nume']) ){echo htmlentities(strip_tags($_POST['nume']));} else { echo $ads['nume']; }?>">
</li>
<li>
<h4>Oras: </h4>
<input type="text" name="oras" value="<?php if (isset($_POST['oras']) ){echo htmlentities(strip_tags($_POST['oras']));} else { echo $ads['oras']; }?>">
</li>
<li>
<h4>Judet: </h4>
<input type="text" name="judet" value="<?php if (isset($_POST['judet']) ){echo htmlentities(strip_tags($_POST['judet']));} else { echo $ads['judet']; }?>">
</li>
<li>
<h4>Telefon: </h4>
<input type="text" name="telefon" value="<?php if (isset($_POST['telefon']) ){echo htmlentities(strip_tags($_POST['telefon']));} else { echo $ads['telefon']; }?>">
</li>
<li>
<h4>Email: </h4>
<input type="text" name="email" value="<?php if (isset($_POST['email']) ){echo htmlentities(strip_tags($_POST['email']));} else { echo $ads['email']; }?>">
</li>
<li>
<h4>Titlu Anunt: </h4>
<input type="text" name="titlu_anunt" value="<?php if (isset($_POST['titlu_anunt']) ){echo htmlentities(strip_tags($_POST['titlu_anunt']));} else { echo $ads['titlu_anunt']; }?>">
</li>
<li>
<h4>Text anunt:</h4>
<textarea name="text_anunt"><?php if (isset($_POST['text_anunt']) ){echo htmlentities(strip_tags($_POST['text_anunt']));} else { echo $user['text_anunt']; }?></textarea>
</li>
<li>
<h4>Pret: </h4>
<input type="text" name="pret_anunt" value="<?php if (isset($_POST['pret_anunt']) ){echo htmlentities(strip_tags($_POST['pret_anunt']));} else { echo $ads['pret_anunt']; }?>">
</li>
<li>
<h4>Image</h4>
<input type="file" name="image_name[]" multiple /><br />
</ul>
</div>
<div class="clear"></div>
<hr />
<span>Update Changes:</span>
<input type="submit" value="Update">
</form>
This is not related to PDO.
You cannot use an ads instance as an array. For example
$ads = new ads();
$ads['something'] = 1; //Fatal Error comes here
It is in your form everywhere.
<input type="text" name="site" value="<?php if (isset($_POST['site']) ){
echo htmlentities(strip_tags($_POST['site']));} else { echo $ads['site']; }
?>">
In PHP if you want to use a property, you have to define it.
class ads {
public myProperty;
public function setAValueForMyProperty(){
$this->myProperty = 1;
}
}
$ads = new ads();
$ads->setAValueForMyProperty();
echo $ads->myProperty;
If you want to use a class instance as an array, you have two options. You can export its content into an array:
class ads {
protected myProperty = 1;
public function toArray(){
return array(
'myProperty' => $this->myProperty;
);
}
}
$ads = new ads();
$arr = $ads->toArray();
echo $arr['myProperty'];
Or you can implement the ArrayAccess interface:
class ads implements ArrayAccess {
protected myProperty = 1;
public function offsetSet($offset, $value) {
$this->$offset = $value;
}
public function offsetExists($offset) {
return isset($this->$offset);
}
public function offsetUnset($offset) {
unset($this->$offset);
}
public function offsetGet($offset) {
return $this->$offset;
}
}
$ads = new ads();
echo $ads['myProperty'];
I think you should read more about how classes work in php.
http://www.php.net/manual/en/language.oop5.php