How to insert every value of array variable in database - php

How to insert every value of array variable in database, whenever i try to insert value using array variable it gives me a error "Array to string conversion".Actually i want to store the attendance of students into "attendance database table", i am retrieving id and name of students from students database, this information of students is being stored in array but when i use array variable"$result" to insert the name of student into attendence_tbl database it gives me error of array to string conversion.
<html>
<head>
</head>
<body>
<div class="container">
<div class="row">
<div class="templatemo-line-header" style="margin-top: 0px;" >
<div class="text-center">
<hr class="team_hr team_hr_left hr_gray"/><span class="span_blog txt_darkgrey txt_orange">Attendance Form</span>
<hr class="team_hr team_hr_right hr_gray" />
</div>
</div>
</div>
<?php
error_reporting(E_ALL ^ E_DEPRECATED);
include("config.php");?>
<div class="form-container">
<form method="post" action="" role="form">
<!-- <div class="container"> -->
<div class="col-lg-3">
<div class="form-group">
<?php
$qs=mysql_query("select * from student_table");
?>
<table border=1>
<?php
$c=0;
while($stid=mysql_fetch_row($qs))
{
?>
<tr>
<td ><?php echo $stid[0]?></td>
<td><?php echo $stid[1]?></td>
<td>
<select name="present[]" >
<option value=""> ---Select Attendence--- </option>
<option value="P"> Present </option>
<option value="A"> Absent </option>
</select></td>
</tr>
<?php
$stud= $stid[0];
$subj= $stid[1];
$location_vars = array(/*"stud" ,*/ "subj");
$result[] = compact("nothing_here", $location_vars);
$date = date('Y-m-d H:i:s');
$c++;
}
// echo "</select>"."<br>";
echo $c;
$e=0;
if(isset($_POST['present'])){
foreach($_POST['present'] as $present){
print_r($result);
$query=mysql_query("Insert into tbl_attendence (StudentRollNumber,SubjectId,Attendence,Date)VALUES('$stud','$stid','$present','$date')");
$e++;
}}
?>
</table>
</div>
</div> <!--col-lg-4-->
<button type="submit" name="save" value="Save" class="btn btn-success btn-sm">Save</button>
</form>
</div> <!--form-container-->
</div><!--container-->
</body>
</html>

Seems you want to put an array variable data directly into table which is supposed to throw error,
Here is the solution.
For adding all value of an array directly into table you have to use first convert array into json and then need to insert it into database. like this..
$resultJson = json_encode($result);
$query = mysql_query("Insert into tbl_attendence (StudentRollNumber,SubjectId,Attendence,Date)VALUES(".$stud.", ".$resultJson.", ".$present.", ".$date.")");
AND if you want to add all array value into database for each value per row separately then you have to make sure run the loop and then insert each value into database for each record.

If I understand you right you want to upload something like this:
Array([1] => '1', [2] => '2')
into a table, which would not work. So you'd have to use JSON to stringify the array. Example:
<?php
$value = 'Some string';
$value2 = 'Some other string';
$values = Array('String 1', 'String 2', 'String 3');
$json_values = json_encode($values);
$mysqli = new mysqli('HOSTNAME', 'USERNAME', 'PASSWORD', 'DATABASE'); // Connecting to SQL Server
// Checking if connection was successfull
if( $mysqli->connect_errno ){
echo 'There was an error connection to the SQL Server<br>';
echo '(' . $mysqli->connect_errno . ') ' . $mysqli->connect_error;
exit; // FAIL
}
// Preparing a statement
$stmt = $mysqli->prepare('INSERT into TABLENAME(value, value2, values) VALUES(?, ?, ?)');
// Checking if php prepared the statement successfully
if(!$stmt){
echo 'There was an error preparing the statement!';
exit;
}
if( !$stmt->bind_param('sss', $value, $value2, $json_values) ){
echo 'There was an error binding params to the statement!';
exit;
}
$stmt->execute();
?>

to post arrays into DB I use this approach:
//database connection class
class Database{
// specify your own database credentials
private $host = "YOUR HOST";
private $db_name = "DATABASE NAME";
private $username = "USERNAME";
private $password = "PASSWORD";
public $conn;
// get the database connection
public function getConnection(){ $this->conn = null;
try{
$this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $this->password);
}catch(PDOException $exception){
echo "Connection error: " . $exception->getMessage();
}
return $this->conn;
}
}
//model class
class Model{
// database connection
private $conn;
// constructor with $db as database connection
public function __construct($db){
$this->conn = $db;
}
// add info to db
function create($fieldset){
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// query to insert record
$query = "INSERT INTO
tbl_attendence
SET
$fieldset";
// prepare query
$stmt = $this->conn->prepare($query);
// execute query
if($stmt->execute()){
return true;
}else{
return false;
}
}
}
//part that will handle the post
// get database connection
$database = new Database();
$db = $database->getConnection();
//instatiate model
$model = new Model($db);
//function that will filter posted values
function filter($value){
$value = trim($value);
$value = strip_tags($value);
$value = stripslashes($value);
$value = htmlentities($value);
return $value;
}
if(!empty($_POST)){
//Get Variables
foreach($_POST as $key => $value){
//this part will tackle values which are arrays
if(is_array($value)){
$val=implode(",",filter($value));
$groupVal[] = $val;
$groupKeys[] = $key;
}
else{
$groupVal[] = $this->filter($value);
$groupKeys[] = $key;
}
}
//count items in array to establish a limit
$limit = count($_POST);
//arranges the data into "key = value" format
for($i=0;$i<$limit;$i++){
$prepFieldset[$i] = "$groupKeys[$i] = $groupVal[$i]";
}
//prepares the fieldset to be used in SQL query
$fieldset = implode(",",$prepFieldset);
//process them in the model
$status = $model->create($fieldset);
//show response
if($status == true){
$response = 'Data saved';
}
else{
$response = 'Error when saving data';
}
}

Related

Is it possible to connect a button from another table to another table to get the data?

I have two tables in one database. The first one is the g1 where the buttons' data is located. The second is the gradeone, where the enrollees' data is located. I want to display the data from the table "gradeone" by clicking the
specific buttons.
Assuming that I added 2 sections. Section 1 and section 2. I click the button section1. By clicking it, I want to display the data of the enrollee from table "gradeone" where the section is 1.
<?php
$dsn = 'mysql:host=localhost;dbname=admin';
$username = 'root';
$password = '';
try{
// Connect To MySQL Database
$con = new PDO($dsn,$username,$password);
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (Exception $ex) {
echo 'Not Connected '.$ex->getMessage();
}
$sectionnumber ="";
$datasuccess ="";
$error ="";
function getPosts(){
$posts = array();
$posts[1] = $_POST['sectionnumber'];
return $posts;
}
if(isset($_POST['add'])){
$data = getPosts();
if(empty($data[1])){
$error = 'Enter The User Data To Insert';
}else {
$insertStmt = $con->prepare('INSERT INTO g1(sectionnumber) VALUES(:sectionnumber)');
$insertStmt->execute(array(
':sectionnumber'=> $data[1]
));
if($insertStmt){
$datasuccess = "<font color='#f8234a'>New added</font>";
}
}
}
?> //Code for adding a button
<?php
require 'connection.php';
$sql = "SELECT sectionnumber FROM g1";
$result = $con->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<button type='button' class='btn'>Section " . $row["sectionnumber"] . "</button></a><hr>";
}
} else { echo "<B>No Sections</B>"; }
$con->close();
?> //Code for displaying the button
<html>
<body>
<form action=">
<input type="number" name="sectionnumber">
<input type="submit" name="add">
</form>
</body>
</html>

PHP/SQL Question regarding updating/deleting in php with a sql database

I'm working on a basic database app which uses a sql database to store and retrieve information from as part of the crud operations the creation and reading of data works perfectly fine. However I'm facing issues with updating and deleting the data stored and it never happened before.Is there something I'm doing wrong?
I'm assuming the something that I've done wrong in update may be similar to my issue in delete.
Here's the code for the update part : [Note this is just for a basic demo and so security features aren't important]
<?php
require "config.php";
require "common.php";
if (isset($_POST['submit'])) {
try {
$connection = new PDO($dsn, $username, $password, $options);
$user =[
"char_id" => $_POST['char_id'],
"char_name" => $_POST['char_name'],
"currency" => $_POST['currency'],
"server_id" => $_POST['server_id'],
"account_id" => $_POST['account_id']
];
$sql = "UPDATE characters
SET
char_name = :char_name,
currency = :currency,
server_id = :server_id,
account_id = :account_id
WHERE char_id = :char_id";
$statement = $connection->prepare($sql);
$statement->execute($user);
} catch(PDOException $error) {
echo $sql . "<br>" . $error->getMessage();
}
}
if (isset($_GET['char_id'])) {
try {
$connection = new PDO($dsn, $username, $password, $options);
$char_id = $_GET['char_id'];
$sql = "SELECT * FROM characters WHERE char_id = :char_id";
$statement = $connection->prepare($sql);
$statement->bindValue(':char_id', $char_id);
$statement->execute();
$user = $statement->fetch(PDO::FETCH_ASSOC);
} catch(PDOException $error) {
echo $sql . "<br>" . $error->getMessage();
}
} else {
echo "Something went wrong!"; //this happens
exit;
}
?>
<?php require "templates/header.php"; ?>
<?php if (isset($_POST['submit']) && $statement) : ?>
<blockquote><?php echo escape($_POST['char_name']); ?> successfully
updated.</blockquote>
<?php endif; ?>
<h2>Edit a character</h2>
<form method="post">
<?php foreach ($user as $key => $value) : ?>
<label for="<?php echo $key; ?>"><?php echo ucfirst($key); ?>
</label>
<input type="text" name="<?php echo $key; ?>" id="<?php echo $key; ?>" value="<?php echo escape($value); ?>" <?php echo ($key === 'id' ? 'readonly' : null); ?>>
<?php endforeach; ?>
<input type="submit" name="submit" value="Submit">
</form>
Back to home
<?php require "templates/footer.php"; ?>
The problem seems to be that your loop of inputs expects an array variable called $user. The $user comes from a DB query, using inputs from your form, but the actual input values comes from the $user variable which isn't set until the DB query is run!
First I would try keeping the $_GET in your code. Your SELECT query expects $_GET['char_id'] to be set in order to execute. Do that by adding ?char_id=SOME NUMBER HERE to your url and go. The number should be a char_id present in your Database.
Now the DB query gets the $_GET['char_id'] that it needs (since the $_GET method fetches parameters from the URL), and you should get some working inputs from your loop, and be able to update entries in your Database.

Form post array to class.php and PDO insert function in db.php

I was wondering if you could help me with a problem when submitting a form to POST values and using a PDO Insert function to enter values into database. Once someone can help me find the issue I will be able to use code over again in form areas. I have checked my $conn PDO statement and it is connected correctly to database just I can not insert the data from form.
My coding layout:
Form located in cust_form.php, names of form fields are as in database with the exception of an autoID generated upon insertion.
Class.php is used to take POST values and to send to Insert function located in db.php.
db.php
<?php
//dbdt database class
if(!class_exists('dbdt')){
class dbdt {
//Connect and select database
function connect() {
try {
require_once('config.php');
$conn = new PDO('mysql:host=localhost;dbname=displaytrends', $DB_USER, $DB_PASS);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
}
//Connect to above
function __construct() {
$this->connect();
}
//Insert data into database
function insert($conn, $table, $fields, $values) {
try{
$fields = implode(", ", $fields);
$values = implode(", ", $values);
$insert = "INSERT INTO $table (autoID, $fields) VALUES ('', $values)";
$query = $handler->prepare($insert);
$query->execute();
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
}
}
}
$dbdt = new dbdt;
?>
class.php
<?php
if(!class_exists('cust_form')){
class cust_form {
/*
CUSTOMER FORM = cust_form.php
*/
function cust_upd_cre_del(){
if ( isset( $_POST['cust_upd'] ) ) {
$int_custID=$_POST['int_custID'];
$cust_company=$_POST['cust_company'];
$cust_address=$_POST['cust_address'];
$cust_postcode=$_POST['cust_postcode'];
$cust_contact_1=$_POST['cust_contact_1'];
$cust_contact_2=$_POST['cust_contact_2'];
$cust_tel=$_POST['cust_tel'];
$cust_mob=$_POST['cust_mob'];
$cust_DDI=$_POST['cust_DDI'];
$cust_email=$_POST['cust_email'];
$cust_notes=$_POST['cust_notes'];
require_once('db.php');
$table = 'customers';
$fields = array(
'int_custID',
'cust_company',
'cust_address',
'cust_postcode',
'cust_contact_1',
'cust_contact_2',
'cust_tel',
'cust_mob',
'cust_DDI',
'cust_email',
'cust_notes'
);
$values = array (
'int_custID' => $int_custID,
'cust_company' => $cust_company,
'cust_address' => $cust_address,
'cust_postcode' => $cust_postcode,
'cust_contact_1' => $cust_contact_1,
'cust_contact_2' => $cust_contact_2,
'cust_tel' => $cust_tel,
'cust_mob' => $cust_mob,
'cust_DDI' => $cust_DDI,
'cust_email' => $cust_email,
'cust_notes' => $cust_notes
);
$insert = $dbdt->insert($conn, $table, $fields, $values);
if ( $insert == TRUE ) {
}
} else {
die('Your form was not submitted.');
}
}
}
}
$cust_form = new cust_form;
?>
cust_form.php
<!doctype html>
<?php
require_once('load.php');
?>
<html>
<head>
<meta charset="UTF-8">
<title>Customer Form</title>
</head>
<body>
<form action="" method="POST" name="cust_details_form" id="cust_details_form">
<label>Account No:</label>
<input type="text" name="int_custID" id="int_custID" />
<label>Company:</label>
<input type="text" name="cust_company" id="cust_company"/>
<label>Address:</label>
<textarea type="text" rows=5 name="cust_address" id="cust_address"></textarea>
<label>Postcode:</label>
<input type="text" name="cust_postcode" id="cust_postcode"/>
<label>Contact 1:</label>
<input type="text" name="cust_contact_1" id="cust_contact_1"/>
<label>Contact 2:</label>
<input type="text" name="cust_contact_2" id="cust_contact_2"/>
<label>Telephone:</label>
<input type="text" name="cust_tel" id="cust_tel"/>
<label>Mobile:</label>
<input type="text" name="cust_mob" id="cust_mob"/>
<label>DDI:</label>
<input type="text" name="cust_DDI" id="cust_DDI"/>
<label>Email:</label>
<input type="email" name="cust_email" id="cust_email"/>
<label>Notes:</label>
<textarea type="text" rows=5 colums=1 name="cust_notes" id="cust_notes"></textarea>
<input type="submit" name="cust_upd" id="cust_upd" value="Update">
<input type="submit" name="cust_del" id="cust_del" value="Delete">
</form>
</body>
</html>
load.php contains require_once db.php, class.php & config.php (contains username and password). This file is okay.
Thanks for any help you may be able to give!
EDITTED
Thanks for all your help! Here is the working code for anyone who needs it!
function ins_upd($table, $values) {
try{
include('config.php');
$conn = new PDO('mysql:host=localhost;dbname=displaytrends;charset=utf8', $DB_USER, $DB_PASS);
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
//Strip $_POST array to fields with values
$values=array_filter($values);
//Take array keys from array
$field_keys=array_keys($values);
//Implode for insert fields
$ins_fields=implode(",", $field_keys);
//Implode for insert value fields (values will binded later)
$value_fields=":" . implode(", :", $field_keys);
//Create update fields for each array create value = 'value = :value'.
$update_fields=array_keys($values);
foreach($update_fields as &$val){
$val=$val." = :".$val;
}
$update_fields=implode(", ", $update_fields);
//SQL Query
$insert = "INSERT INTO $table ($ins_fields) VALUES ($value_fields) ON DUPLICATE KEY UPDATE $update_fields";
$query = $conn->prepare($insert);
//Bind each value based on value coming in.
foreach ($values as $key => &$value) {
switch(gettype($value)) {
case 'integer':
case 'double':
$query->bindParam(':' . $key, $value, PDO::PARAM_INT);
break;
default:
$query->bindParam(':' . $key, $value, PDO::PARAM_STR);
}
}
$query->execute();
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
}
You don't need to send "fields" parameters because if that array is in a different order than "values" your code won't work. Use the array keys from "values":
//Insert data into database
function insert($conn, $table, $values) {
try {
$keys = array_keys($values);
$fields = implode(", ", $keys);
$values = ":" . implode(", :", $keys);
$insert = "INSERT INTO $table ($fields) VALUES ($values)";
$query = $handler->prepare($insert);
foreach ($values as $key => &$value) {
switch(gettype($value)) {
case 'integer':
case 'double':
$query->bindParam(':' . $key, $value, PDO::PARAM_INT);
break;
default:
$query->bindParam(':' . $key, $value, PDO::PARAM_STR);
}
}
$query->execute();
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
}
Hope it helps. I couldn't test it without complete code.
PS: Avoid using prepare to execute SQL statements without using bindParam because you must to quote strings but not integers or floating point numbers.

add checkbox with values from query

i'm trying to create a php web app that will have options to select using checkbox form and then submit the checkedbox to other file. but how can i do this if the value of checkbox is defined with values from query?
please help me, i cant find a solution :/
<form action="addPratosEnc4.php" method="POST">
*Pratos a Adicionar:
<select name="nomeA">
<?php
try
{
$host = "xxxx";
$user ="xxx";
$password = "xxx";
$dbname = $user;
$db = new PDO("mysql:host=$host;dbname=$dbname", $user, $password);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT nomeA FROM Disponivel;";
$result = $db->query($sql);
foreach($result as $row)
{
$nomeA = $row['nomeA'];
/*should be here?*/
}
$db = null;
}
catch (PDOException $e)
{
echo("<p>ERROR: {$e->getMessage()}</p>");
}
?>
</select>
<br>
<br>
<input type="submit" value="Disponibilizar">
</form>
Ok, let's get this straight
You want checkboxes, right! I mean, check!
The nameA column is unique or primary, no duplicates!
the logic and template together
<?php
try {
$host = "xxxx";
$user ="xxx";
$password = "xxx";
$dbname = $user;
$db = new PDO("mysql:host=$host;dbname=$dbname",$user,$password);
$db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$q = "SELECT nomeA FROM Disponivel";
$options = array();
$count = 0;
foreach($db->query($q) as $row) {
$count++;
$options[$row['nomeA']] = '<input type="checkbox" name="dispo[]" value="'.$row['nomeA'].'" />';
}
echo '<p>Rows processed: '.$count.'</p>';
$db = null;
} catch (PDOException $e) {
echo '<p>ERROR: '.$e->getMessage().'</p>';
}
?>
<form action="addPratosEnc4.php" method="POST">
*Pratos a Adicionar:
<?php
if (!$options) echo ' agora no hay pratos';
else foreach ($options as $name => $input) echo '<label>'.$input.' '.$name.'</label><br />';
?>
<br />
<br />
<button type="submit">Disponibilizar</button>
</form>
Try this, ask any questions if you have them and if any solutions worked for you, please mark them as answer
To render the option list you do:
.......
$nomeA = $row['nomeA'];
/*should be here?*/
?> <option value="<?php echo $nomeA; ?>"><?php echo $nomeA; ?></option><?php
}
$db = null;
}
........
This should create a option list within the select that is filled with the results from the query. I assume you meant an option list not checkboxes -
A select box gives you each option and you can only select 1. You could also do this with radiobuttons. On the other hand you may have meant to use Checkbox's where the user can select multiple boxes.
In this case you shouldnt wrap anything in the select just something like
<input type="checkbox" name="group" value="<?php echo $nomeA; ?>">I have a <?php echo $nomeA; ?><br>
within the for loop.
Good Luck
Narimm
echo'<input type ="checkbox" name = "'.$row['nomeA'].'"value = "'.$row['nomeA'].'" />'.$row['nomeA'].'<br />;
instead of :
$nomeA = $row['nomeA'];
remove the select tag and that should work.
just to complete my task, i will post what its need to get the values selected:
<?php
session_start();
$email = $_SESSION['email'];
$nEnc = $_SESSION['nEnc'];
$options = $_REQUEST['dispo'];
echo("<p>$email</p>");
echo("<p>$nEnc</p>");
try
{
$host = "xxxx";
$user ="xxxx";
$password = "xxxx";
$dbname = $user;
$db = new PDO("mysql:host=$host;dbname=$dbname", $user, $password);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
foreach($options as $name){
$nomeA = $name;
$sql = "INSERT INTO RegistoEnc VALUES ('$email',$nEnc,'$nomeA');";
echo("<p>$sql</p>");
$db->query($sql);
};
$db = null;
}
catch (PDOException $e)
{
echo("<p>ERROR: {$e->getMessage()}</p>");
}
echo "<br>Encomenda Criada!!<br>";
?>

Column count doesn't match value count at row 1 when INSERT INTO

I am trying to pass the data into the data base using an array, but I keep getting this error. I checked my code carefully to see if I was missing a column but it doesn't look like it.
What am I doing wrong?
<?php
class inventario {
public function __construct() {}
public function insertar($info) {
if(isset($info)) {
$db_host = 'localhost';
$db_user = 'root';
$db_pass = 'root';
$db_name = 'inventory_cars';
$db_link = mysqli_connect($db_host, $db_user, $db_pass, $db_name) or die('No Connection');
$clean_info = mysqli_real_escape_string($db_link, array_values($info));
$query = mysqli_query( $db_link, "INSERT INTO cars(date, stock, year, make, model, vin, cr) VALUES('" . (string)$clean_info. "')") or die(mysqli_error($db_link));
if($query) {
return 'Record inserted';
}
mysqli_close($db_link);
}
else {
echo 'info variable not set';
}
}
public function table() {
$action = $_SERVER['PHP_SELF'];
$table = '<form name="insertar" method="post" action="' . $action . '"><table><tr><td>Date</td><td><input type="date" name="date"/></td></tr><tr><td>Stock#</td><td><input type="text" name="stock"/></td></tr><tr><td>Year:</td><td><input type="text" name="year"/></td></tr><tr><td>Make:</td><td><input type="text" name="make"/></td></tr><tr><td>Model:</td><td><input type="text" name="model"/></td></tr><tr><td>VIN:</td><td><input type="text" name="vin"/></td></tr><tr><td>CR:</td><td><input type="text" name="cr"/></td></tr><tr><td><input type="submit" value="Submit" name="submit"/></td></tr></table></form>';
return $table;
}
public function stock_list() {
$db_host = 'localhost';
$db_user = 'root';
$db_pass = 'root';
$db_name = 'inventory_cars';
$db_link = mysqli_connect($db_host, $db_user, $db_pass, $db_name) or die('No Connection');
$query = "SELECT * FROM cars";
$result = mysqli_query($db_link, $query) or die('Query fail.. Please wait...');
while($row = mysqli_fetch_array($result)) {
echo '<tr><td>' . $row['date'] . '</td><td>' . $row['year'] . '</td><td>' . $row['make'] . '</td><td>' . $row['model'] . '</td><td>' . $row['vin'] . '</td><td>CR</td></tr>';
}
mysqli_close($db_link);
}
}
?>
<?php
require('inventoryControl.php');
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Inventory</title>
<!--[if lt IE 9]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body>
<div id="wraper">
<div class="add_item">
<?php
$inventario = new inventario;
echo $inventario->table();
if (isset($_POST['submit'])) {
$info = array('date' => $_POST['date'], 'stock' => $_POST['stock'], 'year' => $_POST['year'], 'make' => $_POST['make'], 'model' => $_POST['model'], 'vin' => $_POST['vin'], 'cr' => $_POST['cr']);
if(isset($info)) {
$inventario->insertar($info);
}
else {
echo 'variable not set';
}
}
?>
</div><!--end add item -->
<div class="inventory_list">
<?php
echo '<table>';
$inventario->stock_list();
echo '</table>';
?>
</div><!--end inventory_list -->
</div><!--end wraper -->
</body>
</html>
It looks like you're passing the "submit" value, too.
Output $clean_info to the screen (before you run the query) to debug it.
Echo out the query text you are sending to the database.
The insert statement lists seven columns, :
INSERT INTO cars
(date, stock, year, make, model, vin, cr)
So there need to be seven values in the values list, e.g.
VALUES ('2013-08-22','stk','''74','Dodge','Charger','12345','1500')
I suspect that concatenating (string)$clean_info into the SQL text is not producing a valid statement. This is just basic debugging. Generate that SQL statement into a string, and echo (or vardump) that string out so you can see what's being passed to the database.
With the mysqli interface, you can use paramaterized queries, which is really a better approach. (You don't use mysqli_real_escape_string on the values supplied as bind parameters)
e.g.
$sqltext = "INSERT INTO cars(date,stock,year,make,model,vin,cr) VALUES (?,?,?,?,?,?,?)";
if ($stmt = $mysqli->prepare($sqltext)) {
$stmt->bind_param("sssssss",$date,$stock,$year,$make,$model,$vin,$cr);
$stmt->execute();

Categories