This one has had me stumped for a while I cannot see why I am getting this error. This is my code
<?php
include('include/auth.php');
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
if(isset($_POST['submit']))
{
$serverName = "localhost";
$connectionInfo = array( "Database"=>"db", "UID"=>"sa", "PWD"=>"****");
$conn = sqlsrv_connect( $serverName, $connectionInfo );
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
$pathfinderid = $_POST['pathfinderid'];
$locationid = $_POST['locationid'];
$status = $_POST['status'];
$statusnote = $_POST['statusnote'];
$user = $_SESSION['SESS_USER'];
$date = new DateTime();
$ims = 'New Device Added';
if(empty($pathfinderid) || empty($locationid) || empty($status) || empty($statusnote)) {
echo "<div id='source'><p style='color:red;'>Please complete all fields</p></div>";
}
else
{
//SQL to check if pathdnder exsists
$stmt = sqlsrv_query( $conn, "SELECT * FROM devices WHERE pathfinderid='$pathfinderid'");
//If statement to check rows
if ($stmt) {
$rows = sqlsrv_has_rows( $stmt );
if ($rows === true) {
echo "<div id='source'><p style='color:red';>PathfinderID already exists</div>";
}
else
{
//Insert in to Devices Table
$tsql="INSERT INTO devices (pathfinderid, locationid, addeddate, status, creation_date, status_note) VALUES (?,?,?,?,?,?)";
$var = array ($pathfinderid, $locationid, $date, $status, $date, $statusnote);
if (!sqlsrv_query($conn, $tsql, $var)) {
die('Error: ' . sqlsrv_errors());
}
//Insert in to Transaction Log
$tsql="INSERT INTO transaction_log (Date, IMS, PathfinderID, LocationID, TransactionNotes, ManagedBy) VALUES (?,?,?,?,?,?,?)";
$var = array ($date, $ims, $pathfinderid, $locationid, $statusnote, $statusnote, $user);
if (!sqlsrv_query($conn, $tsql, $var)) {
die('Error: ' . sqlsrv_errors());
}
//Insert in to Movment Log
$tsql="INSERT INTO movement_log (pathfinderid, locationid, status, update_timestamp, addeddate, status_note) VALUES (?, ?, ?, ?, ?, ?')";
$var = array ($pathfinderid, $locationid, $status, $date, $date, $statusnote);
if (!sqlsrv_query($conn, $tsql, $var)) {
die('Error: ' . sqlsrv_errors());
}
//Display the confirmation messgae
echo "<div id='source'><p style='color:green;'>Device Added</p></div>";
}
}
}
}
?>
The error is flagging as beng on line 52 which is:
//Insert in to Transaction Log
$tsql="INSERT INTO transaction_log (Date, IMS, PathfinderID, LocationID, TransactionNotes, ManagedBy) VALUES (?,?,?,?,?,?,?)";
$var = array ($date, $ims, $pathfinderid, $locationid, $statusnote, $statusnote, $user);
if (!sqlsrv_query($conn, $tsql, $var)) {
die('Error: ' . sqlsrv_errors());
}
Any ideas? The only thing I can think is if it is because I am reusing variable names?
You've got a double variable ($statusnote)
//Insert in to Transaction Log
$tsql="INSERT INTO transaction_log (Date, IMS, PathfinderID, LocationID, TransactionNotes, ManagedBy) VALUES (?,?,?,?,?,?,?)";
$var = array ($date, $ims, $pathfinderid, $locationid, $statusnote, $statusnote, $user);
if (!sqlsrv_query($conn, $tsql, $var)) {
die('Error: ' . sqlsrv_errors());
}
should be
//Insert in to Transaction Log
$tsql="INSERT INTO transaction_log (Date, IMS, PathfinderID, LocationID, TransactionNotes, ManagedBy) VALUES (?,?,?,?,?,?)";
$var = array ($date, $ims, $pathfinderid, $locationid, $statusnote, $user);
if (!sqlsrv_query($conn, $tsql, $var)) {
die('Error: ' . sqlsrv_errors());
}
Related
I have found similar questions on here, but nothing quite right for my situation. I need to make multiple entries to a database from a combination of values from a set of arrays and repeated strings. To give an example:
$sql = "INSERT INTO sonch_MAIN.Concert (venue_id, date, ensemble_id, info, title, repertoire, time)
VALUES ('$venue', '$date', '1', '$info', '$title', '$repertoire_formatted', $time)";
$venue, $time, AND $date are arrays.
'1' should be added to EACH entry to the database without change.
$info, $title, AND $repertoire_formatted are strings that should be repeated, i.e., inserted without any variation, for each entry to the database.
So the following example shows what the contents of each variable might be:
$venue = array('venue1', 'venue7', 'venue50');
$date = array('2019-01-01', '2019-02-02', '2019-03-03');
$time = array('20:00:00', '19:00:00', '18:00:00');
$info = 'General info about this event';
$repertoire_formatted = 'Music that people will play at this event';
My SQL database is set up to take the different types of data for each input variable.
HERE is the code I have (not working):
session_start();
$_SESSION["servername"] = "localhost";
$_SESSION["username"] = "sonch_nB";
$_SESSION["password"] = 'hello';
$_SESSION["dbname"] = "sonch_MAIN";
date_default_timezone_set('Europe/Zurich');
$venue = ($_POST['venue']);
$date = ($_POST['date']);
$ensemble_id = '1'; //THIS WILL BE SET VIA LOGIN
$info = ($_POST['info']);
$title = ($_POST['title']);
//FORMAT INCOMING VARS CODE SKIPPED//
// Create connection
$conn = new mysqli($_SESSION['servername'], $_SESSION['username'], $_SESSION['password'], $_SESSION['dbname']);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//NEED TO LOOP INPUT TO MYSQL NUMBER OF VALUES IN ARRAY
$stmt = $conn->prepare("INSERT INTO sonch_MAIN.Concert (venue_id, date, ensemble_id, info, title, repertoire, time) VALUES (?, ?, '1', ?, ?, ?, ?)");
$stmt->bind_param("ssssss", $v, $d, $info, $title, $repertoire_formatted, $t);
for ($i = 0; $i < count($venue); $i++) {
$v = $venue[$i];
$d = $date[$i];
$t = $time[$i];
$stmt->execute();
}
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$stmt->close();
You should use a prepared statement. In MySQLi (assuming your connection is $conn):
$stmt = $conn->prepare("INSERT INTO sonch_MAIN.Concert (venue_id, date, ensemble_id, info, title, repertoire, time)
VALUES (?, ?, '1', ?, ?, ?, ?)");
$stmt->bind_param("ssssss", $v, $d, $info, $title, $repertoire_formatted, $t);
for ($i = 0; $i < count($venue); $i++) {
$v = $venue[$i];
$d = $date[$i];
$t = $time[$i];
if ($stmt->execute() === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $conn->error;
}
}
$stmt->close();
I made this script to generate a string and insert it into a database,
but it doesn't insert into the database even though i get no errors what so ever.
$pare = $id;
$time_stamp = date('H:m');
$token = 'token'. md5($pare . $time_stamp);
echo " Token: -" . $token;
try {
$database = $this->server->connect_to_database('3250900');
$sql_query_string = "INSERT INTO `authentication_tokens` (`id`, `user_id`, `token`, `timestamp`) VALUES (:n, :user_id, :token, :time_stamp)";
$statement = $database->prepare($sql_query_string); //Prepare the sql statement
$statement->execute([ ':n' => NULL,
':user_id' => $pare,
':token' => $token,
':time_stamp' => $time_stamp]); //execute query
} catch (Exception $e) {
echo $e;
}
print_r($statement);
Try this code:
$pare = $id;
$time_stamp = date('H:m');
$token = 'token'. md5($pare . $time_stamp);
echo " Token: -" . $token;
try {
$database = $this->server->connect_to_database('3250900');
$stmt = $database ->prepare ("INSERT INTO `authentication_tokens` (`id`, `user_id`, `token`, `timestamp`) VALUES (:n, :user_id, :token, :time_stamp)");
$stmt -> bindParam(':n', NULL);
$stmt -> bindParam(':user_id', $pare);
$stmt -> bindParam(':token', $token);
$stmt -> bindParam(':timestamp', $time_stamp);
$result = $stmt -> execute();
}
catch (PDOException $e) {
trigger_error('Error occured while trying to insert into the DB:' . $e->getMessage(), E_USER_ERROR);
}
if ($result) {
return $stmt->rowCount();
}
A friend of mine has made a website for his computer science class. He made a php script with which you can add a steamgame with it's ID (example, CS:GO with ID 730). My question is, is it possible to make a script.
Here is his code.
<?php
//$gamesxml = file_get_contents("http://api.steampowered.com/ISteamApps/GetAppList/v0001");
//$gamesjson = json_decode($gamesxml);
//$gamesarray = $gamesjson->applist->apps->app; //["applist"]["apps"]["app"];
set_time_limit(999999);
// Create mysql connection
$conn = mysqli_connect("", "", "", "");
#mysqli_select_db($conn, "gamereviews") or die("Unable to select database");
if(!array_key_exists("steamid", $_POST)){
echo "Er is geen steamid gegeven.";
return;
}
$steamid = htmlspecialchars($_POST["steamid"]);
$gamexml = file_get_contents("http://store.steampowered.com/api/appdetails?appids=" . $steamid);
$gamejson = json_decode($gamexml);
if ($gamejson->$steamid->success != "true") {
return;
}
$gamedata = $gamejson->$steamid->data;
if ($gamedata->type != "game") {
return;
}
//Data
$name = $gamedata->name;
$date = $gamedata->release_date->date;
$genres = "";
$genrefirst = true;
foreach ($gamedata->genres as $genre) {
if (!$genrefirst) {
$genres .= ", ";
}
$genrefirst = false;
$genres .= $genre->description;
}
$shortdescription = $gamedata->short_description;
$description = $gamedata->detailed_description;
$about = $gamedata->about_the_game;
$price = array_key_exists("price_overview", $gamedata) ? $gamedata->price_overview->initial : 0;
$languages = $gamedata->supported_languages;
$headerimage = $gamedata->header_image;
$website = $gamedata->website;
$metacritic_score = array_key_exists("metacritic", $gamedata) ? $gamedata->metacritic->score : -1;
$metacritic_url = array_key_exists("metacritic", $gamedata) ? $gamedata->metacritic->url : "";
$videourl = array_key_exists("movies", $gamedata) ? $gamedata->movies[0]->webm->max : "";
$recommendations = $gamedata->recommendations->total;
$backgroundimg = $gamedata->background;
//Statement 1: Verwijder alle games met hetzelfde appid
$stmt = mysqli_prepare($conn, "DELETE FROM games WHERE steamid=?");
$stmt->bind_param("s", $steamid);
if (!$stmt->execute()) {
echo "SQL 1 gefaald voor $steamid<br>";
return;
}
//Statement 2: Voeg nieuwe game toe
$stmt = mysqli_prepare($conn, "INSERT INTO games (name, steamid, date, genre, shortdescription, description, aboutthegame, price, languages, headerimg, website, metacritic_score,
metacritic_url, videourl, recommendations, backgroundimg) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
$stmt->bind_param("sisssssssssissis", $name, $steamid, $date, $genres, $shortdescription, $description, $about, $price, $languages, $headerimage, $website,
$metacritic_score, $metacritic_url, $videourl, $recommendations, $backgroundimg);
if (!$stmt->execute()) {
echo "SQL 2 gefaald voor $steamid<br>";
echo mysqli_error($conn);
return;
}
//
$result = #mysqli_query($conn, $stmt);
echo "true";
?>
This code will add it to the database. This is not the post script, which I can send too if you want.
I'm having an issue with a piece of my code. It works perfectly fine, except it won't save itself to the database. This is the code:
function createOrder($user, $cart, $price, $method) {
try {
$username = "root";
$password = "";
$connection = new PDO('mysql:host=localhost;dbname=dreamlineslaapsystemen', $username, $password);
$connection->beginTransaction();
$productList=$_SESSION['products'];
$orderList=$_SESSION['orders'];
$orderItems=$_SESSION['orderitems'];
$orderid = generateOrderid();
$allOrders = array();
for($i=0; $i<count($orderList); $i++) {
array_push($allOrders, $orderList[$i]->getID());
}
while(in_array($orderid, $allOrders)) {
$orderid = generateOrderid();
}
$today = date("Y-m-d H:i:s");
$order = new Order($orderid, $user->getID(), $price, $today, $method);
$newOrder = array(
':id' => $orderid,
':userid' => $user->getID(),
':date' => $today,
':method' => $method
);
$addOrder = $connection->prepare('INSERT INTO orders(id, userid, date) VALUES (:id, :userid, :date, :method');
$addOrder->execute($newOrder);
array_push($orderList, $order);
foreach($cart->getCart() as $item => $amount) {
$itemid=null;
for($i=0; $i<count($productList);$i++) {
if($productList[$i]->getID()==$item) {
$orderitem = new Orderitem($orderid, $i, $amount);
array_push($orderItems, $orderitem);
$newOrderitem = array(
':orderid' => $orderid,
':productid' => $i,
':amount' => $amount
);
$addOrderitem = $connection->prepare('INSERT INTO orderitems(orderid, productid, amount) VALUES (:orderid, :productid, :amount');
$addOrderitem->execute($newOrderitem);
}
}
}
$connection->commit();
$_SESSION['orders']=$orderList;
$_SESSION['orderitems']=$orderItems;
return $orderid;
} catch(PDOException $e) {
$connection->rollback();
print "Er is iets fout gegaan: " . $e->getMessage() . "<br>";
return null;
}
}
It does add everything to the arrays and sessions and when I do var_dump to see if it is all stored correctly in the sessions/arrays. It just won't add to the database.
You have 3 columns yet you are inserting 4 values. I assume you have a method column in your table and your insert statements lacks closing ) parenthesis.
$addOrderitem = $connection->prepare('INSERT INTO orderitems(orderid, productid, amount, method) VALUES (:orderid, :productid, :amount, :method'));
$addOrderitem = $connection->prepare('INSERT INTO orderitems(orderid, productid, amount) VALUES (:orderid, :productid, :amount'));
I am trying to insert image path into an existing databse. The code below works, but inserts a new row.
$address= htmlentities($_SESSION['address']);
$city= htmlentities($_SESSION['city']);
$zip_code= htmlentities($_SESSION['zip_code']);
$query =
"INSERT INTO property(name, size, type_picture, file_path, username) VALUES (?,?,?,?,?)";
$conn = $db->prepare($query);
if ($conn == TRUE) {
$conn->bind_param("sisss", $myfile, $fileSize, $fileType, $path, $username);
if (!$conn->execute()) {
echo 'error insert';
}else {
echo 'Success!<br/>';
echo '<img src="' . DISPLAY_PATH . $myfile . '"/>';
}
} else {
die("Error preparing Statement");
When I try the same as above but UPDATE, i get the "Error preparing Statement". I need to update empty cells (if this matters).
$query =
"UPDATE property(name, size, type_picture, file_path, username)
SET(?,?,?,?,?)
WHERE address = '$address' // with or without ''
city = '$city' ";
$conn = $db->prepare($query);
if ($conn == TRUE) {
$conn->bind_param("sisss", $myfile, $fileSize, $fileType, $path, $username);
if (!$conn->execute()) {
echo 'error insert';
} // etc. etc.
Thank you so much. Tried for a day, need some help.
Your update query is wrong, try this instead:
$query = "UPDATE property SET name = ?, size = ?, type_picture = ?, file_path = ?, username = ?
WHERE address = ? AND city = ?"
$conn = $db->prepare($query);
if ($conn == TRUE) {
$conn->bind_param("sisss", $myfile, $fileSize, $fileType, $path, $username,$address,$city);
if (!$conn->execute()) {
echo 'error update';
}
}
You need an AND or OR in the WHERE statement:
WHERE address = '$address' AND // with our without ''
city = '$city' ";
I also don't think you should mix parameters with string substitution. Make $address and $city parameters as well.