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();
Related
I am trying to enter data from html into MSSQL database using php. I am unable to insert record in 2 different tables and unable to insert multiple records to a table, I have the code below
<?php
$name = $_POST["name"];
$email = $_POST["email"];
$company = $_POST["company"];
$contact = (int)$_POST["contact"];
$worktitle = $_POST["worktitle"];
$industry = $_POST["industry"];
$V101 = $_POST["part2q1"];
$V102 = $_POST["part2q2"];
$V103 = $_POST["part2q3"];
$V104 = $_POST["part2q4"];
$V105 = $_POST["part2q5"];
$V106 = $_POST["part2q6"];
$V107 = $_POST["part3q1"];
$V108 = $_POST["part3q2"];
$V109 = $_POST["part3q3"];
$V110 = $_POST["part3q4"];
$V111 = $_POST["part3q5"];
$V112 = $_POST["part3q6"];
$V113 = $_POST["part4q1"];
$V114 = $_POST["part4q2"];
$V115 = $_POST["part4q3"];
$V116 = $_POST["part4q4"];
$V117 = $_POST["part4q5"];
$V118 = $_POST["part4q6"];
$V119 = $_POST["part5q1"];
$V120 = $_POST["part5q2"];
$V121 = $_POST["part5q3"];
$V122 = $_POST["part5q4"];
$V123 = $_POST["part5q5"];
$V124 = $_POST["part5q6"];
$V125 = $_POST["part6q1"];
$V126 = $_POST["part6q2"];
$V127 = $_POST["part6q3"];
$V128 = $_POST["part6q4"];
$V129 = $_POST["part6q5"];
$V130 = $_POST["part6q6"];
$V131 = $_POST["part7q1"];
$V132 = $_POST["part7q2"];
$V133 = $_POST["part7q3"];
$V134 = $_POST["part7q4"];
$V135 = $_POST["part7q5"];
$V136 = $_POST["part7q6"];
$V137 = $_POST["part7q7"];
$V138 = $_POST["part7q8"];
$V139 = $_POST["part8q1"];
$V140 = $_POST["part8q2"];
$V141 = $_POST["part8q3"];
$V142 = $_POST["part8q4"];
$V143 = $_POST["part8q5"];
$V144 = $_POST["part8q6"];
$currenttime = date("Ymd h:m:sa");
$server = "***";
$connOptions = array("Database"=>"**", "UID"=>"**", "PWD"=>"**!");
$conn = sqlsrv_connect($server, $connOptions);
if($conn){
$query="INSERT INTO dbo.profile (
name,
email,
company,
telephone,
worktitle,
industry,
createdate
)
VALUES (?, ?, ?, ?, ?, ?,getdate())";
$params = array(
$name,
$email,
$company,
$contact,
$worktitle,
$industry,
$currenttime
);
if(sqlsrv_query($conn, $query, $params)){
echo "<h4>Thank you</h4><p>You have completed the survey and your answers have been received.</p>";
} else {
echo "<p>We're sorry but there has been and error receiving your answers.</p>";
}
} else {
echo "<p>We're sorry but there has been and error receiving your answers. </p>";
}
Im trying to insert records to another table like this continuing from the previous line:
if($conn){
$query1="INSERT INTO dbo.SurveyResponse (
profileid,
Value,
CreatedOn
)
VALUES ('2', ?, ?, ?, ?, ?,getdate())";
$params=array($V101,$currenttime);
$query1="INSERT INTO dbo.SurveyResponse (
profileid,
Value,
CreatedOn
)
VALUES ('2', ?, ?, ?, ?, ?,getdate())";
$params=array($V102,$currenttime);
$query1="INSERT INTO dbo.SurveyResponse (
profileid,
Value,
CreatedOn
)
VALUES ('2', ?, ?, ?, ?, ?,getdate())";
$params=array($V103,$currenttime);
. . . . .
if(sqlsrv_query($conn, $query1, $params))
{
echo "<h4>Thank you</h4><p>You have completed the survey and your answers have been received.</p>";
} else {
echo "<p>We're sorry but there has been and error receiving your answers.</p>";
}
} else {
echo "<p>We're sorry but there has been and error receiving your answers. </p>";
}
?>
I have been trying this, insert works for first table but not the second table, can anyone help please
The following worked for me to enter multiple records to second table. Thanks to Miken32
if($conn){
$query1="INSERT INTO dbo.SurveyResponse (
profileid,
Qid,
Value,
CreatedOn
)
VALUES (?, ?, ?,getdate())";
$params1=array(2,101,$V101,$currenttime);
if(sqlsrv_query($conn, $query1, $params1))
{
echo "";
}
else { echo"<p>We're sorry but there has been and error receiving your answers.</p>" ; }
}
if($conn){
$query2="INSERT INTO dbo.SurveyResponse (
profileid,
Qid,
Value,
CreatedOn
)
VALUES (?, ?, ?,getdate())";
$params2=array(2,102,$V102,$currenttime);
if(sqlsrv_query($conn, $query2, $params2))
{
echo "";
}
else { echo"<p>We're sorry but there has been and error receiving your answers.</p>" ; }
}
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.
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());
}
I'm stumped, I recently had this working in plain Mysqli statements, but was told to avoid injection to write it using prepared statements. The truncate is the only thing that seems to work. Any advice?
$con=mysqli_connect(localhost,"username","password","db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$deletetable = $con->prepare('TRUNCATE TABLE twitch_streams');
$deletetable->execute();
$deletetable->close();
$result = $con->prepare("SELECT field_value
FROM xf_user_field_value
WHERE field_id = 'twitch'
AND field_value != ''");
$result->bind_result($twitchfield);
while($result->fetch())
{
printf("%s\n", $twitchfield);
$username[] = $twitchfield;
$data = json_decode(file_get_contents('http://api.justin.tv/api/stream/l ist.json?channel=' . $username[0]));
$viewer[] = $data[0]->channel_count;
$insert = $con->prepare("INSERT INTO twitch_streams (twitchuser, viewercount)
VALUES (?, ?)");
$insert->bind_param('si', $twitchuser, $viewercount);
$twitchuser = $username[0];
$viewercount = $viewer[0];
$insert->execute();
echo $twitchuser;
echo $viewercount;
$insert->close();
}
$result->close();$deletetable = $con->prepare('TRUNCATE TABLE twitch_streams');
$deletetable->execute();
$deletetable->close();
$result = $con->prepare("SELECT field_value
FROM xf_user_field_value
WHERE field_id = twitch
AND field_value != ''");
$result->bind_result($twitchfield);
while($result->fetch())
{
printf("%s\n", $twitchfield);
$username[] = $twitchfield;
$data = json_decode(file_get_contents('http://api.justin.tv/api/stream/l ist.json? channel=' . $username[0]));
$viewer[] = $data[0]->channel_count;
$insert = $con->prepare("INSERT INTO twitch_streams (twitchuser, viewercount)
VALUES (?, ?)");
$insert = bind_param('si', $twitchuser, $viewercount);
$twitchuser = $username[0];
$viewercount = $viewer[0];
$insert->execute();
echo $twitchuser;
echo $viewercount;
$insert->close();
}
$result->close();
mysqli_close($con);
There is no function bind_param(), it is a method of mysqli_stmt
You use it like so:
$insert->bind_param()
Check here for more information on mysqli_stmt
I've a few examples but nothing that I can grasp. I have the below code, the echos work but the insert does not. I believe I'm suppose to explode these? Not sure but maybe someone can give me a hint with my own example.
$con=mysqli_connect(localhost,"username","password","db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$deletetable = $con->prepare('TRUNCATE TABLE twitch_streams');
$deletetable->execute();
$deletetable->close();
$result = $con->prepare("SELECT field_value
FROM xf_user_field_value
WHERE field_id = 'twitch'
AND field_value != ''");
$result->bind_result($twitchfield);
while($result->fetch())
{
printf("%s\n", $twitchfield);
$username[] = $twitchfield;
$data = json_decode(file_get_contents('http://api.justin.tv/api/stream/l ist.json?channel=' . $username[0]));
$viewer[] = $data[0]->channel_count;
$insert = $con->prepare("INSERT INTO twitch_streams (twitchuser, viewercount)
VALUES (?, ?)");
$insert = bind_param('si', $twitchuser, $viewercount);
$twitchuser = $username[0];
$viewercount = $viewer[0];
$insert->execute();
echo $twitchuser;
echo $viewercount;
$insert->close();
}
$result->close();$deletetable = $con->prepare('TRUNCATE TABLE twitch_streams');
$deletetable->execute();
$deletetable->close();
$result = $con->prepare("SELECT field_value
FROM xf_user_field_value
WHERE field_id = twitch
AND field_value != ''");
$result->bind_result($twitchfield);
while($result->fetch())
{
printf("%s\n", $twitchfield);
$username[] = $twitchfield;
$data = json_decode(file_get_contents('http://api.justin.tv/api/stream/l ist.json? channel=' . $username[0]));
$viewer[] = $data[0]->channel_count;
$insert = $con->prepare("INSERT INTO twitch_streams (twitchuser, viewercount)
VALUES (?, ?)");
$insert = bind_param('si', $twitchuser, $viewercount);
$twitchuser = $username[0];
$viewercount = $viewer[0];
$insert->execute();
echo $twitchuser;
echo $viewercount;
$insert->close();
}
$result->close();
mysqli_close($con);
You're missing quotes around your string values:
"INSERT INTO twitch_streams (twitchuser, viewercount)
VALUES ($username[0], $viewer[0])"
should be
"INSERT INTO twitch_streams (twitchuser, viewercount)
VALUES ('$username[0]', '$viewer[0]')"
You would spot this error easily if you add error handling to your code. Look into using mysqli_error().
$result = mysqli_query($con,"INSERT INTO twitch_streams (twitchuser, viewercount)
VALUES ('$username[0]', '$viewer[0]')");
if (!result) {
// This should be done better than this
echo mysqli_error();
exit;
}
Since I can't tell from your code what the source of $data[0]->channel_count is I will also mention that you should at least escape your insert variables with mysqli_real_escape_string(). Even better, use prepared statements.