I have database that hold my data in mysql.
I have already data in my table (call words) and I want to insert new data to this table but before I want to check if this data not already exist.
I have function that insert the data to table but I need sql query that will check if the data not exist?
the colum in my table 'words' are :word , num , hit , instoplist.
I write the code in PHP
Thanks,
this is my code:(insert to table function)
function insert($myWords)
{
global $conn;
$temp1 = $value['document'];
$temp2 = $value['word'];
$sql = "INSERT INTO words (word,num,hit,instoplist) VALUES";
foreach ($myWords as $key => $value) {
$word = $value['word'];
$number = $value['document'];
$hit = $value['hit'];
$stop = $value['stopList'];
$sql .= "('$word', '$number', '$hit','$stop'),";
}
$sql = rtrim($sql,','); //to remove last comma
if($conn->query($sql)!== TRUE)
{
echo "error". $conn->error;
}
}
Before inserting the data make a select query on a column which is unique as per your requirement like:
$chkExist = "select id from table where col_name = '".$value."'";
$res = $conn->query($chkExist);
// Now check if there is some record in $res than stop the entry otherwise insert it
function insert($myWords)
{
global $conn;
$temp1 = $value['document'];
$temp2 = $value['word'];
$sql = "INSERT INTO words (word,num,hit,instoplist) VALUES";
foreach ($myWords as $key => $value) {
$sql2 "SELECT * FROM words WHERE word = '".$value['word']."' OR num = '".$value['document']."'"; //other data if you want
$resultat=mysql_query($query);
if($resultat==""){
$word = $value['word'];
$number = $value['document'];
$hit = $value['hit'];
$stop = $value['stopList'];
$sql .= "('$word', '$number', '$hit','$stop'),";
}
}
$sql = rtrim($sql,','); //to remove last comma
if($conn->query($sql)!== TRUE)
{
echo "error". $conn->error;
}
}
$sel="select * from words where word = '$word' AND document = '$document' AND hit = '$hit' AND stopList ='$stopList'";
$qry=mysqli_query($sel);
$num=mysqli_num_rows($qry);
if($num==0){
$sql = "INSERT INTO words (word,num,hit,instoplist) VALUES";
foreach ($myWords as $key => $value) {
$word = $value['word'];
$number = $value['document'];
$hit = $value['hit'];
$stop = $value['stopList'];
$sql .= "('$word', '$number', '$hit','$stop'),";
}
$sql = rtrim($sql,',');
}else{
echo "Already Exist";
}
Related
I have searched around the web but no luck.
Am new to SQLSRV and i was migrating from PHP MySQL to PHP SQL and am having trouble inserting data from a form as some fields are optional which makes the column number vary. I need help on how i can insert when the column number varies.
thank you
here is how my insert code looks like
// sql fields and values for main table
$in_fields = array();
$in_values = array();
// prepare insertion
foreach ($_POST as $key => $value) {
if (!empty($value)) {
$value = sql_escape($value);
$in_fields[] = "[{$key}]";
$in_values[] = "'{$value}'";
}
}
// prepare sql stmt
if (!empty($in_fields)) {
$sql = "INSERT into [table_name](";
$sql .= implode(", ", $in_fields);
$sql .= ") VALUES ()";
if (executeSql($sql, $in_values)) {
$success = "Successfully Added New Record";
}
}
The executeSql function looks like this
function executeSql($sql, $params) {
global $conndb;
$rs = sqlsrv_query($conndb, $sql, $params)or die("Db query error.<br />".print_r(sqlsrv_errors(), true));
return !$rs ? false : true;
}
You need to add placeholder values (?) in the VALUES part of your query, you will need a placeholder for every value you pass through - i.e. for every value in $in_values.
To do this you could have another array, that will just have a number of ? as values, and then, like you have done for the fields, implode the array into the VALUES. Like so:
$in_fields = array();
$in_values = array();
$placeholders = array(); // new array
foreach ($_POST as $key => $value) {
if (!empty($value)) {
$value = sql_escape($value);
$in_fields[] = "[{$key}]";
$in_values[] = "'{$value}'";
// add a placeholder to the array
$placeholders[] = "?";
}
}
if (!empty($in_fields)) {
$sql = "INSERT into [table_name](";
$sql .= implode(", ", $in_fields);
$sql .= ") VALUES (" . implode(",", $placeholders) . ")";
if (executeSql($sql, $in_values)) {
$success = "Successfully Added New Record";
}
}
I am testing multiple array insertion into my table, I have try all what I could but I am not getting.Here is my code:
<?php
ini_set('display_errors',1);
//ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$mysqli = new mysqli(HOST,USER,PASS,DB);
$message = array();
$id =1;
$SocialHandle = "Facebook,Twitter,LinkIn";
$SociaUrl ="Url1,Url2,Url3";
$strSocialHandle = explode(',', $SocialHandle);
$strSociaUrl = explode(',', $SociaUrl);
print_r($strSocialHandle);
print_r($strSociaUrl);
$sql = "INSERT INTO `social_table`(`id`, `social_handle`, `handle_url`) VALUES";
foreach($strSocialHandle as $SocialNameValue){
$sql .= "({$id}, '{$SocialNameValue}','{$strSociaUrl}'),";
}
$sql = rtrim($sql, ',');
$result = $mysqli->query($sql);
if (!$result){
$message = array('Message' => 'insert fail or record exist');
echo json_encode($message);
}else{
$message = array('Message' => 'new record inserted');
echo json_encode($message);
}
?>
Here is my goal achievement:
ID social handle
handle url 1 Facebook
url1 1
Twitter url2 1
LinkIn
url3
Please help.
You can use for loop for it as
$id =1;
$SocialHandle = "Facebook,Twitter,LinkIn";
$SocialHandle = explode(",", $SocialHandle);
$SociaUrl = "Url1,Url2,Url3";
$SociaUrl = explode(",", $SociaUrl);
$sql = "INSERT INTO `social_table`(`id`, `social_handle`, `handle_url`) VALUES";
for ($i = 0; $i < count($SocialHandle); $i++) {
$sql .= "({$id}, '$SocialHandle[$i]','$SociaUrl[$i]'),";
}
$sql = rtrim($sql, ',');
echo $sql;
$result = $mysqli->query($sql);
OUTPUT
INSERT INTO social_table(id, social_handle, handle_url)
VALUES(1, 'Facebook','Url1'),(1, 'Twitter','Url2'),(1,
'LinkIn','Url3')
DEMO
UPDATED
Better use prepare and bind statement to prevent form sql injection as
for ($i = 0; $i < count($SocialHandle); $i++) {
$sql = "INSERT INTO `social_table`(`id`, `social_handle`, `handle_url`) VALUES (?,?,?)";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param('iss', $id, $SocialHandle[$i], $SociaUrl[$i]);
$stmt->execute();
}
You're only looping over $strSocialHandle - the $strSociaUrl array isn't affected by the loop, so will still be an array rather than an individual value. You can store the two lists in a single key-value array, and use one loop to iterate over both:
<?php
$id = 1;
$social = [
'Facebook' => 'Url1',
'Twitter' => 'Url2',
'LinkIn' => 'Url3',
];
$sql = "INSERT INTO `social_table`(`id`, `social_handle`, `handle_url`) VALUES";
foreach($social as $handle => $url) {
$sql .= "({$id}, '{$handle}','{$url}'),";
}
echo rtrim($sql, ',');
This is my table in my database. It should only contain one row.
I have this code, that checks if there is no data , if there is not.. The data is inserted, else it's updated. The problem is, that if i update only Brevet, the value of Baccalaureabt will disappear from my database. Any help?
Code:
if(isset($_POST['submit']))
{ $brevet = $_POST['Brevet'];
$baccalaureatbt = $_POST['Baccalaureatbt'];
$sql1="SELECT Brevet,Baccalaureatbt FROM university";
if ($result=mysqli_query($con,$sql1))
{
$rowcount=mysqli_num_rows($result);
}
if($rowcount==0)
{
$sql="INSERT INTO university(Brevet,Baccalaureatbt) VALUES('$brevet','$baccalaureatbt')";
$result = mysql_query($sql);
}
else
{
$sql2 = "UPDATE university SET Brevet = '$brevet' , Baccalaureatbt = '$baccalaureatbt'";
$result2 = mysql_query($sql2);
}
The issue is that you are setting both values, if however either $baccalaureatbt or $brevet is empty, it will be updated with a empty value, i.e the original value will be deleted.
There are multiple ways to avoid this, but one way to do it is like so:
$sql2 = "UPDATE university SET ";
if(!empty($brevet)){
$sql2 .= "Brevet = '$brevet'";
$first = 1;
}
if(!empty($baccalaureatbt)){
$sql2 .= isset($first) ? ", Baccalaureatbt = '$baccalaureatbt'" : "Baccalaureatbt = '$baccalaureatbt' " ;
}
$result2 = mysql_query($sql2);
To update the values dynamically, use the following code. Just add the values you want in the values array.
if(isset($_POST['submit']))
{
$brevet = $_POST['Brevet'];
$baccalaureatbt = $_POST['Baccalaureatbt'];
$sql1="SELECT Brevet,Baccalaureatbt FROM university";
$result=mysqli_query($con,$sql1);
if ($result)
{
$rowcount=mysqli_num_rows($result);
}
if($rowcount==0)
{
$sql="INSERT INTO university(Brevet,Baccalaureatbt) VALUES('$brevet','$baccalaureatbt')";
$result = mysql_query($sql);
}
else
{
$values = array("brevet","baccalaureatbt");
$sql2 = "UPDATE university ";
$n = 0;
foreach($_POST as $key => $val) {
if(in_array($key, $values)) {
$sql2 += ($n !== 0 ? ", " : 0);
$sql2 += "SET".$key." = ".$val;
$n++;
}
if($n > 0) {
$result2 = mysql_query($sql2);
}
}
}
}
I've made a function to query the database. This function takes an array, the id of the user I want to update
and a query operation.
if the query operation is UPDATE
if you look at the code below, would this be a good coding practice or is this bad code?
public function query($column, $search_value, $query_operation = "SELECT"){
if(strtoupper($query_operation == "UPDATE")){
$query = "UPDATE users SET ";
if(is_array($column)){
$counter = 1;
foreach($column as $key => $value){
if($counter < count($column)){
$query .= $key . ' = ?, ';
}else{
$query .= $key . ' = ? ';
}
$counter++;
}
$query .= "WHERE id = ?";
$stmt = $this->database->prepare($query);
$counter = 1;
foreach($column as $key => &$value){
$stmt->bindParam($counter, $value);
$counter++;
}
$stmt->bindParam($counter, $search_value);
if($stmt->execute()){
$stmt = $this->database->prepare("SELECT* FROM
users WHERE id = ?");
$stmt->bindParam(1, $search_value, PDO::PARAM_INT);
$stmt->execute();
return $this->build_array($stmt);
}
}
}
}
would love to hear some feedback.
I would NOT mix SELECT and UPDATE in the same function.
The following update function uses arrays for column names and values $columnNames & $values using unnamed parameters.
function update($tableName,$columnNames,$values,$fieldName,$fieldValue){
$sql = "UPDATE `$tableName` SET ";
foreach($columnNames as $field){
$sql .= $field ." = ?,";
}
$sql = substr($sql, 0, -1);//remove trailing ,
$sql .= " WHERE `$fieldName` = ?";
return $sql;
}
As table and column names cannot be passed as parameters in PDO I have demonstrated whitelistng of table names.
$tables = array("client", "Table1", "Table2");// Array of allowed table names.
Also array_push()to add value for last parameter (WHERE) into $values array
Use
if (in_array($tableName, $tables)) {
$sql = update($tableName,$columnNames,$values,$fieldName,$fieldValue);
array_push($values,$fieldValue);
$STH = $DBH->prepare($sql);
$STH->execute($values);
}
You can use similar technique for SELECT
I am passing a number of values to a function and then want to create a SQL query to search for these values in a database.
The input for this is drop down boxes which means that the input could be ALL or * which I want to create as a wildcard.
The problem is that you cannot do:
$result = mysql_query("SELECT * FROM table WHERE something1='$something1' AND something2='*'") or die(mysql_error());
I have made a start but cannot figure out the logic loop to make it work. This is what I have so far:
public function search($something1, $something2, $something3, $something4, $something5) {
//create query
$query = "SELECT * FROM users";
if ($something1== null and $something2== null and $something3== null and $something4== null and $something5== null) {
//search all users
break
} else {
//append where
$query = $query . " WHERE ";
if ($something1!= null) {
$query = $query . "something1='$something1'"
}
if ($something2!= null) {
$query = $query . "something2='$something2'"
}
if ($something3!= null) {
$query = $query . "something3='$something3'"
}
if ($something4!= null) {
$query = $query . "something4='$something4'"
}
if ($something5!= null) {
$query = $query . "something5='$something5'"
}
$uuid = uniqid('', true);
$result = mysql_query($query) or die(mysql_error());
}
The problem with this is that it only works in sequence. If someone enters for example something3 first then it wont add the AND in the correct place.
Any help greatly appreciated.
I would do something like this
criteria = null
if ($something1!= null) {
if($criteria != null)
{
$criteria = $criteria . " AND something1='$something1'"
}
else
{
$criteria = $criteria . " something1='$something1'"
}
}
... other criteria
$query = $query . $criteria
try with array.
function search($somethings){
$query = "SELECT * FROM users";
$filters = '';
if(is_array($somethings)){
$i = 0;
foreach($somethings as $key => $value){
$filters .= ($i > 0) ? " AND $key = '$value' " : " $key = '$value'";
$i++;
}
}
$uuid = uniqid('', true);
$query .= $filters;
$result = mysql_query($query) or die(mysql_error());
}
// demo
$som = array(
"something1" => "value1",
"something2" => "value2"
);
search( $som );
Here's an example of dynamically building a WHERE clause. I'm also showing using PDO and query parameters. You should stop using the deprecated mysql API and start using PDO.
public function search($something1, $something2, $something3, $something4, $something5)
{
$terms = array();
$values = array();
if (isset($something1)) {
$terms[] = "something1 = ?";
$values[] = $something1;
}
if (isset($something2)) {
$terms[] = "something2 = ?";
$values[] = $something2;
}
if (isset($something3)) {
$terms[] = "something3 = ?";
$values[] = $something3;
}
if (isset($something4)) {
$terms[] = "something4 = ?";
$values[] = $something4;
}
if (isset($something5)) {
$terms[] = "something5 = ?";
$values[] = $something5;
}
$query = "SELECT * FROM users ";
if ($terms) {
$query .= " WHERE " . join(" AND ", $terms);
}
if (defined('DEBUG') && DEBUG==1) {
print $query . "\n";
print_r($values);
exit();
}
$stmt = $pdo->prepare($query);
if ($stmt === false) { die(print_r($pdo->errorInfo(), true)); }
$status = $stmt->execute($values);
if ($status === false) { die(print_r($stmt->errorInfo(), true)); }
}
I've tested the above and it works. If I pass any non-null value for any of the five function arguments, it creates a WHERE clause for only the terms that are non-null.
Test with:
define('DEBUG', 1);
search('one', 'two', null, null, 'five');
Output of this test is:
SELECT * FROM users WHERE something1 = ? AND something2 = ? AND something5 = ?
Array
(
[0] => one
[1] => two
[2] => five
)
If you need this to be more dynamic, pass an array to the function instead of individual arguments.