Inserting 2 different array values into database does not work - php

I'm trying to insert 2 values from arrays into a database. There's nothing wrong with the connection, the fields where $fullArr and $thumbArr get inserted are longtexts, and when I try to insert 1 array value it works fine ($fullArr or $thumbArr). As soon as both arrays get used in the query it stops working.
The values in the arrays are data-urls.
private function submitPhoto() {
global $database;
$projectid = $_POST['projectid'];
$fullArr = $_POST['fullArr'];
$thumbArr = $_POST['thumbArr'];
$count = 0;
foreach($thumbArr as $key) {
// Insert Thumb
$database->query("INSERT INTO `photo` (photoid, projectid, dataurlfull, dataurlthumb) VALUES('', '" . $projectid . "', '" . $fullArr[$count] . "', '" . $key . "')");
$count++;
}
}

Try changing the query:
$database->query("INSERT INTO `photos` (photoid, projectid, dataurlfull, dataurlthumb) VALUES('', '$projectid', '$fullArr[$count]', '$key')");

Is it possible you are not executing the query inside the foreach() loop, so the last one will 'overwrite' any that you had before? Also, the $count is not necessary as you can use the $key. Try something like-
foreach($thumbArr as $key=>$value) {
// Insert Thumb
$database->query("INSERT INTO `photo` (photoid, projectid, dataurlfull, dataurlthumb) VALUES('', '" . $projectid . "', '" . $fullArr[$key] . "', '" . $thumbArr[$key] . "')");
$database->execute();
}
Be aware that you are open to SQL injection as you are using $_POST data without sanitizing. If you are using mysqli_ or PDO, use paramatized statements
foreach($thumbArr as $key=>$value) {
// Insert Thumb
$database->query("INSERT INTO `photo` (photoid, projectid, dataurlfull, dataurlthumb) VALUES('', ?, ?, ?)");
$database->bindParam(1,$projectid);
$database->bindParam(2,$fullArr[$key]);
$database->bindParam(3,$thumbArr[$key]);
$database->execute();
}

Related

Can't insert now() in PHP

I am a beginner programmer trying to insert the the now() value into my field date. I have achieved this before and copied the structure word by word but still does not work. I have also viewed other stackoverflow questions and I think that my database structure is correct. Here is INSERT php code:
try{
$conn = new mysqli("xxxxx", "xxxxx", "xxxxxxxx", "xxxxxxx");
$userid = $_GET['userid'];
$title = $_GET['title'];
$comment = $_GET['comment'];
$query = "INSERT into enquiries (userid, title, comment, Resolved, date)
values ('" . addslashes($userid) . "','" . addslashes($title) . "','" . addslashes($comment) . "', N, now() )";
$result = $conn->query($query);
if (!$result){
$json_out = "[" . json_encode(array("result"=>0)) . "]";
}
else {
$json_out = "[" . json_encode(array("result"=>1)) . "]";
}
echo $json_out;
$conn->close();
}
This set of codes worked and inserted values before I added now()
Here is my table structure:
Here is my other table structure that inserted now() just fine:
Your "Resolved" value needs to be in quotes, because you have it defined as a varchar. This would be the case for any of the "char" family of datatypes.
$query = "INSERT into enquiries (userid, title, comment, Resolved, date)
values ('" . addslashes($userid) . "','" . addslashes($title) . "','" . addslashes($comment) . "', 'N', now() )";
Hope this helps!
Sometimes database has some restrictions.. So try using like this NOW() than now() or else use CURDATE().

MySQL inserts values into wrong columns

Problem
With a php website, I have a form to collect information which will then be inserted into the MySQL database, but there are these three columns that have the wrong values inserted into them. The rest are all in the correct order.
Values inserted as php variables via MySQL transaction.
Thank you for your time.
phpmyadmin display (first row is manually corrected)
Code:
<?php
function registerPatient($ptUsername, $ptPassword, $ptFirstName, $ptLastName, $ptSalutation, $ptEmail, $ptDOB, $ptPostCode, $ptHouseNo, $ptTelNo, $link)
{
$accType = "Patient";
$dtID = $_COOKIE["ID"];
$errors = "";
$SQL_patientInsert =
"START TRANSACTION;
INSERT INTO accDetails (`username`, `hashPassword`, `accType`)
VALUES ('" . $ptUsername . "',
'" . $ptPassword . "',
'" . $accType . "');
INSERT INTO ptProfile (`firstName`, `lastName`, `salutation`, `email`, `DOB`, `postCode`, `houseNo`, `telephoneNo`, `dtID`, `ptID`)
VALUES ('" . $ptFirstName . "',
'" . $ptLastName . "',
'" . $ptSalutation . "',
'" . $ptEmail . "',
'" . $ptDOB . "',
'" . $ptPostCode . "',
'" . $ptHouseNo . "',
'" . $ptTelNo . "',
'" . $dtID . "',
LAST_INSERT_ID());
COMMIT;";
if (mysqli_multi_query($link, $SQL_patientInsert)) {
$errors .= "";
} else {
$errors .= "MYSQL Error: ". mysqli_error($link);
}
return $errors;
}
?>
Var_Dump of $SQL_patientInsert
string(495) "START TRANSACTION; INSERT INTO accDetails (`username`, `hashPassword`, `accType`) VALUES ('bingbong', '$2y$10$WDvSHSxzIxaYB8dPGLRIWOFyIdPXxSw5JDXagOxeYuJUtnvFhI.lO', 'Patient'); INSERT INTO ptProfile (`firstName`, `lastName`, `salutation`, `email`, `DOB`, `postCode`, `houseNo`, `telephoneNo`, `dtID`, `ptID`) VALUES ('Dr', 'Bing', 'Bong', 'EMAIL REMOVED FOR SO', '1996-08-02', 'POSTCODE REMOVED FOR SO', '7', '83824', '1256', LAST_INSERT_ID()); COMMIT;"
Table Structure
Table Structure in PHPMyAdmin, no autoincrements, all values allowed to be null
Your are calling your function with wrong parameters order.
Change this line ($ptFirstName <-> $ptSalutation);
function registerPatient($ptUsername, $ptPassword, $ptFirstName, $ptLastName, $ptSalutation, $ptEmail, $ptDOB, $ptPostCode, $ptHouseNo, $ptTelNo, $link)
with
function registerPatient($ptUsername, $ptPassword, $ptSalutation, $ptFirstName, $ptLastName, $ptEmail, $ptDOB, $ptPostCode, $ptHouseNo, $ptTelNo, $link)
I think you just mixed up your variables somewhere. Have you checked the form? Try printing out all the variables right before you build the query and check if they correspond correctly.

MySQL Insert statement not executing

I am trying to run an mySQL insert statement like so:
function insertAppointment($connection, $id, $firstname, $lastname, $email, $phone, $date, $time){
$sql = "INSERT INTO `appointments` (firstname, lastname, email, phone, app_date, app_time) VALUES ('" . $id . "', '" . $firstname . "', '" . $lastname . "', '" . $email . "', " . $date . ", " . $time . ")";
$connection->query($sql);
}
$connection is my connection string, which is not the problem. I am able to use it for select statement like so:
function getTakenDates($connection){
$query = mysqli_query($connection, "SELECT app_date, app_time FROM `appointments`");
$results = array();
while($row = mysqli_fetch_assoc($query)){
$results[] = $row;
}
return $results;
}
You are vulnerable to SQL injection attacks, and are creating an incorrect query with your $date/$time values:
INSERT .... VALUES (..., 2014-11-10, 14:58:00)
since your date value is unquoted, you'll actually be trying to insert the result of that math operation (remember - is SUBTRACTION if it's not in a string), and 14:58:00 is a totally invalid number - mysql has no idea what those : chars are.
You want
$sql = "[..snip..] "', '" . $date . "', '" . $time . "')";
^-------------^--^-------------^----
instead. note the extra quotes. That'll produce
INSERT .... VALUES (..., '2014-11-10', '14:58:00')

mysql insert query in a php script is not working

I have a php script that take data from a table and then try to insert the obtained data in a second table copy of the first one:
function copy_data($id,$mysql_conn){
if($res=mysql_query("SELECT * from table1 WHERE id='".$id."'", $mysql_conn)){
if($row=mysql_fetch_array($res)){
$sql ="INSERT INTO table2 (id, Field1, Field2) values('" . $row['id'] . "', '" . $row['Field1'] . "', '" . $row['Field2'] . "')";
mysql_query($sql,$mysql_conn);
}
}
}
copy_data($id,$mysql_conn);// $id is id of the element I want to add
The insert query works fine but there is one case that makes an exception :one of the field contains a ' character, exp of a query that failed:
INSERT INTO table2 (id, Field1, Field2) values ('12','Company', 'Kurt's Reifen-Shop') the exception comes from the ' character how to insert php variables that do contain this character.
You have to escape the data before insert them into $sql:
function copy_data($id,$mysql_conn){
if($res=mssql_query("SELECT * from table1 WHERE id='".$id."'", $mysql_conn)){
if($row=mysql_fetch_array($res)){
$row['Field1'] = mysql_real_escape_string($row['Field1']);
$row['Field2'] = mysql_real_escape_string($row['Field2']);
$sql ="INSERT INTO table2 (id, Field1, Field2) values('" . $row['id'] . "', '" . $row['Field1'] . "', '" . $row['Field2'] . "')";
mysql_query($sql,$mysql_conn);
}
}
}
copy_data($id,$mysql_conn);// $id is id of the element I want to add
You can do it with a single statement:
$id = mysql_real_escape_string($id);
INSERT INTO table2 (id, Field1, Field2) SELECT id, Field1, Field2 FROM table1 WHERE id='".$id."'"
i dont understand how you managed to put that ' in to the first table but you should use
mysql_real_escape_string
like $field1 = mysql_real_escape_string($row['Field1']);
than put the $field1 as it will be safe now

PHP & MySQL question

I was wondering how can I check a value from an array to see if its in the database if it is don't added to the database again. How would I be able to do this using PHP & MySQL?
PHP code.
for ($x = 0; $x < count($cat_id); $x++){
$cat_query = "INSERT INTO posts_categories (category_id, post_id, date_created) VALUES ('" . mysqli_real_escape_string($mysqli, strip_tags($cat_id[$x])) . "', '" . mysqli_real_escape_string($mysqli, strip_tags($post_id)) . "', NOW())";
}
Revise PHP code.
if(isset($cat_id)){
for($x = 0; $x < count($cat_id); $x++){
$check_query = mysqli_query($mysqli,"SELECT category_id FROM posts_categories WHERE category_id = '" . $cat_id[$x] ."' AND post_id = '" . $post_id . "'");
if ($check_query == TRUE) {
unset($cat_id[$x]);
}
}
for($x = 0; $x < count($cat_id); $x++){
$cat_query = "INSERT INTO posts_categories (category_id, post_id, date_created) VALUES ('" . mysqli_real_escape_string($mysqli, strip_tags($cat_id[$x])) . "', '" . mysqli_real_escape_string($mysqli, strip_tags($post_id)) . "', NOW())";
}
}
You can use INSERT .. ON DUPLICATE UPDATE.
As you're using mysqli you should probabaly use prepared statements (from both a security and performance standpoint)
$stmt = $mysqli->prepare("INSERT IGNORE INTO posts_categories (category_id, post_id, date_created) VALUES (?, ?, ?)");
// Should use a prepared statement here.
foreach ($categories as $key => $cat) {
// Bind params
$stmt->bind_param('iis', $cat, $post_id, 'NOW()');
// Exectute the query
$stmt->execute();
}
// Close the connection!
$mysqli->close();
NOTE: I also used INSERT IGNORE, so the insert will silently fail if the key exists.
$sql = "SELECT * FROM your_table WHERE your_column='".$yourArray['value']."'";
if(!mysql_num_rows(mysql_query($sql))){
// no rows so add it to the database...
}

Categories