Using Variables in SQL Statements
Moderator: General Moderators
Using Variables in SQL Statements
Hi,i was wondering if anyone wold be able to post be a simple guide on how to use variables in SELECTand INSERT statements. I think it might also help other people in the community who may not want to ask this question.
You don't say what DBMS you're working with, but here's how to do it within MySQL.
- Christopher
- Site Administrator
- Posts: 13596
- Joined: Wed Aug 25, 2004 7:54 pm
- Location: New York, NY, US
SQL statements are strings, so you would use PHP's string capabilities. See Strings and String Functions. Those two sections are part of the essential reading for all PHP programmers and that information needs to be put to memory to be effective in PHP.
(#10850)
- RobertGonzalez
- Site Administrator
- Posts: 14293
- Joined: Tue Sep 09, 2003 6:04 pm
- Location: Fremont, CA, USA
Re: Using Variables in SQL Statements
a94060 wrote:Hi,i was wondering if anyone wold be able to post be a simple guide on how to use variables in SELECTand INSERT statements. I think it might also help other people in the community who may not want to ask this question.
Code: Select all
<?php
$numvar = 4;
$stringvar = 'This is a lousy string';
// Insert
$sql = "INSERT INTO mytable (table_id) VALUES ($numvar)";
// Select
$sql = "SELECT * FROM mytable WHERE table_id = $numvar";
// Update
$sql = "UPDATE mytable SET table_text = '$stringvar' WHERE table_id = $numvar";
// Delete
$sql = "DELETE FROM mytables WHERE table_id = $numvar";
?>- RobertGonzalez
- Site Administrator
- Posts: 14293
- Joined: Tue Sep 09, 2003 6:04 pm
- Location: Fremont, CA, USA