How to use PHP variables with SELECT and INSERT INTO SQL Statements - php

Below is the code i'm trying to get to work:
$y= "SELECT ('PRV_IDX')
FROM LLS_PRIVILEGES
WHERE `PRV_NAME` = 'Reader';";
mysql_query($y);
$x= "SELECT ('USER_IDX')
FROM LLS_USERS
WHERE `USR_LOGIN` = '".$_SESSION['tool_user']."';";
mysql_query($x);
$w= "INSERT INTO LLS_USERS_PRIVILEGES
(USP_USR_IDX,USP_PRV_IDX)
VALUES ($x,$y); ";
mysql_query($w);
I want to insert these values from the select statements into the final table. However, I am not sure if my Syntax is correct and I have been unable to find a solution online. I wasn't sure if you had to do the mysql_query each time for the select statement to actually take hold in and place it in the $variable.
Sorry, I'm new to SQL, but thank you for the help!

mysql_* functions are deprecated. Use PDO instead :
$y=$dbh->query("SELECT ('PRV_IDX')
FROM LLS_PRIVILEGES
WHERE `PRV_NAME` = 'Reader'");
$x=$dbh->prepare("SELECT ('USER_IDX')
FROM LLS_USERS
WHERE `USR_LOGIN` = ?");
$x->execute(array($_SESSION['tool_user']));
$w=$dbh->prepare("INSERT INTO LLS_USERS_PRIVILEGES
(USP_USR_IDX,USP_PRV_IDX)
VALUES (?,?)");
$y="SELECT ('PRV_IDX')
FROM LLS_PRIVILEGES
WHERE `PRV_NAME` = 'Reader'";
$x="SELECT ('USER_IDX')
FROM LLS_USERS
WHERE `USR_LOGIN` = '".$_SESSION['tool_user']."'");
$w->execute(array($x,$y));
More About PDO : http://www.php.net/manual/en/book.pdo.php

Related

How to insert spatial data in MySQL with PHP?

I want to save my coordinate from my Android application to a MySQL database. For this I created an API in PHP, but my code is not working.
Here is my PHP code:
<?php
include_once 'db.php';
$nop = $_POST['nop'];
$plot_bng = $_POST['plot_bng'];
$result = mysqli_query($con, "INSERT INTO sp_house (geom, d_nop)
VALUES (STGeomFromText('POINT($plot_bng)'), '$nop')");
echo json_encode(array("value"=>1));
mysqli_close($con);
?>
When I try an INSERT query in phpMyadmin, the data is successfully stored in the database.
Check the right property for the columns
First of all, make sure you have created the right spatial columns in the database by using the GEOMETRY keyword.
CREATE TABLE sp_house (geom GEOMETRY, d_nop VARCHAR(255));
Insert data into the database with authentication
After you created the columns with the right property you can insert the data into your database. However, your code is widely open to SQL Injection and other kind of database hackings since you insert data directly without any kind of authentication. In order to avoid it, use prepared statements and the mysqli_real_escape_string function. Also, check that you have the right syntax for the query and replace STGeomFromText to ST_GeomFromText.
<?php
include_once 'db.php';
$nop = $_POST['nop'];
$plot_bng = $_POST['plot_bng'];
// You can also check that the variables are empty or not ...
// Clean the variables and prepare for inserting
$plot_bng = mysqli_real_escape_string($con, $plot_bng);
$nop = mysqli_real_escape_string($con, $nop);
$sql = "INSERT INTO sp_house (geom, d_nop)
VALUES (ST_GeomFromText(POINT(?)), ?)";
// Prepared statement for inserting
$stmt = $conn->prepare($sql); // prepare statement for inserting
$stmt->bind_param("ss",$plot_bng,$nop); // replace question marks with values
$stmt->execute(); // execute command
$stmt->close(); // close connection
echo json_encode(array("value"=>1));
mysqli_close($con);
?>
Reference and further reading
Creating Spatial Columns in MySQL
Populating Spatial Columns
How to avoid SQL Injection?
How to use prepared statements?
You're not writing your var correctly, try like this
$result = mysqli_query($con, "INSERT INTO sp_house (geom, d_nop)
VALUES (STGeomFromText('POINT(".$plot_bng.")'), '".$nop."')");
As you writing it, the vars are just normal text...

Is there an INSERT or UPDATE equivalent to PDO::FETCH_CLASS?

I have found the PDO::FETCH_CLASS very useful. My classes map to tables. I just do a
$query = $pdo->query("SELECT * FROM fixedTime WHERE
transmissionProgramID = '$transmissionProgramID'");
$query->setFetchMode(PDO::FETCH_CLASS, 'FixedTime');
and voila.
I would like to be able to do the reverse: ie instantiate an object load up the values to UPDATE or INSERT and once again voila.
Have looked but cannot see if this is available.
Well, yes. To some extent you can use something similar for insert or update.
But to achieve that, you have to learn how to use PDO properly. So, first we have to fix your select code:
$sql = "SELECT * FROM fixedTime WHERE transmissionProgramID = ?";
$stmt = $pdo->prepare($sql);
$stmt->execute([$transmissionProgramID]);
$stmt->setFetchMode(PDO::FETCH_CLASS, 'FixedTime');
$ftime = $stmt->fetch();
See - we are using prepared statements here, that you should be always using anyway. And at the same time that's the key for the [semi-]automation we can use with updates. Because with prepared statements you can use the object itself to provide values for the prepared query.
So, as long as you have object properties reflect table fields you can use a code like this:
$user = new stdClass();
$user->name = "foo";
$user->pass = "bar";
$sql = "INSERT INTO users VALUES (NULL, :name, :pass)";
$pdo->prepare($sql)->execute((array)$user);
But for the real automation you have to consider using an ORM, which is doing exactly what you're looking for. You can take a look at Eloquent for example. So, the code would be as simple and straightforward as
$ftime = new fixedTime;
$ftime->value = time();
$ftime->save();

You have an error in your SQL syntax, but cant seem to trace error

I am using the following script to enter data into my database from a form. I have echo'd each of the values declared at the beginning and they are all coming across just fine.
include("connectmysqli.php");
echo '<link rel="stylesheet" href="http://towerroadacademy.co.uk/templates/rt_reflex_j16/css/template.css">';
if (isset($_GET['questionnaireID'])) {$questionnaireID = $_GET['questionnaireID'];}else {$questionnaireID = '';}
if (isset($_POST['newquestionnumber'])) {$questionnumber = $_POST['newquestionnumber'];}
if (isset($_POST['questionID'])) {$questionID = $_POST['questionID'];}else {$questionID = '';}
if (isset($_POST['question'])) {$question = $_POST['question'];}else {$question = '';}
if (isset($_POST['lowerlabel'])) {$lowerlabel = $_POST['lowerlabel'];}else {$lowerlabel = '';}
if (isset($_POST['middlelabel'])) {$middlelabel = $_POST['middlelabel'];}else {$middlelabel = '';}
if (isset($_POST['upperlabel'])) {$upperlabel = $_POST['upperlabel'];}else {$upperlabel = '';}
$stmt = $db->prepare("INSERT INTO `QuestionnaireQuestions` (`questionnaireID`, `questionnumber`, `questionID`, `question`, `lowerlabel`, `middlelabel`, `upperlabel`) VALUES ($questionnaireID', '$questionnumber', '$questionID', '$question', '$lowerlabel', '$middlelabel', '$upperlabel') WHERE questionnaireID='$questionnaireID';");
if (!$stmt) trigger_error($db->error);
$stmt->execute();
I keep getting the following error though and cant seem to trace what is causing it.
Notice: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '', '3', '1947679104', 'questonofngdfngodfngo', 'lower', 'midddle', 'upper') WHER' at line 1 in /home2/towerroa/public_html/questionnaires/addanotherquestionsubmit.php on line 16 Fatal error: Call to a member function execute() on a non-object in /home2/towerroa/public_html/questionnaires/addanotherquestionsubmit.php on line 17
The table QuestionnaireQuestions looks like this :
id questionnaireID questionnumber questionID question lowerlabel middlelabel upperlabel
You're missing a quote on $questionnaireID:
INSERT INTO `QuestionnaireQuestions` (`questionnaireID`, `questionnumber`, `questionID`, `question`, `lowerlabel`, `middlelabel`, `upperlabel`) VALUES ('$questionnaireID', '$questionnumber', '$questionID', '$question', '$lowerlabel', '$middlelabel', '$upperlabel')
Also remove the WHERE clause.
UPDATE statements can use the WHERE statement to update existing database records based upon a condition. Granted INSERT SELECT statements can contain a WHERE, INSERT statements by themselves do not.
INSERT will not work with the WHERE condition,if only you want to UPDATE the row then you can use WHERE condition and replace this
VALUES ($questionnaireID',......
with
VALUES ('$questionnaireID',
You have missed a single quote and remove ';' from the end also.Now the query will be
$stmt = $db->prepare("INSERT INTO `QuestionnaireQuestions` (`questionnaireID`,
`questionnumber`, `questionID`, `question`, `lowerlabel`,
`middlelabel`, `upperlabel`) VALUES ('$questionnaireID',
'$questionnumber', '$questionID', '$question', '$lowerlabel',
'$middlelabel', '$upperlabel')");
But I must appreciate that you are using PDO statements instead of mysql_* deprecated functions
($questionnaireID'
should be
('$questionnaireID'
but you should really try working with prepared statements

How can I use array values in WHERE clauses?

I'm trying to figure out how to use a array variable with a where clause.
when I echo $deader, I get 23,25,43,56,31,24,64,34,ect.. these are id numbers i want Updated
$sql = mysql_query("UPDATE users SET dead='DEAD' WHERE userID ='(".$deader.")' ");
The Array$deader has multiple values of id numbers, it only works and updates the first id# in the $deader Array.
I'm reading that Implode is what I need, but don't know how to get it into a functional format.
Use WHERE ... IN
$sql = mysql_query("UPDATE users SET dead='DEAD' WHERE userID IN (".$deader.")");
Where $deader is in comma separated format. (for example: $deader = '143, 554, 32')
If it is an array you can use $deader = implode(',', $deader); to make it comma separated.
Note:
Please stop using mysql_* functions for new code. The functions aren't maintained anymore and the community has begun the deprecation process. See here for more info about converting this to PDO: How do I convert a dynamically constructed ext/mysql query to a PDO prepared statement? (thanks to PeeHaa)
If $deader is some sort of string of values, you will need to use MySQL IN() condition. Like this
UPDATE users SET dead = 'DEAD" WHERE userID IN ('?', '?', '?')
Where ? are your values. If userID as an INTEGER field, you can omit the single quotes around the values, if it is a string field, they would be required.
I think what you're looking for is the IN keyword in SQL.
UPDATE users set dead='DEAD' where userID in (100,101,102)
Using MySQLi instead of mysql_*
require_once('.dbase'); //contains db constants DB_NAME, DB_USER etc
//using PHP built in connection class mysqli
$mysqli = new mysqli(DB_HOST,DB_UNAME,DB_UPWORD,DB_NAME);
if ($mysqli->connect_errno){
$err = urlencode("Failed to open database connection: ".$mysqli->connect_error);
header("Location: error.php?err=$err");
exit();
}
$deader=implode(',',$deader); //assumes array, sting "143,554,32"
if ($stmt = $mysqli->prepare("UPDATE users SET dead='DEAD' WHERE userID IN (?)"){
//bind variable to statement object
$stmt->bind_param('s',$deader) //var type[string],var to bind
//execute query
$stmt->execute();
//feedback
$rowsAffected = $stmt->affected_rows(); //update doesn't return a result set.
//close statement object
$stmt->close();
}
$mysqli->close();
You guys are hammering on Rickos for using mysql_* but not explaining how to do it otherwise, my point was simply showing how to use mysqli. A prepared statement isn't necessary, but since you marked my comment down (peehaa) for not showing it as a prepared statement, here it is edited as a prepared statement. And it does answer his questions.

parameters in MySQLi

I'm using PHP with MySQLi, and I'm in a situation where I have queries like
SELECT $fields FROM $table WHERE $this=$that AND $this2=$that2
So far I've written some code that splices up an array that I give it, for example:
$search = array(name=michael, age=20) //turns into
SELECT $fields FROM $table WHERE name=michael AND age=20
Is there a more efficient way to do this?
I'm rather worried about MySQL injections - this seems very vulnerable.
Thanks!
Oddly enough, the title to your question is basically the answer to it. You want to do something like this, using mysqli parameterized queries:
$db = new mysqli(<database connection info here>);
$name = "michael";
$age = 20;
$stmt = $db->prepare("SELECT $fields FROm $table WHERE name = ? AND age = ?");
$stmt->bind_param("si", $name, $age);
$stmt->execute();
$stmt->close();
More information in the mysqli section of the manual, specifically the functions related to MySQLi_STMT.
Note that I personally prefer using PDO over mysqli, I don't like all the bind_param / bind_result stuff that mysqli does. If I have to use it I write a wrapper around it to make it work more like PDO.

Categories