Setting a var in mysql and using in new query - php

I will like to do somthing like this
$tagNo = 12345;
mysql_query("var = SELECT `jobNo` FROM `Jobs` WHERE `tagNo`='".$tagNo."';
INSERT INTO `Locations` (`jobNo`,`tagNo`,`name`) VALUES (var, '".$tagNo."', 'blah')");
can this be done?

You can't assign variables like that, but you can achieve exactly what you're after using the INSERT...SELECT syntax:
mysql_query("INSERT INTO `Locations` (`jobNo`, `tagNo`, `name`)
SELECT `jobNo`, '".$tagNo."', 'blah' FROM `Jobs` WHERE `tagNo`='".$tagNo."'");
But, as has been explained in the comments, don't use mysql_* functions in new code.

you must fetch your query first and then insert the values you want.
or use insert .. select statment.
you can try this
$tagNo = '12345';
$var = mysql_query("SELECT `jobNo` FROM `Jobs` WHERE `tagNo`='".$tagNo."' ");
$row = mysql_fetch_array($var) ;
mysql_query("INSERT INTO `Locations` (`jobNo`,`tagNo`,`name`)
VALUES ('".$row['jobNo']."' , '".$tagNo."', 'blah')");
but this is very bad idea using mysql , instead use PDO or MYSQLI

Related

Search parameters SQLSRV_QUERY for WHERE IN syntax

I wonder if there is a way to pass some values into the parameters option on the sqlsrv_query function. I tried a few things but could not get it to work.
This query is what I want to be executed:
SELECT id, name, etc
FROM sqlTable
WHERE id IN ('1', '2', '100', '314')
I want to pass the WHERE IN values using the params option, like this:
$q = "SELECT id FROM sqlTable WHERE id IN ?";
$p = array(array('1', '2', '100', '314'));
sqlsrv_query($connection, $q, $p);
Right now I'm passing the values directly into the query string, but for obvious security reasons I want to pass them as parameters into the function.
Anyone any idea on how to achieve this?
Consider PDO binded parameters which you can pass a defined array in execute(). However, you would need to prepare the statement, knowing number of IN() clause items in advance.
try {
$dbh = new PDO("sqlsrv:server=$server;database=$database",$username,$password);
$sql = "SELECT * FROM sqlTable WHERE id IN (:first, :second, :third, :fourth)";
$STH = $dbh->prepare($sql);
$nums = array('1', '2', '100', '314');
$STH->execute($nums);
}
catch(PDOException $e) {
echo $e->getMessage()."\n";
}
So I have figured out this issue on the sql side. Now I pass a comma separated string with the ids to the query using the params in the sqlsrv_query() function. The query sets the string in a temporarily variable. Using a splitting function every id is stored in a temporarily table. As last I JOIN the temporarily table with the table from witch I want to get the results.
Splitting function in SQL:
CREATE FUNCTION dbo.splitstring ( #stringToSplit VARCHAR(MAX) )
RETURNS
#returnList TABLE ([Name] [nvarchar] (500))
AS
BEGIN
DECLARE #name NVARCHAR(255)
DECLARE #pos INT
WHILE CHARINDEX(',', #stringToSplit) > 0
BEGIN
SELECT #pos = CHARINDEX(',', #stringToSplit)
SELECT #name = SUBSTRING(#stringToSplit, 1, #pos-1)
INSERT INTO #returnList
SELECT #name
SELECT #stringToSplit = SUBSTRING(#stringToSplit, #pos+1, LEN(#stringToSplit)-#pos)
END
INSERT INTO #returnList
SELECT #stringToSplit
RETURN
END
PHP code and SQL query:
$q = "
DECLARE #inStr varchar(max)
SET #inStr = ?
DECLARE #tmpTable table (tmpID varchar(200))
INSERT #tmptable (tmpID)
SELECT * FROM dbo.splitstring(#inStr)
SELECT id, name, etc
FROM sqlTable
JOIN #tmpTable ON id = tmpID";
$p = array('1,2,100,314');
sqlsrv_query($connection, $q, $p);

Trying to make two sql queries, but always landing with error

$query=mysqli_query($conn,"INSERT INTO bus_info(bus_id,route_num,school_name) values('$BusNum','$RouteNum','$SchoolName'); INSERT INTO bus_loc(bus_id,lat,lon) values ((SELECT bus_id from bus_info where bus_info.bus_id='$BusNum'),'$latitude','$longitude')");
PHP
$BusNum = $_POST["BusNum"];
$SchoolName = $_POST["SchoolName"];
$RouteNum = $_POST["RouteNum"];
$latitude = $_POST["lat"];
$longitude = $_POST["lng"];
Database is connected i.e. returned true.enter code here
Fails with :
Error sending data:
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 INSERT INTO bus_loc(bus_id,lat,lon) values ((SELECT bus_id from bus_info where b at line 1
From: http://php.net/manual/de/mysqli.query.php#87203
mysqli::query() can only execute one SQL statement.
Use mysqli::multi_query() when you want to run multiple SQL statements within one query.
How to use mysqli_multi_query: http://php.net/manual/de/mysqli.multi-query.php
For better understanding split query into two parts and use them like :-
$query = mysqli_query($conn,"INSERT INTO bus_info (bus_id,route_num,school_name) values('$BusNum','$RouteNum','$SchoolName')");
$query2 = mysqli_query($conn,"INSERT INTO bus_loc (bus_id,lat,lon) values ((Select bus_id from `bus_info` where bus_id = '$BusNum'),'$latitude','$longitude')");
This query is missing a where clause condition
SELECT bus_id from bus_info where b
change it to like:
SELECT bus_id from bus_info where b = 'something'
but you should not execute two queries like this but execute this first save the result in a variable and then execute the next one like
$query = SELECT bus_id from bus_info where b = 'something'
$saved = $mysqli_query($yourconnection, $query);
$row = mysqli_fetch_assoc();
$fetched = row['columnnamehere'];
and then
INSERT INTO bus_loc(bus_id,lat,lon) values ('$fetched');

Mysql - conditional insert query with select and PDO

I am unable to understand on how to apply insert query with select statement:
I have gone through this question also:
MySQL INSERT from a SELECT with PDO
But where is the VALUES part??
Like I have this query to insert in Mysql and here I use Values also:
$db_conn->beginTransaction();
$query = $db_conn->prepare('INSERT INTO mytable (name, user_id) VALUES(:sname, :uid)');
foreach($UploadData AS $DataValue)
{
$query->execute(array(':sname' => $DataValue['Name'],':uid' =>$_SESSION['uid']));
}
$db_conn->commit();
My motto is to check if the name exists with the same uid it shouldn't import the data otherwise it should. But Where are the values part :/ I am blind :P
EDIT1: From MySQL INSERT from a SELECT with PDO
How will this code block work if no VALUES is supplied?
$sql_enc = '
INSERT INTO sessionid (enc_id, enc_pass, enc_date)
(SELECT AES_ENCRYPT(username, :aeskey), AES_ENCRYPT(pwd, :aeskey), DATE_ADD(NOW(), INTERVAL 15 SECOND) FROM users WHERE username = :username)
';
$res_enc = $pdo->prepare($sql_enc);
$res_enc->bindParam(':aeskey', $aeskey);
$res_enc->bindParam(':username', $username);
$res_enc->bindParam(':pwd', $username);
$res_enc->execute();
$res_enc = null;
There are two valid INSERT syntax:
INSERT
INTO `table` [(field1, field2)]
VALUES ( 'val1', 'val2' )
Or
INSERT
INTO `table` [(field1, field2)]
SELECT 'val1', 'val2'
the selected columns are your value fields.
#comments:
Replace:
http://dev.mysql.com/doc/refman/5.5/en/replace.html
Procedures:
http://dev.mysql.com/doc/refman/5.6/en/create-procedure.html
You are defining the parameters :sname and :uid in your loop. The method execute takes the params and "put them" inside your query before executing this one.
On other words, the query is compiled when you call prepare() and the parameters are applied when you call execute().
Edit:
Ok I didn't understand.
The query includes a "SELECT" part which gives the values to insert. With SELECT you must not write "VALUES", as the documentation says:
INSERT [LOW_PRIORITY | HIGH_PRIORITY] [IGNORE]
[INTO] tbl_name [(col_name,...)]
SELECT ...
[ ON DUPLICATE KEY UPDATE
col_name=expr
[, col_name=expr] ... ]

Why do I get a 500 error? (MySQL php)

<html>
<head>
HTML CODE
<?
$username="xxxxxx";
$password="xxxxxx";
$database="xxxxxx";
mysql_connect(localhost,$username,$password);
$escape = "INSERT INTO monster VALUES ('',$_POST["name"],$_POST["soort"])";
$escape2 = "DELETE monster FROM monster LEFT OUTER JOIN (
SELECT MIN( ID ) AS ID, NAME, PREF
FROM monster
GROUP BY NAME, PREF
) AS KeepRows ON monster.ID = KeepRows.ID
WHERE KeepRows.ID IS NULL";
$query=mysql_real_escape_string($escape);
$query2=mysql_real_escape_string($escape2);
#mysql_select_db($database) or die("MySQL error: Kan inte ansluta till databasen.");
mysql_close();
?>
</body>
</html>
Every time i run this(from another file, containing the name and soort post's) I get an 500 internal server error. First I figured that the queries may be the problem, but they don't even get executed. However, i tried to escape the queries. But still error.
What is wrong with this code? (note: $escape2 is some code i found that removes duplicates in the database. But i don't really know how to format it so that it can be used through php.)
Use something like below...
$query = "INSERT INTO monster VALUES ('', '".$_POST["name"]."', '".$_POST["soort"]."')";
Please do not insert values without escaping.
problem in insert into statement
it should be
$escape = "INSERT INTO monster VALUES ('',".$_POST['name'].",".$_POST['soort'].")";
it is preferable to write colums name while writing insert queries
if column contains string values like VARCHAR or TEXT then use quoted_printable_decode
pass null if column is autoincrement
insert statment
$escape = "INSERT INTO monster (col1, col2, col3) VALUES (NULL,'".$_POST['name']."',".$_POST['soort'].")";
or
$escape = "INSERT INTO monster (col2, col3) VALUES ('".$_POST['name']."',".$_POST['soort'].")";
It looks like you need something like this:
$query = "INSERT INTO monster VALUES ('', '".$_POST["name"]."', '".$_POST["soort"]."')";
Also I would suggest to use prepared statements because it is bad experience to build queries.
First of all I have cool proposition for you. What do you say about some advanced PHP? One step further into great world of safe PHP + MySQL apps?
Introducting to you a PDO. (I know this is not answer to your question but you can consider it). Example of use on your queries:
$db = new PDO('mysql:host=localhost;dbname='.$database, $username, $password);
$insertQuery = $db->prepare('INSERT INTO monster VALUES ("", :name, :soort)');
$deleteQuery = $db->prepare('DELETE monster FROM monster LEFT OUTER JOIN (
SELECT MIN( ID ) AS ID, NAME, PREF
FROM monster
GROUP BY NAME, PREF
) AS KeepRows ON monster.ID = KeepRows.ID
WHERE KeepRows.ID IS NULL');
//to execute query:
$deleteQuery->execute();
//or with params:
$insertQuery->execute(array(
':name' => $_POST['name'],
':soort' => $_POST['soort'],
));
Cool, huh? There is more... Now according to your problem it could be everything (as we don't have error log) but my guess is:
Try to use <?php instead of <?
$escape = "INSERT INTO monster VALUES ('',{$_POST["name"]},{$_POST["soort"]})";
EDIT:
As you provided error log - now I'm sure that problem is in $escape query. It's because you used $escape = " <- and then $_POST["name"] so there was a collision of " (if I can say so).
Try this:
Whenever you insert string type of values in the database using query it has to pass in the quote format. So you just need to change your insert query here.
$query = "INSERT INTO monster VALUES ('', '".$_POST["name"]."', '".$_POST["soort"]."')";
write query like this.
-
Thanks

insert sql statement into mysql database like common string?

I wrote a logger function and it inserts "insert and update queries" to database. altough I apply "mysql_real_escape_string" to the sql stament, I cannot insert it to the database.
any suggestion please?
INSERT INTO kayit (ip, user_id, query) VALUES ('127.0.0.1', 1 UPDATE faal_ekonkod SET bedel = 12000 WHERE id = 1)
In SQL, strings must be quoted. You are also missing a comma. Try this:
INSERT INTO kayit (ip, user_id, query) VALUES ('127.0.0.1', 1, 'UPDATE faal_ekonkod SET bedel = 12000 WHERE id = 1')
i have also problems with this function, then i use the addslashes() function, its not an answer but a solution.
$query = sprintf("SELECT * FROM users WHERE user='%s' AND password='%s'",
mysql_real_escape_string($user),
mysql_real_escape_string($password));

Categories