im having a problem inserting some variables into my database, here's my code.
preg_match('/Tel\. P(.)liza :(.*?)Localidad/s', $a->output(), $tel);
echo "Tel. Poliza: " . $tel[2] . "<br><br>";
$tel = $tel[2];
preg_match('/Tel\. Expt :(.*?)D\.P\./s', $a->output(), $tel1);
$tel1 = $tel1[1];
preg_match_all('/\\b[0-9]{9}\\b/s', $tel1, $tel2);
$tel2 = implode(" / ", $tel2[0]);
echo "Tel. Expt: " . $tel2 . "<br><br>";
$conn = new PDO('mysql:host=localhost;port=3306;dbname=something', 'something', 'something');
$sql = "INSERT INTO clients (tel poliza, tel expt) VALUES ( ? , ? )";
$q = $conn->prepare($sql);
$q->execute(array ($tel, $tel2));
i can echo this variables(they are just numbers from a pdf file) but when i run the sql query nothing is inserted into the db. i have tried this with other variables in my code and they get inserted but when i had this 2 to the query nothing is inserted at all.
Your table column names have spaces in then therefore you have to put them in back quotes
$sql = "INSERT INTO clients (`tel poliza`, `tel expt`) VALUES ( ? , ? )";
Related
i am using INSERT INTO SELECT Statement Syntax to insert values from another table into my main table
in my php project
$student_id=1; // dummy id set in a variable
include 'conndb.php';
$sql = "INSERT INTO `student_resulttbl` ( subject_name,)\n"
. "SELECT subject,\n"
. "FROM `subjecttbl`\n"
. "WHERE subject_class ='$class' AND subject_session = '2020/2021'";
It worked well but my issue is how to insert variable $student_id along with this on student_resulttbl. pls note $student_id is not coming from subjecttbl. Its set already. Thank you
If you want to INSERT $student_id to student_resulttbl table you should do query like this:
INSERT INTO `student_resulttbl` ( subject_name, student_id ) VALUES (
( SELECT subject FROM `subjecttbl`
WHERE subject_class ='$class'
AND subject_session = '2020/2021'
),
$student_id);
The summary code:
$student_id=1; // dummy id set in a variable
include 'conndb.php';
$sql = "INSERT INTO `student_resulttbl` ( subject_name, student_id ) VALUES ("
. "(SELECT subject FROM `subjecttbl` "
. "WHERE subject_class ='$class' "
. "AND subject_session = '2020/2021'"
. "), $student_id)";
You can INSERT multiple columns with INSERT INTO command. More information there:
w3schools.com/sql/sql_insert_into_select.asp
or
https://www.w3schools.com/sql/sql_insert.asp
or
https://www.dofactory.com/sql/insert
do you mean something like this?
$student_id=1; // dummy id set in a variable
include 'conndb.php';
$sql = "INSERT INTO `student_resulttbl` ( student_id, subject_name,)\n"
. "SELECT " . mysqli_real_escape_string($connection, $Student_id) . ", subject\n"
. "FROM `subjecttbl`\n"
. "WHERE subject_class ='$class' AND subject_session = '2020/2021'";
but have a look at prepared statements.
Is there a reason why you use newlines in SQL-Statements?
I am trying to updata a database table using pq_query in PHP. I have the following code:
$q = "UPDATE tableName SET ('data1 = " . $data1 . "', data2='" . $data2 . "') WHERE user=".$user;
$success = pg_query($q);
if (!$success) {
$errormessage = pg_last_error();
echo "Error " . $errormessage;
}
I am getting the following error message:
ERROR: syntax error at or near "'data1 = '"
LINE 1: UPDATE tableName SET ('data1 = 10', data2= 20'') WHERE user=
Replace your query with this query
$q = "UPDATE tableName SET data1 = '$data1', data2='$data2' WHERE user='$user'";
Explaination: You should pass variable in single quotes('') if your query in double quotes.
You are using a lot of quotes which it is not understood by PostgreSQL, try simply this :
$q = "UPDATE tableName SET data1 = " . $data1 . ", data2=" . $data2 . " WHERE user=".$user;
Remove those single quotes !
I am trying to insert data from an Excel file into an Access 2007 database using PDO prepared statements. What the code is trying to do is to check if the value in the Excel sheet exists in the database and if not to add it but it doesn't do anything
Here is the code:
$conn = connect_to_impact();
//******************************************
//select statement
$select = 'SELECT < ? FROM < ?';
$select_query = $conn->prepare($select);
for ($h = 2; $h<count($clmn[0]); $h++){
$value = $clmn[0][$h];
// query execution
$select_query->execute(array($clmn[0][1], $clmn[0][1]));
$impact_no_result = $select_query->fetchAll();
//query result in multidimensional array
$impact_no_arr = impact_no_select($impact_no_result);
// create an indexed array of results
$impact_no_r = impact_no_indexed($impact_no_arr, $clmn[0][1]);
if(is_null($impact_no_r)){
$insert_impact_no = 'INSERT INTO < ? (< ?) VALUES (< ?)';
$simple_arr = [$clmn[0][1], $clmn[0][1], $value];
$insert_query = $conn->prepare($insert_impact_no);
$insert_query->execute($simple_arr);
}
// then if the value in the column is not in the indexed array insert it
elseif(!in_array($value, $impact_no_r)){
$insert_impact_no = 'INSERT INTO < ? (< ?) VALUES (< ?)';
$simple_arr = [$clmn[0][1], $clmn[0][1], $value];
$insert_query = $conn->prepare($insert_impact_no);
$insert_query->execute($simple_arr);
}
}
Indeed replacements cannot be used for table name and column names in PDO prepared statements. Here is the code that fixed the issueČ
$conn = connect_to_impact();
//******************************************
//select statement
$select = "SELECT ". $clmn[0][1] . " FROM " . $clmn[0][1];
//repeat for each row the the excel sheet starting from row 2
for ($h = 2; $h<count($clmn[0]); $h++){
//take each value from each row from column A
$value = $clmn[0][$h];
// query execution
$impact_no_result = $conn->query($select);
if($impact_no_result){
$impact_no_result_ass = $impact_no_result->fetchAll();
}
//if there is no result in the select query
if($impact_no_result == false){
$insert_impact_no = "INSERT INTO ". $clmn[0][1] . "(" . $clmn[0][1] . ") " . "VALUES ('" . $value . "');";
$execute = $conn->query($insert_impact_no);
}
//if there is a result in the select query
else {
//put query result in array
$impact_no_arr = impact_no_select($impact_no_result_ass);
//if value is not in array insert it
if(!in_array($value, $impact_no_arr)){
$insert_impact_no = "INSERT INTO ". $clmn[0][1] . "(" . $clmn[0][1] . ") " . "VALUES ('" . $value . "');";
$execute = $conn->query($insert_impact_no);
}
}
}
I am looking to post data into two database tables from a single form.
My databases are arranged as below:
Database 1 - 'watchlists':
watchlist_id
user_id
name
description
category
Database 2 - 'watchlist_films':
watchlist_id
film_id
My current MySQL query looks like this: $query = "INSERT INTO watchlist_films (watchlist_id, film_id) VALUES ('$watchlist_name['watchlist_id']', '$rt_id') WHERE watchlists ('watchlist_id') = " . $watchlist_name['watchlist_id'];, but I'm not sure if there's got to be some form of INNER JOIN somewhere?
Not sure what other information/code to provide, so I apologise if there's too little detail here, but, if there's anything else which is needed, just drop me a comment and I'll put up anything else which is required. I'm a relative PHP newbie, so apologies if this seems like a really simple question!
Update based on comments:
I have now got half of my query working, and have updated the logic to reflect it. The new query is basically doing the following:
INSERT new Watchlist to 'watchlists' table
SELECT watchlist_id of new Watchlist from 'watchlists' table WHERE watchlist_name = $watchlist_name (name of new Watchlist just created) and user_id = $user_id
INSERT watchlist_id (selected from previous query) AND film_id into 'watchlist_films' table
based on your comments, my queries now look like so:
if ($submit == 'Submit') {
require_once("db_connect.php");
$watchlist_name = clean_string($_POST['watchlist-name']);
$watchlist_description = clean_string($_POST['watchlist-description']);
$watchlist_category = $_POST['watchlist-category'];
$addWatchlist_bad_message = '';
$addWatchlist_good_message = '';
if ($db_server) {
if (!empty($watchlist_name)) {
$watchlist_name = clean_string($watchlist_name);
$watchlist_description = clean_string($watchlist_description);
mysql_select_db($db_database);
// Insert new Watchlist into Watchlist index
$insert_new_watchlist = "INSERT INTO watchlists (user_id, name, description, category) VALUES ('$user_id', '$watchlist_name', '$watchlist_description', '$watchlist_category')";
mysql_query($insert_new_watchlist) or die("Insert failed. " . mysql_error() . "<br />" . $insert_new_watchlist);
// Select new Watchlist ID
$select_new_watchlist = "SELECT watchlist_id FROM watchlists WHERE name = " . $watchlist_name;
$new_watchlist_id = mysql_query($select_new_watchlist) or die("Insert failed. " . mysql_error() . "<br />" . $select_new_watchlist);
// Add film to new Watchlist
$add_new_film = "INSERT INTO watchlist_films (watchlist_id, film_id) VALUES ('$new_watchlist_id', '$rt_id')";
mysql_query($add_new_film) or die("Insert failed. " . mysql_error() . "<br />" . $add_new_film);
$addWatchlist_good_message = '<div class="alert alert-success">Watchlist created successfully!</div>';?>
<script>
$('a.add-watchlist').trigger('click');
</script><?php
}
} else {
$addWatchlist_bad_message = '<div class="alert alert-error">Error: could not connect to the database.</div.';?>
<script>
$('a.add-watchlist').trigger('click');
</script><?php
}
require_once("db_close.php");
}
My query, however, seems to be failing at the SELECT statement, in between adding the new Watchlist to the Watchlist index and adding the film to the newly created Watchlist.
try this
$query1 = "INSERT INTO watchlist_films (watchlist_id, film_id)
VALUES ('" . $watchlist_name['watchlist_id'] . "', '$rt_id')";
$query2= "INSERT INTO watchlists ('watchlist_id')
VALUES (" . $watchlist_name['watchlist_id'] . ")";
$result = mysqli_multi_query($query1, $query2);
You will need to write an INSERT for each table.
$mysqli->query("INSERT INTO watchlist_films (watchlist_id, film_id)
VALUES ('" . $watchlist_name['watchlist_id'] . "', '$rt_id')");
$mysqli->query("INSERT INTO watchlists ('watchlist_id')
VALUES (" . $watchlist_name['watchlist_id'] . ")");
My part_no column has the following format: 000-00000-00 for all records.
I need to extract the five middle characters from part_no and place it in the core column when I create the record.
I can't get my script to work.
I'm not getting any errors. Just not working.
$order = "INSERT INTO cartons_added (add_time, type, part_no, add_type, add_qty, add_ref, add_by, add_notes)
VALUES
('$date',
'$_POST[type]',
'$_POST[part_no]',
'$_POST[add_type]',
'$_POST[add_qty]',
'$_POST[add_ref]',
'$_POST[add_by]',
'$_POST[add_notes]')";
$result = mysql_query($order);
$query2 = "select part_no from cartons_current";
$sel = mysql_query($query2);
$res = mysql_result($sel);
while($row = mysql_fetch_row($res)) {
$core_digits = split('-',$row[0]);
$core =$core_digits[1];
$query3 = "insert into cartons_current(core) values($core)";
$sel2 = mysql_query($query3);
}
You can update your cartons_current table based on your cartons_added table with something like:
INSERT INTO cartons_current(core)
SELECT SUBSTR(part_no, 5, 5) FROM cartons_added
You will probably want to limit that with a WHERE clause or maybe deal with what happens when this value is already in cartons_current (use either INSERT IGNORE or ON DUPLICATE KEY UPDATE)
You are right, the script has no error.
I think the problem is on your SQL that made you can't insert a new row, specifically on the table structure. Maybe you defined a PRIMARY KEY without AUTO_INCREMENT, defined a INDEX or UNIQUE key that is not the core key or there have some other key that did not have default value. Remember that you can't insert a row without defining all required field.
You script is selecting all part_no and for every part_no you are inserting a new row in the same table, so maybe there is the problem.
I think what you want is update every result to add they core value, you can do that with UPDATE as this code:
function getValue($value) {
return "'" . trim(mysql_real_escape_string($value)) . "'";
}
mysql_query('INSERT INTO `cartons_added` (`add_time`, `type`, `part_no`, `add_type`, `add_qty`, `add_ref`, `add_by`, `add_notes`)
VALUES (' .
getValue($date) . ', ' .
getValue($_POST[type]) . ', ' .
getValue($_POST[part_no]) . ', ' .
getValue($_POST[add_type]) . ', ' .
getValue($_POST[add_qty]) . ', ' .
getValue($_POST[add_ref]) . ', ' .
getValue($_POST[add_by]) . ', ' .
getValue($_POST[add_notes]) .
')');
$partNoQuery = mysql_query('SELECT `part_no` FROM `cartons_current`');
while($partNoResult = mysql_fetch_assoc($partNoQuery)) {
list($prefix, $core, $suffix) = explode('-', $partNoResult['part_no']);
mysql_query('UPDATE cartons_current SET `core` = \'' . $core . '\' WHERE `part_no` = \'' . $partNoResult['part_no'] . '\'');
}
I added getValue function to escape posted data to prevent SQL injection.
Try removing this
$res = mysql_result($sel);
And change your while to reference the main query resource
while($row = mysql_fetch_row($sel)) {
I don't understand your logic with your tables though. You're inserting data into the cartons_added table but then you're selecting from cartons_current?
Also, split is deprecated as of PHP 5.3.0
You said five middle "characters", so I'd add quotes around your variable like so:
$query3 = "insert into cartons_current(core) values('$core')";
(Also, there's only about a gazillion answers on SO about SQL injection, and using pdo)
INSERT INTO cartons_current(core)
SELECT
substr(part_no,position('-' IN part_no)+1,position('-' IN substr(part_no,position('-' IN part_no)+1))-1)
FROM cartons_added;