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...
}
Related
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().
Im having some trouble getting my SQL query to 'insert into' my database, is it allowed to use variables as table name, field name, and values?
Here my code:
$nameOfDBFromA = "vagtplanA" . $_GET["from"];
$flytnedToQ1 = $con->prepare("SELECT * FROM $nameOfDBToA WHERE ansatId='$_GET[ansatId]' ORDER BY id DESC");
$flytnedToQ1->execute();
$flytnedTo1 = $flytnedToQ1->fetch();
$nameOfFieldToA1 = "a" . $_GET["to"] . "1";
$nameOfFieldToA2 = "a" . $_GET["to"] . "2";
$nameOfFieldToA3 = "a" . $_GET["to"] . "3";
$nameOfFieldToA4 = "a" . $_GET["to"] . "4";
$nameOfFieldToA5 = "a" . $_GET["to"] . "5";
$nameOfFieldToA6 = "a" . $_GET["to"] . "6";
$nameOfFieldToA7 = "a" . $_GET["to"] . "7";
$redigeringsTidspunkt = date("j M Y");
$flytnedTA = $con->prepare(
"INSERT INTO $nameOfDBFromA
(ansatId, edit, $nameOfFieldToA1, $nameOfFieldToA2,
$nameOfFieldToA3, $nameOfFieldToA4, $nameOfFieldToA5,
$nameOfFieldToA6, $nameOfFieldToA7)
VALUES($_GET[ansatId], $redigeringsTidspunkt,
$flytnedTo1[$nameOfFieldToA1], $flytnedTo1[$nameOfFieldToA2],
$flytnedTo1[$nameOfFieldToA3], $flytnedTo1[$nameOfFieldToA4],
$flytnedTo1[$nameOfFieldToA5], $flytnedTo1[$nameOfFieldToA6],
$flytnedTo1[$nameOfFieldToA7]) ")
or die(mysql_error());
$flytnedTA->execute();
SOLVED! I just put my arrays into it own variable
$intoVarToA1 = $flytnedTo1[$nameOfFieldToA1];
$intoVarToA2 = $flytnedTo1[$nameOfFieldToA2];
$intoVarToA3 = $flytnedTo1[$nameOfFieldToA3];
$intoVarToA4 = $flytnedTo1[$nameOfFieldToA4];
$intoVarToA5 = $flytnedTo1[$nameOfFieldToA5];
$intoVarToA6 = $flytnedTo1[$nameOfFieldToA6];
$intoVarToA7 = $flytnedTo1[$nameOfFieldToA7];
You shouldn't substitute variables into the query, you should use bind_param() to provide parameter values for the prepared query.
$flytnedTA = $con->prepare(
"INSERT INTO $nameOfDBFromA
(ansatId, edit, $nameOfFieldToA1, $nameOfFieldToA2,
$nameOfFieldToA3, $nameOfFieldToA4, $nameOfFieldToA5,
$nameOfFieldToA6, $nameOfFieldToA7)
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?) ")
or die(mysqli_error($con));
$flytnedTA->bind_param("sssssssss", $_GET[ansatId], $redigeringsTidspunkt,
$flytnedTo1[$nameOfFieldToA1], $flytnedTo1[$nameOfFieldToA2],
$flytnedTo1[$nameOfFieldToA3], $flytnedTo1[$nameOfFieldToA4],
$flytnedTo1[$nameOfFieldToA5], $flytnedTo1[$nameOfFieldToA6],
$flytnedTo1[$nameOfFieldToA7]);
$flytnedTA->execute();
You also need to call mysqli_error($con), not mysql_error().
One of your mistakes is when you want to access a value in an array inside of a string, you can't do:
"$flytnedTo1[$nameOfFieldToA1]"
You have to do it like this:
"{$flytnedTo1[$nameOfFieldToA1]}" // use curly brackets
If you have variables like that, you can insert data into db like below in php.
$first_name = mysqli_real_escape_string($link, $_POST['firstname']);
$last_name = mysqli_real_escape_string($link, $_POST['lastname']);
$email_address = mysqli_real_escape_string($link, $_POST['email']);
$sql = "INSERT INTO persons (first_name, last_name, email_address) VALUES ('$first_name', '$last_name', '$email_address')";
Is not a good practice put _GET or _POST variables directly on query, use mysqli_real_escape_string to clear the value in variable.
The array values are not parsed directly in strings, you must enclose the expression in {}:
For this: " $flytnedTo1[$nameOfFieldToA3] " replace with: "'{$flytnedTo1[$nameOfFieldToA3]}'" , the result value also need to enclosed by '' singlequoes for sql string value.
$flytnedTA = $con->prepare("INSERT INTO $nameOfDBFromA (ansatId, edit, $nameOfFieldToA1, $nameOfFieldToA2, $nameOfFieldToA3,
$nameOfFieldToA4, $nameOfFieldToA5, $nameOfFieldToA6, $nameOfFieldToA7)
VALUES({$_GET['ansatId']}, '$redigeringsTidspunkt', '{$flytnedTo1[$nameOfFieldToA1]}', '{$flytnedTo1[$nameOfFieldToA2]}',
'{$flytnedTo1[$nameOfFieldToA3]}', '{$flytnedTo1[$nameOfFieldToA4]}', '{$flytnedTo1[$nameOfFieldToA5]}',
'{$flytnedTo1[$nameOfFieldToA6]}', '{$flytnedTo1[$nameOfFieldToA7]}') ") or die(mysql_error());
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')
I have a form with text input fields & select dropdowns which submits information to profile-updated.php. It worked as a simple UPDATE query but I tried to make it into a parameterised query and it does not work. It doesn't give me an error, it just doesn't actually update anything. I did a tutorial for a parameterised SELECT or INSERT query so I probably messed something up when trying to make it suit my UPDATE needs with the "$_POST['age'];" portion. Any help hugely appreciated.
Here is the attempted parameterised query code:
$age = $_POST['age'];
$gender = $_POST['gender'];
$videourl = $_POST['videourl'];
$soundcloud = $_POST['soundcloud'];
$about = $_POST['about'];
$facebook = $_POST['facebook'];
$twitter = $_POST['twitter'];
$stmt = $con->stmt_init();
if ($stmt->prepare("UPDATE Users1 (age, gender, videourl, soundcloud,
about, facebook, twitter) VALUES (?, ?, ?, ?, ?, ?, ?) WHERE email = '" . $_POST['email'] . "' ")) {
$stmt->bind_param("sssssss", $age, $gender, $videourl, $soundcloud, $about, $facebook, $twitter);
$stmt->execute();
$stmt->close();
}
$con->close();
Here is my old update code that worked fine:
$sql = mysqli_query($con, "UPDATE Users1
SET age = '" . $_POST['age'] . "',
gender = '" . $_POST['gender'] . "',
videourl = '" . $_POST['videourl'] . "',
soundcloud = '" . $_POST['soundcloud'] . "',
about = '" . $_POST['about'] . "',
facebook = '" . $_POST['facebook'] . "',
twitter = '" . $_POST['twitter'] . "',
WHERE email = '" . $_POST['email'] . "'
");
I think the syntax of your update statement is incorrect. Your 'old update code' uses the correct one.
That syntax is more appropriate to the 'insert' statement.
Try:
$stmt->prepare( "update users1 set age = ?, gender = ?, ... where email = ?" );
$stmt->bind_param( ... , $_POST[ 'age' ] );
and so on.
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();
}