Use a function to insert 2 queries in mysql - php

Currently I am trying to write a single function in my php script that adds a new page into my database and updates the navigation table at the same time. For some reason both queries are failing, and I'm not sure what else I should do.
This is my add_content function call:
elseif ($react == "add_content") {
echo 'add content';
$title = $_POST['title'];
$content = $_POST['content'];
$page = $_POST['page'];
if (!empty($title) && !empty($content) && !empty($page)) {
addcontent($title, $content, $page);
} else {
echo 'not enough info';
}
and this is my function:
function addcontent($title, $content, $page) {
global $db;
$query1 = "INSERT INTO `content`(`title`, `content`) VALUES (:title, :content)";
$query2 = "INSERT INTO `navigation` ('page', 'content_id') SELECT :page, c.content_id FROM content c WHERE title=:page;";
try {
$stat = $db->prepare($query1);
$stmt = $db->prepare($query2);
$stat->bindParam(':title', $title);
$stat->bindParam(':content', $content);
$stat->bindParam(':page', $page);
$stat->execute($query1);
$stmt->execute($query2);
$result = "<strong>$title</strong> added<p>";
} catch (Exception $ex) {
$result = "$title deltetion failed";
}
}
I know the two queries work because I've already tested them with dummy information, it's just getting them to work inside of this function that's causing the problem.
I'm not sure if this is needed, but just in case, this is my table to add content:
<form method="POST" action="index.php">
<input type="hidden" name="react" value="add_content">
<input type="hidden" name="page|title" value="admin">
<div align="center"><center><p>ADD A New Page<br>
Title: <input type="text" name="title|page" size="20"><br>
Content: <input type="text" name="content" size="20"><br>
<input type="submit" value="Submit"></p></center></div>
</form>

$query2 = "INSERT INTO `navigation` ('page', 'content_id')
SELECT :page, c.content_id FROM content c WHERE title=:page;";
^ column name marker
You can't use markers for column names. From the docs
The markers are legal only in certain places in SQL statements. For
example, they are allowed in the VALUES() list of an INSERT statement
(to specify column values for a row), or in a comparison with a column
in a WHERE clause to specify a comparison value. However, they are not
allowed for identifiers (such as table or column names), in the select
list that names the columns to be returned by a SELECT statement), or
to specify both operands of a binary operator such as the = equal
sign. The latter restriction is necessary because it would be
impossible to determine the parameter type. In general, parameters are
legal only in Data Manipulation Language (DML) statements, and not in
Data Definition Language (DDL) statements.
If you're trying to select the constant $page you can select c.title because your where condition guarantees that it will be equal to $page.
$query2 = "INSERT INTO `navigation` ('page', 'content_id')
SELECT c.title, c.content_id FROM content c WHERE title=:page;";
Also, you're binding $page to the wrong statement
$stat->bindParam(':page', $page);
Change it to
$stmt->bindParam(':page', $page);
^

Related

I have a problem with "ADD" and "INSERT" functions in database

I wanna ask you, how can I fix this code? I have a problem with "ADD" and "INSERT" functions in database. I can only delete from database, but "add and insert" functions do nothing.
this is my about.php file.
$mode = 'add';
$about = '';
if(isset($_GET['edit']) && is_numeric($_GET['edit'])){
$sql = "SELECT * FROM `about_me` WHERE `about_me`.`id` =".$_GET['edit'];
$result_about = mysqli_query($conn, $sql);
if(mysqli_num_rows($result_about) == 1) {
$mode = 'edit';
$about = mysqli_fetch_assoc($result_about);
}
}
$apie = '';
if(isset($_POST["submit"])){
if(isset($_POST["apie"])){
$apie = trim($_POST["apie"]);
}
}
elseif($mode=='edit') {
$apie = $about['about'];
}
if($mode=='add') {
if(($apie!='')){
$sql = 'INSERT INTO about_me(about)
VALUES ("'.$apie.'")';
mysqli_query($conn, $sql);
header('Location:about.php');
die();
}
}
elseif($mode=='edit') {
if(($apie!='')){
$sql = "UPDATE `about_me` SET `about` = '".$apie."' WHERE `about_me`.`id` = ".$_GET['edit'];
mysqli_query($conn, $sql) ;
}
}
<..>
<input type = "text" name = "apie" value = "<?php echo $apie; ?>">
<br><br>
<input type = "submit" name = "submit" value = "Gerai">
<br><br>
I checked mysql error, with https://www.w3schools.com/php/func_mysqli_error.asp, and then it insert in my DB. I think there is code foult, but I don't know where.
You have a slight error with your first query, you can't use parentheses next to the database selector, I'd recommend creating a separate file with a database connection that you can refer to as $conn, your first query should look like this:
$sql = "INSERT INTO about_me
VALUES (?)";
Also, you should look into prepared statements for your queries, instead of inserting them directly you use a question mark? to which you bind the parameter/parameters. This helps prevent SQL injections!
Hope this helps!:)

Fetching data from two MySQL tables simlutenously with PHP + AJAX

I'm creating a search box that queries two MySQL tables and lists the results in real time. For now though, I have a working prototype that will query only one table. I've written the following PHP code in conjunction with JQuery and it works wonderfully:
HTML
<input onkeyup="search(this);" type="text">
<ol id="search-results-container"></ol>
Javascript
function search(input) {
var inputQuery = input.value;
/* $() creates a JQuery selector object, so we can use its html() method */
var resultsList = $(document.getElementById("search-results-container"));
//Check if string is empty
if (inputQuery.length > 0) {
$.get("search-query.php", {query: inputQuery}).done(function(data) {
//Show results in HTML document
resultsList.html(data);
});
}
else { //String query is empty
resultList.empty();
}
}
and PHP
<?php
include("config.php"); //database link
if(isset($_REQUEST["query"])) {
$sql = "SELECT * FROM students WHERE lastname LIKE ? LIMIT 5";
/* Creates $stmt and checks if mysqli_prepare is true */
if ($stmt = mysqli_prepare($link, $sql)) {
//Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "s", $param_query);
//set parameters
$param_query = $_REQUEST["query"] . '%';
//Try and execute the prepared statement
if (mysqli_stmt_execute($stmt)) {
$result = mysqli_stmt_get_result($stmt);
//get number of rows
$count = mysqli_num_rows($result);
if ($count > 0) {
//Fetch result rows as assoc array
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
echo "<h1>Students:</h1>"; //Header indicates student list
for ($i = 0; $i < $count; $i++) {
$name = $row["lastname"];
echo "<p>$name</p>";
}
}
else { //Count == 0
echo "No matches found.<br>";
}
}
else { //Execution of preped statement failed.
echo "Could not execute MySQL query.<br>";
}
} // end mysqli_prepare
} // end $_RESQUEST isset
?>
The details of the students table are arbitrary, except for the fact that it has a String column that lists the student's last name.
My problem is that there is also a staff table which is effectively the same as students but for a different purpose. I'd like to query the staff table at the same time as students, but have the results separated like so:
<h1>Students:</h1>
<p>Student1</p>
<p>Student2</p>
<h1>Staff</h1>
<p>Staff1</p>
<p>Staff2</p>
The obvious answer would be to add another $sql statement similar to the one on Line 5 and just do both queries serially - effectively doubling the search time - but I'm concerned this will take too long. Is this a false assumption (that there will be a noticeable time difference), or is there actually a way to do both queries alongside each other? Thanks in advance!
If the two tables have identical structures, or if there is a subset of columns which could be made to be the same, then a UNION query might work here:
SELECT *, 0 AS type FROM students WHERE lastname LIKE ?
UNION ALL
SELECT *, 1 FROM staff WHERE lastname LIKE ?
ORDER BY type;
I removed the LIMIT clause because you don't have an ORDER BY clause, which makes using LIMIT fairly meaningless.
Note that I introduced a computed column type which the result set, when ordered by it, would place students before staff. Then, in your PHP code, you would just need a bit of logic to display the header for students and staff:
$count = mysqli_num_rows($result);
$type = -1;
while ($count > 0) {
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
$curr_type = $row["type"];
if ($type == -1) {
echo "<h1>Students:</h1>";
$type = 0;
}
else if ($type == 0 && $curr_type == 1) {
echo "<h1>Staff:</h1>";
$type = 1;
}
$name = $row["lastname"];
echo "<p>$name</p>";
--$count;
}

Wordpress and SQL, compare condition

I wanna compare "postType",
<input name="postType" value="" id="postType" required>
with a column in my DB called "post_type" (from table wp_posts). So, I just wanna the results with matches the input with the value in post_type column. I don't know if I can do a for each or put a SQL statement. Examples:
if($_POST["postType"] == "page") {
//results
}
So, if I put "page" in my input it returns the correct results.
What I've done to the general case:
$term = $_POST["postType"];
$result = $wpdb->get_results("SELECT count(ID) FROM $wpdb->posts WHERE post_type = '".$term."')");
foreach($result as $resultX) {
if($_POST["postType"] == $resultX) {
//results
}
}
But it is not working

php cant insert array data into database

the sql :
$sql = $db->prepare('SELECT * FROM product_detail WHERE size = $order_size AND product_id = $order_detail_product_id');
the code:
$order_detail_product_id = $_POST['order']['product_id'];
$order_size = $_POST['order']['size'];
html:
<?php foreach ($it as $e) { >?
<input type="text" name="order[product_id][]" value="<?php echo $e[0]; ?>">
<input type="text" name="order[size][]" value="<?php echo $e[3]; ?>">
<?php } ?>
why that's can't work. the error is array to string conversion
You can't use variables like that inside single quotes in your prepare statement (you'd need double quotes for that to make sense, but it'd still be quite bad and still doesn't make sense cause you're using an array as a string), and also putting the value inside the string you prepare beats the purpose of preparing, you should do:
foreach ($order_size as $key => $size):
$stmt = $db->prepare('SELECT * FROM product_detail WHERE size = ? AND product_id = ?');
$stmt->bindParam(1, $size);
$stmt->bindParam(2, $order_detail_product_id[$key]);
...
endforeach;
Or a different query, depending on what you want, which is not easy to guess with what you posted.
Assuming you're using pdo and not mysqli (which would suck).

How to insert these values correctly in the database

Below is part of the code where it uploads a file (fileImage) into a folder (ImageFiles). But what I want to also do is INSERT the file location (The location the file is uploaded into) into the database using INSERT VALUES code. I want the file location to be inserted into the "ImageFile" field and for the "ImageId" I want it to display the string "IMG" and then include a number after the string. For Example:
In my database table if it reads like this:
ImageId ImageFile
IMG1 ImageFiles/penguins.png
IMG2 ImageFiles/desert.png
IMG3 ImageFiles/jellyfish.jpg
Then if I upload the file from my computer 'tulips.png' into the ImageFiles folder, then in the database it should insert the values like this below:
ImageId ImageFile
IMG4 ImageFiles/tulips.png
But how can this be coded? Below is my code at the moment which uploads the file successfully and contains only partial coding of the INSERT VALUES:
move_uploaded_file($_FILES["fileImage"]["tmp_name"],
"ImageFiles/" . $_FILES["fileImage"]["name"]);
$result = 1;
$imagesql = "INSERT INTO Image (ImageId, ImageFile)
VALUES ("");
mysql_query($imagesql);
If you use PHPs PDO object it would simplify your code and make it more safe at the same time (by using prepared statements).
Here's an example of how you would do that:
Firstly, store your ID as an AUTO_INCREMENT-ed INT rather than "IMG#" as this would make things easier (you wouldn't need to INSERT the ID value then)
DROP TABLE IF EXISTS tbl_img_store;
CREATE TABLE tbl_img_store(
id INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(id),
filename VARCHAR(25) --increase this if you think you need to
) ENGINE=InnoDB;
Also, create a table to store configuration settings to make your database more efficient:
DROP TABLE IF EXISTS tbl_img_config;
CREATE TABLE tbl_img_config(
img_path VARCHAR(50)
);
INSERT INTO tbl_img_config (img_path) VALUES ("http://img.mysite.com/?i=");
Now back to PHP, you can quickly insert a load of images like this:
# Create a DB connection
$db = new PDO("mysql:host=X.X.X.X;dbname=mydb", $user, $pass);
# Compile an array of image paths
$img1path = "img1.png";
$img2path = "img2.png";
$img3path = "img3.png";
$images = array($img1path, $img2path, $img3path);
# Create a query to insert the paths to the db
$sql = "INSERT INTO tbl_img_store (filename) VALUES (?),(?),(?);";
$query = $db->prepare($sql);
$query->execute($images);
# Check rows affected
$rows = $query->rowCount();
echo "$rows images were saved.";
You should use an auto incremented id for identifying images instead of using strings for this.
This would ease up the process for you as you would only have to insert a single fields and the autoi ncremented fields updates automatically.
$imagesql = "INSERT INTO Image (ImageFile) VALUES ('ImageFiles/".mysql_real_escape_string($_FILES['fileImage']['name'])."')";
ImageId should then be of type INT as PRIMARY KEY with AUTO INCREMENT instead. That's also a good way to design your tables.
You need to add the values to the query like this
$imagesql = "INSERT INTO Image (ImageId, ImageFile)
VALUES ('$imageName','$imageFile');";
But first make sure you escape the values correctly to avoid any problems. Also note that it's not recommended to use the mysql_ functions any more. Instead use mysqli_ equivalents or better still PDO (with PDO it will automatically handle the DB escaping for you.
You can use MySql Auto increment .. you don't need to worry about IMG IMG2 ... etc
See : http://dev.mysql.com/doc/refman/5.5/en/example-auto-increment.html
Example:
Assumption : ImageId is an auto increment field
http://dev.mysql.com/doc/refman/5.5/en/example-auto-increment.html
$tmpName = $_FILES ["fileImage"] ["tmp_name"];
$fileName = $_FILES ["fileImage"] ["tmp_name"];
move_uploaded_file ( $tmpName, $fileName );
$sql = "INSERT INTO Image (ImageId, ImageFile) VALUES (NULL,'%s');";
mysql_query ( sprintf ( $sql, mysql_real_escape_string ( $fileName ) ) );
When you want to get your images
$sql = "SELECT ImageId, ImageFile FROM Image";
$result = mysql_query ( $sql );
while ( $row = mysql_fetch_assoc ( $result ) ) {
echo "IMG", $row ["ImageId"], " = ", 'ImageFiles/' , $row ["ImageFile"], PHP_EOL;
}
Reason Why you should use this
A. IMG and ImageFiles/ are constant saving them several times is not efficient
B. integer based id would also faster than varchar and performs better on `JOIN
C. To get IMGX where X is an increment value would involve multiple SQL calls .. and not efficient
This is what I do. For an answer to your question, look near the end of the second file, for the mysql_query for SELECT LAST_INSERT_ID(). Note that I don't INSERT an id but let the database auto_increment.
The image is uploaded through upload.php, part of which looks like this:
<form>
<?php
session_start();
if (isset($error["image"])) echo '<span class="error">'.$error["image"].'</span>'; else echo 'Select an image<span class="required"> *</span>';
if ($imgVars["is_image"] == "J") {
echo '
<input type="hidden" name="image_url" value="'.$imgVars["image_url"].'">
<input type="hidden" name="image_type" value="'.$imgVars["image_type"].'">
<input type="hidden" name="is_image" value="J">
<img src="'.$imgVars["image_url"].'" width="224" height="168" alt="Image">
<p>Change image?</p>';
?>
<input type="file" name="image">
<input type="submit" name="upload" value="Upload" title="Upload your image">
</form>
Then the uploaded file is processed through process.php, part of which looks like this:
<?php
session_start();
if (!session_is_registered("error"))
session_register("error");
$error = array();
if (!session_is_registered("imgVars"))
session_register("imgVars");
foreach($_POST as $varname => $value)
$imgVars[$varname] = trim(EscapeShellCmd(stripslashes($value)));
$imgVars = array();
if ($imgVars["is_image"] != 'J') {
$imgVars["is_image"] = 'N';
if ($_FILES["image"]["size"] > 0) {
$size = GetImageSize($_FILES["image"]["tmp_name"]);
$width = $size[0];
$height = $size[1];
if(($width != 224) || ($height != 168)) {
$error["image"] = 'Image dimensions must be exactly 224 x 168 pixel!';
$imgVars["is_image"] = "N";
}
preg_match("/(\.\w+)$/",
$_FILES["image"]["name"],$match);
$imagetype = $match[1];
if (!in_array(strtolower($imagetype), array(".jpg",".jpeg",".gif",".png"))) {
$error["image"] = 'You may upload only images of type JPEG, GIF and PNG!';
$imgVars["is_image"] = "N";
}
if ($imgVars["is_image"] == "J") {
$filename = time().$imagetype;
copy($_FILES["image"]["tmp_name"], "img/".$filename);
$imgVars["image_url"] = "img/".$filename;
$imgVars["image_type"] = $imagetype;
}
} else {
$error["image"] = 'Please upload an image!';
}
}
if (count($error))
{
header('Location: upload.php');
exit();
}
// connect to database
$query = "INSERT INTO images SET image_url = '" . $imgVars["image_url"] . "';
if (!($result = # mysql_query ($query, $connection)))
die("Your mysql error routine here.");
$rs = mysql_query("SELECT LAST_INSERT_ID()", $connection);
$lid = mysql_fetch_row($rs);
$image_id = $lid[0];
if ($imgVars["is_image"] == 'J') {
rename ($imgVars["image_url"], "img/".$image_id.$imgVars["image_type"]);
$query = "UPDATE images SET image_url = 'img/".$image_id.$imgVars["image_type"]."' WHERE image_id = '".$image_id."'";
if (!(# mysql_query ($query, $connection)))
die("Your mysql error routine here.");
}
session_unregister("formVars");
session_unregister("fehler");
header('Location: danke.php');
exit();
?>
There might be typos or omissions in this code, because I translated and trimmed it from my original file without testing.
First of all : ALWAYS use mysql_real_escape_string when inserting values in the db.
Then :
$query = "INSERT INTO `Image` (`ImageId`, `ImageFile`)
VALUES ('".mysql_real_escape_string($_FILES["fileImage"]["tmp_name"])."','".
mysql_real_escape_string($_FILES["fileImage"]["name"])."'
);";

Categories