Insert statement from php script to mysql: Database not reading insert statement - php

So everything up to the insert statement works perfectly. I know the database is connecting because I can select information from the database with the first two statements. I also know that the execute_statment3 works because no errors are being printed off and when it is put into the sql the statement is inserted the way it should be. Therefore the problem lies somewhere with the communication between the script and phpmyadmin. Please help I have been staring at this problem for two days and am going rather crazy.
<?php
session_start();
$hostname = 'localhost';
$username = '####';
$password = '####';
$connection = mysql_connect($hostname, $username, $password)
or die ('Connection error!!!');
$database = '####';
mysql_select_db($database);
$uid = $_SESSION['ID'];
$album = $_POST['albumname'];
$description = $_POST['description'];
$filename = $_FILES["upload_file"]["name"];
$filetype = $_FILES["upload_file"]["type"];
$filesize = $_FILES["upload_file"]["size"];
$file_on_server = $_FILES["upload_file"]["tmp_name"];
if ($filetype == "image/jpeg") {
$file_copy_name = date(m.d.y_H.i.s) . ".jpg";
copy($file_on_server, "uploads/" . $file_copy_name);
print "<br>";
print "<img src = \"uploads/$file_copy_name\">";
print "<br>";
$ret = system("pwd");
$picture = "uploads/$file_copy_name";
}
$execute_statement = "SELECT * FROM ImageAlbums WHERE Album = '$album'";
$results = mysql_query($execute_statement) or die ('Error executing SQL statement!!!');
while($item = mysql_fetch_array($results))
{
$album2 = $item['Album'];
}
if ($album2 == $album)
{
$execute_statement2 = "SELECT * FROM ImageAlbums WHERE Album = '$album'";
$results2 = mysql_query($execute_statement2) or die ('Error executing SQL statement2!!!');
while ($row2 = mysql_fetch_array($results2)) {
$AID = $row2["AlbumID"];
}
$execute_statement3 = "INSERT INTO Images (`ImageID`, `AlbumID`, `Description`, `Extensions`) VALUES ('NULL', '$AID', '$description', '$file_copy_name')";
($execute_statement3) or die ('Error executing SQL statement3!!!');
}
print "<br>";
print "<br>";
print $execute_statement3;
print "<br>";
print "<br>";
print $AID;
print "<br>";
print "<br>";
print $picture;
?>
I am using two databases for this script one of the databases is called ImageAlbums and has two columns called AlbumID and Album (AlbumID being a primary key). The second table is called Images and has four columns ImageID (primary key), AlbumID (foreign key), Description and Extensions.

You are not running the statement
($execute_statement3) or die ('Error executing SQL statement3!!!');
Try:
mysql_query($execute_statement3);
Also, make sure you escape all the variables.

make sure that the user you are connecting with in the php script has privileges for insert statements. you could be using a db user with only select privs...

Related

How can I use a for loop to insert data from a csv table to a sql database?

This is the sample csv file I'm using:
Column1,Column2,Column3
data1,data2,data3
data1,data2,data3
data1,data2,data3
data1,data2,data3
The purpose of my program is to insert this table into a php file via command line and insert the data into an SQL database. I'm using this project as a way of learning how to use MySql.
A csv file is taken and the data is then converted into an array or arrays. A database is then created and the data is supposed to be inserted into the table.
Instead of my data being inserted, I get only one row with null values.
<?php
/**
* Created by PhpStorm.
* User:
* Date: 6/16/2017
* Time: 11:32 AM
*/
$servername = "localhost";
$username = "pop-user";
$password = "pop-pw";
$database = 'popdb';
parse_str(implode('&', array_slice($argv, 1)), $_GET);
$file = array_map('str_getcsv', file($argv[1]));
// connecting to MySQL
$link = mysqli_connect($servername,$username,$password);
// check if connection completed
if ($link->connect_error) {
die("Connection failed: ". $link->connect_error);
}
//creating database
printf("Creating database...\n");
$dbcheck = mysqli_select_db($link, $database);
// if database doesn't exist, then one will be created
if (!$dbcheck) {
$sql = 'CREATE DATABASE '. $database;
if (mysqli_query($link, $sql)) {
echo "Database ". $database ." created\n";
}
else {
echo "Failed to create database:\n";
echo $link->error."\n";
}
}
printf("Creating table...");
//creating table to hold information
$sql = 'USE '. $database. ';';
printf("\r\n");
mysqli_query($link,$sql);
$sql2 = "CREATE TABLE popCensus (";
foreach ($file[0] as $rows) {
if ($rows != end($file[0]))
$sql2 .= "{$rows} varchar(33), ";
else
$sql2 .= "{$rows} varchar(33)";
}
$sql2 .= ");";
echo $sql2;
printf("\r\n");
mysqli_query($link,$sql2);
printf("Inserting data into table...\n");
$cnt = 1;
$sql3 = "";
//Not inserting data
foreach ( $file as $file[$cnt]) {
$sql3 = "INSERT INTO popcensus VALUES ( ";
foreach ($file[$cnt] as $rows) {
if ($rows != end($file[$cnt]))
$sql3 .= "{$rows} , ";
else
$sql3 .= "{$rows});";
}
printf($sql3);
printf("\n");
mysqli_query($link, $sql3);
$cnt++;
printf("cnt: ". $cnt."\n");
$sql3 = "";
}
printf("\nDone\n");
mysqli_close($link);
?>
edit: I'm able to parse the information into an arrays of arrays. the problem I'm having is trying to insert them into a table afterwards.
you need to use prepared statement inside the loop
Try checking the query for an error result inside the foreach loop.
if (false === mysqli_query($link, $sql3)) {
throw new Exception(mysqli_error($link));
}
Beyond that, you should really be using a prepare statement.

creating new db rows from data in array?

Hey guys im trying to pass some data from an (oracle) fetch_array to a variable array and then use that array data to check if the data exists on a mysql db and create any rows that dont currently exist.. this is what i have so far.
the problem is its only checks/creates 1 entry of the array and doesn't check/created the entire array data. i think i would need to use a for loop to process all the array data concurrently
<?php
$conn = oci_connect('asdsdfsf');
$req_number = array();
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$stid = oci_parse($conn, " SELECT WR.REQST_NO
FROM DEE_PRD.WORK_REQST WR
WHERE WR.WORK_REQST_STATUS_CD = 'PLAN' AND WR.DEPT_CD ='ISNG'
");
oci_execute($stid);
while (($row = oci_fetch_array($stid, OCI_BOTH+OCI_RETURN_NULLS)) != false) {
// Use the uppercase column names for the associative array indices
$req_number[]= $row['REQST_NO'];
}
oci_free_statement($stid);
oci_close($conn);
//MYSQL
//Connection Variables
//connect to MYSQL
$con = mysqli_connect($servername,$username,$password,$dbname);
if (!$con)
{
die('Could not connect: ' . mysqli_error());
}
// lets check if this site already exists in DB
$result = mysqli_query($con,"
SELECT EXISTS(SELECT 1 FROM wr_info WHERE REQST_NO = '$req_number') AS mycheck;
");
while($row = mysqli_fetch_array($result))
{
if ($row['mycheck'] == "0") // IF site doesnt exists lets add it to the MYSQL DB
{
$sql = "INSERT INTO wr_info (REQST_NO)VALUES ('$req_number[0]')";
if (mysqli_query($con, $sql)) {
$created = $req_number." Site Created Successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($con);
}
}else{ // if site is there lets get some variables if they are present...
$result = mysqli_query($con,"
SELECT *
FROM wr_info
WHERE REQST_NO = '$req_number[0]'
");
while($row = mysqli_fetch_array($result))
{
$do some stuff
}
}
}
mysqli_close($con);
?>
You create an array:
$req_number = array();
And loop over records to assign values to the array:
while (($row = oci_fetch_array($stid, OCI_BOTH+OCI_RETURN_NULLS)) != false) {
$req_number[]= $row['REQST_NO'];
}
But then never loop over that array. Instead, you're only referencing the first record in the array:
$sql = "INSERT INTO wr_info (REQST_NO)VALUES ('$req_number[0]')";
// etc.
(Note: There are a couple of places where you directly reference the array itself ($req_number) instead of the element in the array ($req_number[0]), which is likely an error. You'll want to correct those. Also: You should be using query parameters and prepared statements. Getting used to building SQL code from concatenating values like that is a SQL injection vulnerability waiting to happen.)
Instead of just referencing the first value in the array, loop over the array. Something like this:
for($i = 0; $i < count($req_number); $i++) {
// The code which uses $req_number, but
// referencing each value: $req_number[$i]
}

I can't connect to db or pull data

I am using this same code `
php $postId = 41;
<!-- hidden items and variables. Elements that will not be revealed !-->
<span id="gameLength"><?php
// MySQL connect configuration
$dbname="my_db";
$host="localhost";
$user="guessthe";
$dbh=mysql_connect ($host,$user,"correctPassword?") or die ('I cannot connect to the database because: ' . mysql_error(). '');
mysql_select_db ("$dbname") or die('I cannot select the database because: ' . mysql_error());
$sql="SELECT * FROM games WHERE postId = $postId";
$result=mysql_query($sql);
$rows=mysql_fetch_array($result);
$gameId = $rows['id'];
$game100s = $rows['game100s'];
$gamesPlayedAllTime = $rows['gamesPlayed'];
$gamesPointsAllTime = $rows['gameScore'];
$gameLength = $rows['gameLength']; // get number of questions
$gameScore = $rows['gameScore'];
$gameType = $rows['gameType'];
$gametitle = $rows['gameSubTitle'];
echo $gameLength;
There is a value in the gameLength row! I can't get this code to pull any of the rows! Any idea what i'm doing wrong?
You're using MySQL, which is depcirated - and will be phased out. You should use MySQLi or PDO instead. Also, your $postId is defined outside a PHP-tag? Might just be a copy/paste mistake? Anyway, you can try the code below, which is in MySQLi:
<?php
$postId = 41;
?>
<!-- hidden items and variables. Elements that will not be revealed !-->
<span id="gameLength"><?php
// MySQL connect configuration
$dbname = "my_db";
$host = "localhost";
$user = "guessthe";
// Connecting to the database
$mysqli = new mysqli($host, $user, "correctPassword?", $dbname);
if ($mysqli->connect_errno) {
// If we are here, the connection failed
echo "Failed to connect to MySQL: (".$mysqli->connect_errno.") ".$mysqli->connect_error;
}
$sql ="SELECT * FROM games WHERE postId = $postId";
if ($result = $mysqli->query($sql)) {
// If the query was sucsessfull, we can get the rows
while ($row = $result->fetch_assoc()) {
$gameId = $row['id'];
$game100s = $row['game100s'];
$gamesPlayedAllTime = $row['gamesPlayed'];
$gamesPointsAllTime = $row['gameScore'];
$gameLength = $row['gameLength']; // get number of questions
$gameScore = $row['gameScore'];
$gameType = $row['gameType'];
$gametitle = $row['gameSubTitle'];
}
} else {
// If the query failed, do something here
}
echo $gameLength;
?>
I see some people commenting that you need to put the $postId variable inside quotes in the query, but when using double-quotes (") variables will be posted, so it's not really needed. Also note that things are case-sensitive, so if your results doesn't show, check for spelling-mistakes.
There are many errors in your code
Try this...
<?php
$postId = 41;
?>
<!-- hidden items and variables. Elements that will not be revealed !-->
<span id="gameLength">
<?php
// MySQL connect configuration
$host = "localhost";
$dbname = "my_db";
$user = "username";
$password = "password";
$dbh = mysql_connect ($host,$user,$password) or die ('I cannot connect to the database because: ' . mysql_error() . '');
mysql_select_db($dbname, $dbh) or die('I cannot select the database because: ' . mysql_error());
$sql = "SELECT * FROM games WHERE postId='$postId'";
$result = mysql_query($sql);
while($rows = mysql_fetch_array($result)){
$gameId = $rows['id'];
$game100s = $rows['game100s'];
$gamesPlayedAllTime = $rows['gamesPlayed'];
$gamesPointsAllTime = $rows['gameScore'];
$gameLength = $rows['gameLength']; // get number of questions
$gameScore = $rows['gameScore'];
$gameType = $rows['gameType'];
$gametitle = $rows['gameSubTitle'];
echo $gameLength;
}
?>
You need to fix this is your code and that should fix the error.
$sql="SELECT * FROM games WHERE postId ='".$postId."' ";
If you want all the records you can use a while loop. Here is some pseudo code.
while($row = mysql_fect_assoc($query)){
echo $row["THE THING YOU WANT"];
...
}

Get mysql result and using it in a subsequent insert command within the same script

So I am having a difficult time getting a variable using a mysql search command and then using it in the same script in an insert command. What am I doing wrong?
<?php
$usto= $_GET["usto"];
$itena= "item";
$sql = 'SELECT sname FROM login';
$hostname_Database = "blocked";
$database_Database = "blocked";
$username_Database = "blocked";
$password_Database = "blocked";
$mysqli = new mysqli($hostname_Database, $username_Database, $password_Database, $database_Database);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$result = $mysqli->query($sql);
if ($result) {
$row = $result->fetch_assoc();
$sql = "INSERT INTO pon(mis, take)
VALUES({$row['snake']}, '" . $usto . "')"; //Here, I am trying to use the result from the previous select statement for the variable
$result = $mysqli->query($sql);
if ($result) {
...etc.
}
}
?>
You are vulnerable to SQL injection attacks. Read up about those and fix your code FIRST.
After that, realize that ->query() calls return a result HANDLE, not the actual field(s) you'd requested in your query. You have to FETCH a row of data first:
$result = $mysqli->query($sql);
$row = $result->fetch_assoc();
$sql = ".... VALUES ({$row['name_of_field']} ...)";
Note that this is STILL vulnerable to SQL injection.. it's purely to illustrate the query/fetch/insert process.

JSONKit - parse JSON String to PHP to MYSQL database

In my database I have the following schema:
Answers:
answerId(PK) auto_inc
answer
questionId
I am passing the following JSON String to my php file:
[{"answer":"bnk","questionId":"1"},{"answer":"1","questionId":"2"},{"answer":"b n","questionId":"3"},{"answer":"3","questionId":"4"},{"answer":"rgb","questionId":"5"},{"answer":"No","questionId":"6"},{"answer":"0","questionId":"7"},{"answer":"0","questionId":"8"},{"answer":"0","questionId":"9"},{"answer":"0","questionId":"10"},{"answer":"0","questionId":"11"},{"answer":"0","questionId":"12"},{"answer":"0","questionId":"13"},{"answer":"0","questionId":"14"},{"answer":"3","questionId":"18"},{"answer":"nko","questionId":"19"},{"answer":"hhkl","questionId":"15"},{"answer":"2","questionId":"16"},{"answer":"vnlf hugg","questionId":"17"}]
This is captured via a post request in $_POST['answers']:
if(isset($_POST['submitanswer'])){
$dbh = connect();
$user = $_POST['user'];
$entry = $_POST['entryId'];
$answers = $_POST['answers'];
$answers = json_decode($answers); //decode JSON answers
//for loop to iterate through answers ans insert new row into database
}
How do I iterate through the answers array and insert a new row into my answers table?
Something like:
foreach($answers as $row){
$query = "INSERT INTO Answers (answer, questionId) VALUES ($row['answer'], $row['questionId'])";
mysql_query($query);
}
If this code didn't work for you, try this:
foreach($answers as $row){
$query = "INSERT INTO Answers (answer, questionId) VALUES (".$row['answer'].", ".$row['questionId'].")";
mysql_query($query);
}
Otherwise, I can't spot anything wrong here.
I gues you know this but make sure your connection string is good.
Actually this is what I do. Probably a bit much info for you, also I do all that concatenation in the SQL so I can easily comment out fields for testing.
$Link = mysql_connect( $Host , $User , $Password , $DBName);
if (!$Link) {
die('Could not connect: ' . mysql_error());
}
$sql = "insert into table "
."("
."hashfirstName".","
."hashfamilyName".","
."hashemailAddress"
.")"
."values ("
."'$firstNameHashed'".","
."'$familyNameHashed'".","
."'$emailAddressHashed'"
.")";
mysql_select_db($DBName , $Link) or die("Database error in insertdata<br>"."Error #" . mysql_errno() . ": " . mysql_error());
if(!mysql_query($sql , $Link))
{
$errors['sql'] = $sql;
$errors['DBName'] = $DBName;
$errors['Link'] = $Link;
$errors['status'] = "false"; //There was a problem saving the data;
echo json_encode($errors);
}
else
{
$errors['status'] = "true";
echo json_encode($errors);
}; // if(!mysql_query( $DBName , $sql , $Link))

Categories