Trying to use an array value as an SQL insert value - php

Hey guys I am trying to use a value that i got from a previous query in a new one, the value is a string stored in an array, they are the $Name and $Email variables, it looks like this when i var_dump them... string 'nathgold' (length=8) .... I want to use that nathgold as a value in the insert of a new query. I get the error Notice: Array to string conversion in C:\wamp\www\login\post.php on line 30
<?php
include_once('connect-db.php');
session_start();
if(!isset($_SESSION['isLogged']))
{
header("Location: home.php");
die();
}
if (!isset($_REQUEST['MBID'])) exit;
if (!isset($_REQUEST['Parent'])) {
$Parent = 0;
} else {
$Parent = $_REQUEST['Parent'];
}
if (isset($_POST['Title'])) {
$user_info=mysqli_query($connection, "SELECT * FROM usertest WHERE id=".$_SESSION['user']);
$userRow=mysqli_fetch_array($user_info);
$Name = $userRow=['username'];
$Email = $userRow=['email'];
$Title = mysqli_real_escape_string($connection, $_POST['Title']);
$Message = mysqli_real_escape_string($connection, $_POST['Message']);
$CurrentTime = time();
// other filtering here...
$result = mysqli_query($connection, "INSERT INTO mbmsgs (MBID, Parent, Poster, Email, Title, Message, DateSubmitted) VALUES ({$_REQUEST['MBID']}, $Parent, ".$Name.", ".$Email.", '$Title', '$Message', $CurrentTime);");
if ($result) {
echo "Your message has been posted - thanks!<br /><br />";
echo "Back to messageboard";
exit;
} else {
echo "There was a problem with your post - please try again.<br /><br />";
}
}
?>
<form method="post" action="post.php">
Message title: <input type"text" name="Title" /><br /><br />
Message:<BR />
<textarea name="Message" rows="10" cols="40"></textarea><br /><br />
<input type="hidden" name="MBID" value="<?php echo $_REQUEST['MBID']; ?>" />
<input type="hidden" name="Parent" value="<?php echo $Parent; ?>" />
<input type="submit" value="Post" />
</form>

You to convert $name on a string :
use implode("|",$name);

Related

Php - isset() condition doesn't work

I am a newbie to PHP. & My PHP Code doesn't work, I want to update some date using MySQL but it seems that first IF condition is 'false' i don't why, I am using PHP 7 & XAMP as a local host, Dreamweaver as an IDE & this is my code:
if(isset($_POST["btn_edit"]))
{
$name = $_POST["name"];
$email = $_POST["email"];
$password = $_POST["password"];
if(!empty($_FILES["img"]["name"]))
{
$img = $_FILES["img"]["name"];
$img_temp = $_FILES["img"]["tmp_name"];
if(move_uploaded_file($img_temp, "assets/images/".$img))
{
$query = mysqli_query($Connection, "UPDATE entry_data SET names='$name',emails='$name',passwords='$password',images='$img' WHERE id='$ID'");
if($query)
{
$result = header("Location:index.php");
}
else
{
echo mysql_error();
}
}
}
else
{
$query = mysqli_query($Connection, "UPDATE entry_data SET names='$name',emails='$name',passwords='$password',images='$img' WHERE id='$ID'");
if($query)
{
echo "<h5>Updated</h5>";
}
}
}
it showing me nothing just refresh the page & this is HTML CODE:
<form method="post" enctype="multipart/form-data">
<input name="name" value="<?php echo $name ?>" />
<input name="email" value="<?php echo $email ?>" />
<input name="password" value="<?php echo $password ?>" />
<img width="50" height="50" src="<?php echo 'assets/images/'.$row[4] ?>" />
<input name="img" type="file" class="text-info" required="required" />
<br/>
<input name"btn_edit" type="submit" />
<?php if(isset($_POST["btn_edit"])) echo $result ?>
You have syntax issue in your button HTML.
This:-
<input name"btn_edit" type="submit" />
Need to be:-
<input name="btn_edit" type="submit" /><!-- = is missing in name -->

Why is my form not working using POST method?

I have written the below HTML code:
<form action="index.php" method="POST">
<input type="text" name="title" required>
<input type="text" name="brief_text" required>
<textarea name="text" required></textarea>
<input type="submit" name="add" value="Add">
</form>
My PHP code:
<?php
require_once('db.php');
if(isset($_POST['add'])){
$title = $_POST['title'];
$brief_text = $_POST['brief_text'];
$text = $_POST['text'];
$blog_cat_id = $_POST['blog_cat_id'];
if($title AND $brief_text AND $text AND $blog_cat_id){
$insert_blog = "insert into blog values ('','$title','$brief_text','$text','$blog_cat_id',NOW())";
$run_insertion = mysqli_query($con, $insert_blog);
if($run_insertion){
echo "Blog has been added!";
}
else{
echo "Error adding blog!!!";
}
}
else{
echo "All fields are required!";
}
}
else{
echo "GOODBYE";
}
?>
Every time I refresh the page, it only shows the form and "GOODBYE" and does not even insert the data into database table.
Help me out please.
Is it still showing 'GOODBYE' now you've changed
$_POST['add_blog']
to
$_POST['add']
when you click submit?
You have few mistakes,
1) should be: $_POST['add'] instead of $_POST['add_blog']
2) don't have $_POST['blog_cat_id'] as not in form
EDIT
Copied your code and made some changes:
code:
if(isset($_POST['add'])){
print_r($_POST);
$title = $_POST['title'];
$brief_text = $_POST['brief_text'];
$text = $_POST['text'];
$blog_cat_id = $_POST['blog_cat_id'];
if($title AND $brief_text AND $text AND $blog_cat_id){
echo "inside condition";
$insert_blog = "insert into blog values ('','$title','$brief_text','$text','$blog_cat_id',NOW())";
$run_insertion = mysqli_query($con, $insert_blog);
if($run_insertion){
echo "Blog has been added!";
}
else{
echo "Error adding blog!!!";
}
}
else{
echo "All fields are required!";
}
}
else{
echo "GOODBYE";
}
HTML:
<form action="index.php" method="POST">
<input type="text" name="title" required>
<input type="text" name="brief_text" required>
<input type="text" name="blog_cat_id" required>
<textarea name="text" required></textarea>
<input type="submit" name="add" value="Add">
</form>
output
Array ( [title] => test [brief_text] => test [blog_cat_id] => 1 [text] => testing [add] => Add )
inside condition
Now, check your query if doesn't work.
Hope this will help you.
Your query is wrong, columns are not specified and you are open to sql injection you should learn to use parameterized query. but for this time you can use the following.
Try this:
htmlcode
<form action="index.php" method="POST">
<input type="text" name="title" required>
<input type="text" name="brief_text" required>
<input type="text" name="blog_cat_id" required>
<textarea name="text" required></textarea>
<input type="submit" name="add" value="Add">
</form>
index.php
<?php
require_once('db.php');
if(isset($_POST['add'])){
$title = $_POST['title'];
$brief_text = $_POST['brief_text'];
$text = $_POST['text'];
$blog_cat_id = $_POST['blog_cat_id'];
if($title AND $brief_text AND $text AND $blog_cat_id){
$insert_blog = "insert into blog('col1','col2','col3','col4','col5','col6') values ('','$title','$brief_text','$text','$blog_cat_id',NOW())";
$run_insertion = mysqli_query($con, $insert_blog);
if($run_insertion){
echo "Blog has been added!";
}
else{
echo "Error adding blog!!!";
}
}
else{
echo "All fields are required!";
}
}
?>
Note : col1, col2, col3, col4, col5 and col6 will be your column name.

Populate drop down list, pass two variables

I am wanting to populate a drop down list from another mysql table and then assign the values from two of the columns into variables - i.e. "select name, eid, perc from employee". "John Doe" would be $eid = 1234 and $perc = 20.
Any help with this would be greatly appreciated!
Thank you - Matt
Here is the code I have been working with:
PHP
<?php
//session_start();
$page_title = 'New invoice';
include ('includes/header.html');
// Check for form submission:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
require ('mysqli_connect.php'); // Connect to the db.
/*$errors = array(); // Initialize an error array. */
// Invoice number is automatic
if (empty($_POST['op1'])) {
$errors[] = 'Operation needs to be entered.';
} else {
$op1 = mysqli_real_escape_string($dbc, trim($_POST['op1']));
}
// Amount:
if (empty($_POST['amount1'])) {
$errors[] = 'Amount to be charged.';
} else {
$amount1 = mysqli_real_escape_string($dbc, trim($_POST['amount1']));
}
// percentage:
if (empty($_POST['perc'])) {
$errors[] = 'Select a percentage.';
} else {
$perc = mysqli_real_escape_string($dbc, trim($_POST['perc']));
}
// eid:
if (empty($_POST['eid'])) {
$errors[] = 'Enter a techician.';
} else {
$eid = mysqli_real_escape_string($dbc, trim($_POST['eid']));
}
// Stocknum:
if (empty($_POST['stocknum'])) {
$errors[] = 'Need a stock number.';
} else {
$stocknum = mysqli_real_escape_string($dbc, trim($_POST['stocknum']));
}
// Stocknum:
if (empty($_POST['myear'])) {
$errors[] = 'Enter vehicle year.';
} else {
$myear = mysqli_real_escape_string($dbc, trim($_POST['myear']));
}
if (empty($_POST['make'])) {
$errors[] = 'Enter vehicle make.';
} else {
$make = mysqli_real_escape_string($dbc, trim($_POST['make']));
}
if (empty($_POST['model'])) {
$errors[] = 'Enter vehicle model.';
} else {
$model = mysqli_real_escape_string($dbc, trim($_POST['model']));
}
if (empty($_POST['vin'])) {
$errors[] = 'Enter last 6 of the VIN.';
} else {
$vin = mysqli_real_escape_string($dbc, trim($_POST['vin']));
}
if (empty($_POST['mileage'])) {
$errors[] = 'Enter current mileage.';
} else {
$mileage = mysqli_real_escape_string($dbc, trim($_POST['mileage']));
}
if (empty($errors)) { // If everything's OK.
$q = "INSERT INTO `mwcc`.`wp` (`tdate`, `stocknum`, `myear`, `make`, `model`,`vin`, `eid`, `op1`, `amount1`,`mileage`,`ecomm`) VALUES (CURRENT_DATE(), '$stocknum', '$myear', '$make', '$model','$vin', '$eid', '$op1', '$amount1','$mileage', ($amount1*$perc));";
$r = #mysqli_query ($dbc, $q); // Run the query.
//echo ($q);
if ($r) { // If it ran OK.
// Print a message:
echo '<h1>Success!</h1>
<p>Invoice has been created!<br /></p>';
} else { // If it did not run OK.
// Public message:
echo '<h1>System Error</h1>
<p class="error">Uh oh. There has been an error. We apologize for any inconvenience.</p>';
// Debugging message:
echo '<p>' . mysqli_error($dbc) . '<br /><br />Query: ' . $q . '</p>';
} // End of if ($r) IF.
mysqli_close($dbc); // Close the database connection.
exit();
} else { // Report the errors.
echo '<h1>Error!</h1>
<p class="error">The following error(s) occurred:<br />';
foreach ($errors as $msg) { // Print each error.
echo " - $msg<br />\n";
}
echo '</p><p>Please try again.</p><p><br /></p>';
} // End of if (empty($errors)) IF.
mysqli_close($dbc); // Close the database connection.
} // End of the main Submit conditional.
?>
HTML :
<form action="newinv.php" method="post">
<p>Stock #
<input type="text" name="stocknum" size="15" maxlength="20" value="<?php if (isset($_POST['stocknum'])) echo $_POST['stocknum']; ?>" />
Last 6 of VIN
<input type="text" name="vin" size="15" maxlength="6" value="<?php if (isset($_GET['vin'])) echo $_POST['vin']; ?>" /> </p>
<p>Year
<input type="text" name="myear" size="4" maxlength="4" value="<?php if (isset($_POST['myear'])) echo $_POST['myear']; ?>" />
Make
<input type="text" name="make" size="30" maxlength="20" value="<?php if (isset($_POST['make'])) echo $_POST['make']; ?>" />
Model
<input type="text" name="model" size="30" maxlength="20" value="<?php if (isset($_POST['model'])) echo $_POST['model']; ?>" /></p>
Mileage
<input type="text" name="mileage" sizesize="15" maxlength="6" value="<?php if (isset($_POST['mileage'])) echo $_POST['mileage']; ?>" /> </p>
<p>Operation <input type="text" name="op1" size="60" maxlength="250" value="<?php if (isset($_POST['op1'])) echo $_POST['op1']; ?>" />
Amount <input type="text" name="amount1" size="8" maxlength="20" value="<?php if (isset($_POST['amount1'])) echo $_POST['amount1']; ?>" /></p>
<br>
<input type="radio" name="eid" value="1767">Alex H<br>
<input type="radio" name="eid" value="1688">Blake S<br>
<input type="radio" name="eid" value="1506">Brian M<br>
<input type="radio" name="eid" value="1898">Chris V<br>
<input type="radio" name="eid" value="3000">Kim R<br>
<input type="radio" name="eid" value="1916">Jorden U<br>
<input type="radio" name="eid" value="1931">Tina M<br>
<input type="radio" name="eid" value="1506">Tanner C<br>
<br>
<input type="radio" name="perc" value=".35">35%
<br>
<input type="radio" name="perc" value=".40">40%
<p><input type="submit" name="submit" value="Add" /></p>
</form>
My understanding from your question.
Get query result as you mentioned.select name, eid, perc from employee
For Front End if you want pass both values in single select then use some unique separator like i'm using double underscore __
<?php foreach($result as $user): ?>
<select name="eid__perc" >
<option value="<?php $user->eid . '__' . $user->perc?>">
<?php $user->name; //in array case $user['name'];?>
<option>
<select>
<?php endforeach;?>
And when you save information use same separator to explode data like
list($eid, $perc) = explode('__', $_POST['eid__per'])
You need to use WHERE condition for that:
SELECT name, eid, perc FROM employee WHERE eid = ? AND perc = ?
Than use mysqli_stmt_bind_param($stmt, 'ss', $eid, $perc); to bind parameters.

Update function php

I'm working in a update file using php and mysql but the update function doesn't work. I wrote the code using an example and modified according to the requirements. The file does work and doesn't really drop any error but it doesn't change anything in the database. It is suppose to update a book database.
Code:
<?php
$page_title = 'Add Books';
include ('bookincludes/header.html');
// Check for form submission:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
require ('../mysqli_connect.php'); // Connect to the db.
$errors = array(); // Initialize an error array.
if (empty($_POST['title'])) {
$errors[] = 'Please add title.';
} else {
$e = mysqli_real_escape_string($dbc, trim($_POST['title']));
}
if (empty($_POST['author'])) {
$errors[] = 'Please add the name of the author.';
} else {
$p = mysqli_real_escape_string($dbc, trim($_POST['author']));
}
if (!empty($_POST['isbn1'])) {
if ($_POST['isbn1'] != $_POST['isbn2']) {
$errors[] = 'ISBN number does not match.';
} else {
$np = mysqli_real_escape_string($dbc, trim($_POST['isbn1']));
}
} else {
$errors[] = 'You need to enter ISBN number.';
}
if (empty($errors)) { // If everything's OK.
$q = "SELECT ISBN FROM Books WHERE (Title='$e' AND Author ='$p')";
$r = #mysqli_query($dbc, $q);
$num = #mysqli_num_rows($r);
if ($num == 1) { // Match was made.
$row = mysqli_fetch_array($r, MYSQLI_NUM);
// Make the UPDATE query:
$q = "UPDATE Books SET ISBN='$np' WHERE ISBN = $row[0] ";
$r = mysqli_query($dbc, $q);
if (mysqli_affected_rows($dbc) == 1) { // If it ran OK.
// Print a message.
echo '<h1>Thank you!</h1>
<p>Thank you, Book has been added or modified</p><p><br /></p>';
} else { // If it did not run OK.
// Public message:
echo '<h1>System Error</h1>
<p class="error">System error. We apologize for any inconvenience.</p>';
// Debugging message:
echo '<p>' . mysqli_error($dbc) . '<br /><br />Query: ' . $q . '</p>';
}
mysqli_close($dbc); // Close the database connection.
// Include the footer and quit the script (to not show the form).
include ('includes/footer.html');
exit();
} else {
echo '<h1>Error!</h1>
<p class="error">ISBN number is incorrect.</p>';
}
} else { // Report the errors.
echo '<h1>Error!</h1>
<p class="error">The following error(s) occurred:<br />';
foreach ($errors as $msg) { // Print each error.
echo " - $msg<br />\n";
}
echo '</p><p>Please try again.</p><p><br /></p>';
} // End of if (empty($errors)) IF.
mysqli_close($dbc); // Close the database connection.
} // End of the main Submit conditional.
?>
<h1>Update</h1>
<form action="Bupdate.php" method="post">
<p>ISBN number: <input type="text" name="isbn1" size="20" maxlength="60" value="<?php if (isset($_POST['isbn1'])) echo $_POST['isbn1']; ?>" /> </p>
<p>Confirm ISBN: <input type="text" name="isbn2" size="20" maxlength="60" value="<?php if (isset($_POST['isbn2'])) echo $_POST['isbn2']; ?>" /> </p>
<p>Author: <input type="text" name="author" size="20" maxlength="60" value="<?php if (isset($_POST['author'])) echo $_POST['author']; ?>" /></p>
<p>Title: <input type="text"" name="title" size="20" maxlength="60" value="<?php if (isset($_POST['title'])) echo $_POST['title']; ?>" /></p>
<p>Year: <input type="text"" name="year" size="20" maxlength="60" value="<?php if (isset($_POST['year'])) echo $_POST['year']; ?>" /></p>
<p><input type="submit" name="submit" value="Update" /></p>
</form>
<?php include ('bookincludes/footer.html'); ?>
This is what If I try to change the ISBN got:
System error. We apologize for any inconvenience.
Query: UPDATE Books SET ISBN='978-1782175910' WHERE ISBN =
978-1782175919
If I tried to update the ISBN or the year but I get the message above.
How can I fix this?
The query requires that text values are wrapped in quotes like this
$q = "UPDATE Books SET ISBN='$np' WHERE ISBN = '$row[0]'";
Although I would look for a tutorial that uses parameterised and prepared queries rather than string concatenated queries to avoid SQL Injection
And any tutorial that suggests using the # error silencing prefix should tell you the author has no idea what they are doing and should be avoided like the plague.
you seem to be missing single quotes on your where clause
UPDATE Books SET ISBN='978-1782175910' WHERE ISBN = 978-1782175919
should be
UPDATE Books SET ISBN='978-1782175910' WHERE ISBN = '978-1782175919'

Undefined Index on $_GET variable, its set but still doesn't works?

I am redirecting from here
Update
and code which shows error is
<?php include('../includes/connections.php'); ?>
<?php
try{
if(isset($_POST['submit'])){
$title = $_POST['title'];
$post = $_POST['post'];
$dates = $_POST['date'];
$sql = 'UPDATE `blog`.`contents` SET `titles` = :title, `posts` = :post, `dates` = :date WHERE `contents`.`id` = :idendity';
$result = $pdo->prepare($sql);
$result->bindValue(':title',$title);
$result->bindValue(':post',$post);
$result->bindValue(':date',$dates);
$result->bindValue(':idendity',$_GET['updid']);
$result->execute();
$count = $result->rowCount();
if($count == 1){
header('location: index.php');
}else{
echo 'Problem Occoured';
}
}
}
catch(PDOException $e){
echo "Problem: " .$e->getMessage();
}
?>
error which is shown:-Notice: Undefined index: updid in C:\xampp\htdocs\myblog\admin\update_post.php on line 13
Problem Occoured
<form action="update_post.php" method="post">
Title:<br/>
<input style="height:40px;" size="110" type="text" name="title" /><br />
Post:<br />
<textarea rows="30" cols="85" name="post" ></textarea><br />
Date:<br />
<input type="text" name="date" /><br/ >
<input type="submit" name="submit" />
</form>
yes by form submission and that is the reason i am checking for if submit isset or not.
You should include $_SESSION['id'] in a hidden field in the form:
<input type="hidden" name="updid" value="<?php echo $_SESSION['id']; ?>" />
... and change:
$result->bindValue(':idendity',$_GET['updid']);
... into:
$result->bindValue(':idendity',$_POST['updid']);
Edit
First of all, your question above has error. As mentioned in the comment, it's not possible that isset($_POST['submit']) will return true if you click on a link.
$_POST will have values when you access the page by submitting a form that has post in the method part.
As for $_GET, its values are taken from the query string of a URL:
http://yourpage.php?foo=bar&bar=foo
bar is the value of $_GET['foo']
foo is the value of $_GET['bar']
I've searched for basic $_POST/$_GET explanation but unable to find one :-D

Categories