mysqli, prepared statements, and INSERT-SELECTs

末鹿安然 提交于 2019-12-23 13:13:25

问题


Let's pretend that I have two tables in an InnoDB database: categories and jokes; and that I'm using PHP/MySQLi to do the work. The tables look like so:

CATEGORIES
id (int, primary, auto_inc)  |  category_name (varchar[64])
============================================================
1                               knock, knock

JOKES
id (int, primary, auto_inc)  |  category_id (int)  | joke_text (varchar[255])
=============================================================================
empty

Thanks to a previous answer on here, I discovered that you could do the following in order to add a new joke comprised of: $joke_text, $category_id.

INSERT INTO jokes (category_id, joke_text)
SELECT c.id, '$joke_text'
FROM categories AS c WHERE c.id = $category_id;

This enables me, without the use of foreign keys, to be sure that the $category_id value refers to an existing category (please ignore the issue of foreign keys, as my question is aimed at helping me learn "complicated" prepared statements).

So that worked just fine. However, I am now trying to learn prepared statements and, after spending all day on it, I finally have the basics down. Unfortunately, I have ABSOLUTELY NO IDEA how to to execute the above SQL query with prepared statements, under mysqli, and I have not been able to find any info online regarding such an issue.

If anyone can help me out, I'd be very appreciative.


回答1:


First you create the statement very much like a normal statement you have made

$stmt = $mysqli->prepare("INSERT INTO jokes (category_id, joke_text)
SELECT c.id, ?
FROM categories AS c WHERE c.id = ?;");

Get the statement bound to the parameter 's' stands for string data and i for integer

$stmt->bind_param('si', $joke_text,$category_id);   // bind to the parameters

/* execute prepared statement */

$stmt->execute();



回答2:


I was actually writing some code but I realised that you were searching online for this too. So instead I got you the link to the PHP website where you can see many of these.

Prepared statements

mysqli in general

Since you are learning MySQLi, why not just move to PDO instead. It's very similar but I think that's where the future of this is headed.

http://php.net/manual/en/book.pdo.php

http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers



来源:https://stackoverflow.com/questions/18393635/mysqli-prepared-statements-and-insert-selects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!