ERROR: Insert data into mySQL - php

When I add data to Database MySQL it fails.
//function add
public function add($name, $director, $cast, $genre,$release,$duration,$thumb,$plot,$another,$reviews,$critic)** {
$query = "INSERT INTO $this->table_name(name,director,cast,genre,release,duration,thumb,plot,another,reviews,critic) "
. "Values('$name','$director','$cast','$genre','$release',$duration,'$thumb','$plot','$another','$reviews',$critic)";
$data = parent::insert($query);
var_dump($query);
return $data;
}
//Add data
$info = new Info_Film();
if (isset($_POST['save'])) {
$name = $_POST['name'];
$director = $_POST['director'];
$cast = $_POST['cast'];`enter code here`
$genre = $_POST['genre'];
$release = $_POST['release'];
$duration = $_POST['duration'];
$thumb = $_POST['thumb'];
$plot = $_POST['plot'];
$another = $_POST['another'];
$reviews = $_POST['reviews'];
$critic = $_POST['critic'];
$info->add($name, $director, $cast, $genre,$release,$duration,$thumb,$plot,$another,$reviews,$critic);
}
?>

echo your old $query then copy and paste it in mysql query editor and Run it. You will what is the actual error and all query variables are blank or not.
$query = "INSERT INTO `$this->table_name` (`name`,`director`,`cast`,`genre`,`release`,`duration`,`thumb`,`plot`,`another`,`reviews`,`critic`) "
. " Values ('$name','$director','$cast','$genre','$release','$duration','$thumb','$plot','$another','$reviews','$critic')";
Echo & check all values then Replace above query.

release is a mysql reserved word, so you would need to quote it in backticks.
However, you could also be sql injecting yourself. You should really switch to a prepared statement to avoid that.
You should also add error handling and display errors during development. Both mysqli and PDO can throw exceptions but you need to tell them to do that.

Related

php mysql UPDATE multiple fields in one record at once

I am trying to UPDATE every field (16 fields plus the key) in a record in a MySQL database with some new data from a form using php. It works fine with INSERT but when I try to change to UPDATE it won't do it. I also feel this is a very long way to do it and there is probably a more iterative solution, I would really appreciate some help please:
<?php
require_once 'login.php';
$con=mysqli_connect($hh,$un,$pw,$db);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
echo 'Connected successfully';
$sql = "UPDATE PiBQ_Config
SET (upButton, dnButton, stepCore1, stepCore2, stepCore3, stepCore4, limSwitch, waitTime, maxPosn, pidKp, pidKi, pidKd, intMax, intMin, sleepTime, progRun) =
('$_POST[upButton]', '$_POST[dnButton]', '$_POST[stepCore1]', '$_POST[stepCore2]', '$_POST[stepCore3]', '$_POST[stepCore4]', '$_POST[limSwitch]', '$_POST[waitTime]', '$_POST[maxPosn]', '$_POST[pidKp]', '$_POST[pidKi]', '$_POST[pidKd]', '$_POST[intMax]', '$_POST[intMin]', '$_POST[sleepTime]', '$_POST[progRun]')
WHERE tableKey = 1";
mysqli_query($con,$sql);
echo "1 record added";
header ('location: ../settings.php');
mysql_close($con)
?>
Set each field individually for example:
"UPDATE PiBQ_Config
SET upButton = '$_POST[upButton]',
dnButton ='$_POST[upButton]',
stepCore1 = '$_POST[dnButton]',
.
.
.//the rest of variables
WHERE tableKey = 1"
This method creates a query from three parameters: the table name, an associative array which has the name of the columns as keys and another whitch has the name of the column you want to update as keys for the where statement.
public function update($table, $data, $where)
{
$query='UPDATE `'.$table.'` SET ';
foreach($data as $key => $value)
{
$query .= '`'.$key.'`=:'.$key.',';
}
$query = substr($query, 0, -1);
$query .= ' WHERE ';
foreach($where as $key => $value)
{
$query .= '`'.$key.'`=:'.$key.',';
}
$query = substr($query, 0, -1);
$data += $where;
$update = $this->db->prepare($query);
$update->execute($data);
}
It will build a query and execute it. You should use PDO and prepared statements for more security.
Example:
for example you want to update the name of a user in the database.
$firstName = 'newFirstName';
$lastName = 'newLastName';
$id = idOfUserYouWantToUpdate;
$table = 'users';
$data = array('user_firstname'=>$firstName, 'user_lastname'=>$lastName);
$where = array('user_id'=>$id)
update($table, $data, $where);

PHP MySQL Query Where x = $variable from function

Why is this not working:
function listOrderComments ($factnr){
global $connection;
//$factnr = 123; //or $factnr = "123"; (Both work)
$query = "SELECT * FROM orderstatus WHERE factuurnummer = '$factnr'";
$result = mysqli_query($connection, $query);
When I echo $factnr I get "123" back.
When I uncommented //$factnr = 123; my function is working.
Looked everywhere for a solution. check the type $factnr is (string).
Well if you're using a variable in your query you're opening yourself up to an injection attack for one.
If you're going to be using that variable I would recommend you use bind_param for your query
Read the PHP manual link below and you will be able to figure out the issue
http://php.net/manual/en/mysqli-stmt.bind-param.php
If you're passing in a variable to your function it should already be set so I don't understand why you're setting it to 123 anyway. So execute the sql statement and bind the parameter following the first example on the PHP docs page.
public function listOrderComments ($factnr)
{
global $connection;
$query = "SELECT * FROM orderstatus WHERE factuurnummer = ?";
$sql->prepare($query);
$sql->bind_param("s", $factnr);
$sql->execute();
$result = $sql->get_result();
$data = mysqli_fetch_all($result, MYSQLI_ASSOC);
foreach ($data as $row) {
print_r($row);
}
}
Then do what you want with the result
You can go with:
$query = "SELECT * FROM orderstatus WHERE factuurnummer = ". $factnr;
Concatenating your code is not good practise. Your best solution is to use PDO statements. It means that your code is easier to look at and this prevents SQL injection from occuring if malice code slipped through your validation.
Here is an example of the code you would use.
<?php
// START ESTABLISHING CONNECTION...
$dsn = 'mysql:host=host_name_here;dbname=db_name_here';
//DB username
$uname = 'username_here';
//DB password
$pass = 'password_here';
try
{
$db = new PDO($dsn, $uname, $pass);
$db->setAttribute(PDO::ERRMODE_SILENT, PDO::ATTR_EMULATE_PREPARES);
error_reporting(0);
} catch (PDOException $ex)
{
echo "Database error:" . $ex->getMessage();
}
// END ESTABLISHING CONNECTION - CONNECTION IS MADE.
$factnr = "123" // or where-ever you get your input from.
$query = "SELECT * FROM orderstatus WHERE factuurnummer = :factnr";
$statement = $db->prepare($query);
// The values you wish to put in.
$statementInputs = array("factnr" => $factnr);
$statement->execute($statementInputs);
//Returns results as an associative array.
$result = $statement->fetchAll(PDO::FETCH_ASSOC);
$statement->closeCursor();
//Shows array of results.
print_r($result);
?>
Use it correctly over "doted" concat. Following will just work fine:
$factnr = 123;
$query = "SELECT * FROM orderstatus WHERE factuurnummer = " . $factnr;
UPDATE:
here is $factnr is passing as argument that supposed to be integer. Safe code way is DO NOT use havvy functions even going over more complicated PDO, but just verify, is this variable integer or not before any operation with it, and return some error code by function if not integer. Here is no danger of code injection into SQL query then.
function listOrderComments ($factnr){
global $connection;
if (!is_int($factnr)) return -1
//$factnr = 123; //or $factnr = "123"; (Both work)
$query = "SELECT * FROM orderstatus WHERE factuurnummer = " . $factnr;
$result = mysqli_query($connection, $query);

How do i troubleshoot this MySQL error?

I'm making a simple website for a class, and I am trying to save information to my database. The error is not very specific and I do not know which part of my code I need to fix.
Error message:
check the manual that corresponds to your MariaDB server version for
the right syntax to use near ')' at line 2
My PHP code:
<?php
include 'mysqli.php' ;
$result = $con->query("select * from setList s
left join songTable t on s.SetList_ID = t.Song_ID
left join bands b on s.SetList_ID = b.Band_ID");
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$setList = $_POST['setlist'];
$venue = $_POST['venue'];
$date = $_POST['dateOfShow'];
$band= $_POST['band'];
$set = $result->fetch_object();
//error handling and form
try {
if (empty($setList) || empty($venue) || empty($date) || empty($band)) {
throw new Exception(
"All Fields Required");
}
if (isset($set)) {
$id = $set->SetList_ID;
$q = "update setList set SetList_Name = '$setList',
Venue = '$venue', Show_Date = $date, Band_Name = '$band')";
}
else{
$q = "insert setList (SetList_Name, Venue, Show_Date, Band_Name)
values ('$setList', '$venue', $date, '$band')";
}
$result = $con->query($q);
if (!$result) {
throw new Exception($con->error);
}
header('Location:my_set-lists.php');
} catch(Exception $e) {
echo '<p class ="error">Error: ' .
$e->getMessage() . '</p>';
}
}
?>
The error message tells you exactly where the problem is; you have an extra ). Replace
$q = "update setList set SetList_Name = '$setList',
Venue = '$venue', Show_Date = $date, Band_Name = '$band')";
// extra ) is here ---------------------------------------------^
With
$q = "update setList set SetList_Name = '$setList',
Venue = '$venue', Show_Date = $date, Band_Name = '$band'";
Note: your next query (starting insert setList) is also going to fail; it should be INSERT INTO setList.... A decent IDE (like PHPStorm) would catch these errors for you.
Also, you are wide open to SQL injection. You really need to be using prepared statements.

PDO/SQL insert not working

got the following code. All values are gotten through javascript and then sent through ajax. The var_dump($array) at the end works and display all the correct values. So they are all passed through correctly. The catch error for the try method also never pops up. The values are not being inserted into the sql table. Whats wrong?
Thanks in advance.
$name = $_GET['name'];
$category = $_GET['category'];
$subCategory = $_GET['subCategory'];
$date = $_GET['date'];
$address = $_GET['address'];
$city = $_GET['city'];
$state = $_GET['state'];
$host = $_GET['host'];
$imagePath = $_GET['imagePath'];
$info = $_GET['info'];
//turn into array
$array = array();
$array[0]=$name;
$array[1]=$category;
$array[2]=$subCategory;
$array[3]=$date;
$array[4]=$address;
$array[5]=$city;
$array[6]=$state;
$array[7]=$host;
$array[8]='j';//$imagePath;
$array[9]=$info;
try {
$con = new PDO('mysql:host=localhost;dbname=test');
$insert = $con->prepare(" INSERT INTO create
(name,category,subCategory,date,address,city,state,host,imagePath,info)
VALUES (?,?,?,?,?,?,?,?,?,?) ");
$insert->execute($array);
}
catch(PDOException $e) { //try
echo 'error';
//echo 'ERROR: ' . $e->getMessage();
}
var_dump($array);
create is a reserved word in mysql so you need to quote it in backticks:
INSERT INTO `create` ...
To have PDO throw exceptions, you need to add that after you open your connection:
$con = new PDO('mysql:host=localhost;dbname=test');
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
By the way, I assume that you are logging into your database with a username and a password as well (the second and third parameter of the PDO constructor)...

PHP5 Mysqli class is not outputting data

So i am trying to make a backup class and this is what I have so far. Issue is the $tbl_data is empty. What am I doing wrong.
The connection to the database is successful.
Without the 'echo $tbl_data', the '$current_table - current table' output is correct but if 'echo $tbl_data' is used, only the first table is shown ( trying to backup two tables to begin with ).
class mBackup{
private $_connection = ""; //db connection var
private $output = ""; //sql output
private $tbl_data = "";
private $tbl_row = "";
private $nfields = "";
private $create_table_query = "";
private $create_table_output = "";
public function __construct($dbhost,$dbname,$dbuser,$dbpassword){
$this->_connection = new mysqli($dbhost,$dbuser,$dbpassword,$dbname);
//possible connection error
if($this->_connection->connect_errno){
echo "Failed to connect to the DB";
}
else{
echo "Connected<br />";
}
}
public function backup_db(){
//get the table names from the DB and store in an array
$result = $this->_connection->query("SHOW TABLES");
//get the TABLE names
while($row = $result->fetch_row())
{
$table_names[] = $row[0];
}
//For each table
foreach($table_names as $current_table)
{
echo $current_table." - current table<br />"; //debug
$tbl_data = "";
$tbl_row = "";
$nfields = "";
$create_table_query = "";
$create_table_output = "";
//SELECT Everything from the table in use
$query = $this->_connection->prepare("SELECT * FROM ?");
$query->bind_param('s', $current_table);
$query->execute();
$query->bind_result($tbl_data);
$query->fetch();
echo $tbl_data."<br/>";
}
}
Try something like:
while ($query->fetch()) {
echo $tbl_data;
}
and see if that gets you anything. From the little that I know, bind_result binds columns in the result set to variables. If your table has 5 columns, you should have bind_result($var1, $var2, $var3, $var4, $var5) but since your number of columns are going to change depending on the table, I don't know if bind_result will give you what you need.
Try closing the prepared statement after every loop
$query->close();
or resetting.
$query->reset()
You can't use ? for the table name. See the second note in http://www.php.net/manual/en/mysqli.prepare.php for the allowed places for markers. So you'll have to construct the query by normal variable interpolateion:
$select = sprintf("SELECT * FROM `%s`", $current_table);
$result = $this->_connection->query($select);

Categories