Query running in phpmyadmin but not in codeigniter model - php

I am running the following query :
SELECT #newNo := MAX( category_code ) FROM category_master;
INSERT INTO category_master VALUES (#newNo +1, 'Test')
The query runs flawlessly in phpmyadmin but it shows a database error when run using codeigniter :
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 category_master VALUES(#newNo+1, 'Test')' at line 2
what could be the reason ??
In codeigniter model i use the following code :
$query = 'SELECT #newNo := MAX(category_code) FROM category_master;
INSERT INTO category_master VALUES(#newNo+1,
\''.$category_name.'\')';
$result = $this -> db -> query($query);

You cannot run two queries at once. Seperate them:
$query = 'SELECT #newNo := MAX(category_code) FROM category_master';
$result = $this->db->query($query);
$query = 'INSERT INTO category_master VALUES(#newNo+1, \''.$category_name.'\')';
$result = $this->db->query($query);
EDIT:
On your second query it is recommended to use query bindings:
$query = 'INSERT INTO category_master VALUES(#newNo+1, ?)';
$result = $this->db->query($query, $category_name);

Make sure the query does not contains any special characters. The browser will convert the special characters, so the query is running in phpmyadmin.
To know the special characters, echo the query and copy it and paste in an editor like dreamweaver, it will show you the special characters. Hope this helps.

Related

Problem calling parameterized MariaDB SP with LIMIT using PHP

I have been stumped with this and cannot find a working example or tutorial anywhere.
Given the following stored procedure:
SQL
delimiter $$
CREATE PROCECURE sp1(IN 'myoffset' INT, IN 'myrows'
INT)
begin
select * from t1
limit 'myoffset', 'myrows'
END$$
delimiter
I am trying to call it from PHP like so:
... establish $conn, then
PHP
// ver1:
$sql = ( "SET #p0 = $tmp1;" . " SET #p1 = $tmp2;" . "
CALL `sp1`(#p0, #p1);" );
//OR
//ver2
$sql = "SET #p0 = `$tmp1`; SET #p1 = `$tmp2`; CALL
`sp1`(#p0, #p1);";
$result = mysqli_query($conn, $sql);
Neither one works. MariaDB complains that
"Error description: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'SET #p1 = 25; CALL sp1(#p0, #p1)' at line 2"
Any help would be much appreciated!
What is in $tmp1?
If it is a number, then the first one should work, but the second one does not make sense because it becomes
SET #p0 = `1234`;
I assume there is not a column or table named 1234? Keep in mind that backtics are for columns, tables, and database names.
If $tmp is the string "a string", then you get
SET #p0 = a string; -- strings need to be quoted here
or
SET #p0 = `a string`; -- again that is treated as a column (etc) name.
After that, you have another problem: Do not tack multiple statements together (separated by ;); run them separately.
Finally, there is no need for #p0, etc:
$sql = "CALL `sp1`('$tmp1', '$tmp2')";
is sufficient.
Well, not quite. If the values for $tmps came from the outside world, see the dreaded "SQL Injection" problem.
Oh, and what if
$tmp1 = "Don't do this";
Then you get
$sql = "CALL `sp1`('Don't do this', '$tmp2')";
Look at the single quotes. There are 3 of them. How will this be parsed?

sql query with select before insert

I am currently working on the following sql code which should insert a new data set only if it doesn't exist so far. The sql code works fine when being executed in phpmyadmin. If I execute the code within php I get the error (see below).
The sql code is the following:
INSERT INTO `historiclist` (`id`, `date`, `name`, `idnumber`, `prop1`, `prop2`, `prop3`, `difflimit1`, `difflimit2`)
SELECT * FROM (SELECT
0 as `id`,
1515529465 as `date`,
'johndoe' as `name`,
'381' as `idnumber`,
105 as `prop1`,
240 as `prop2`,
60 as `prop3`,
'-10' as `difflimit1`,
'-10' as `difflimit2`
) AS tmp
WHERE NOT EXISTS (
SELECT `id` FROM historiclist
WHERE `date` = 1515529465
AND `name` = 'johndoe'
AND `idnumber` = '381'
) LIMIT 1;
The mysql error I receive is:
Invalid query: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'INSERT INTO historiclist (id, date, name, idnumber, prop1, `prop' at line 21
The mysterious situation is also that prop2 is not fully displayed. So it cuts the 2 in the end of the name as well as e. g. prop3.
What am I missing?
//Edit I was missing something else as well ... here my php code:
$sql1return = sqlQUERY($connection, $sql1);
$message = 'Invalid query: ' . mysql_error() . "\n";
function sqlQUERY($connection, $sqlinput){
$return = #mysql_query($sqlinput, $connection);
return $return;
}
The database connection works just fine in any other place (I know it is a bit outdated however).

PHP: Error on Update statement with subquery

I have a page that updates the data of a specific user. The user has position, which is a foreign key. The query update (below) works fine without the position, but with the position I get the following error.
Query :
$queryUpdate = "UPDATE visitorsystem.employee SET idNumber = '$idNumber', name = '$name',
surname = '$surname',
position = 'SELECT positionid FROM visitorsystem.position WHERE positionName LIKE '%$position%'',
email = '$email'
WHERE employeeid = '$empId'";
$resultUpdate = mysqli_query($connection,$queryUpdate)
or die("Error in query: ". mysqli_error($connection));
Error in query: 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 'SELECT positionid FROM visitorsystem.position WHERE
positionName LIKE '%Informat' at line 3
I have tried to work my way around by using inner join as I have seen some solutions given here on stack but nothing has worked. Any Suggestions ?
Subqueries go within regular parens, not quotes, so in a general sense:
SELECT x FROM y WHERE z IN (SELECT z FROM a)
Single and double quotes (by default) are only for string values.

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');

Help resolving SQL error that occurs in code but not in SQL workbench

I run this command in SQL Workbench and it returns my desired results, but it return a syntax error in the browser...
$sql = "SELECT
SUBSTRING(`last_name`, 1, 1) AS alpha,
SUBSTRING(`middle_name`, 1, 1) AS subMiddleName,
`idClients`,
`type`,
`first_name`,
`middle_name`,
`last_name`,
`address`,
`primary_number`,
`secondary_number`,
`home_number`,
`office_number`,
`cell_number`,
`fax_number`,
`ext_number`,
`other_number`,
`comments`
FROM `clients`
WHERE `user_id` = 2
AND `is_sub` = 0
AND `prospect` = 1
ORDER BY `last_name`";
Also user_id, is_sub, and prospect are of the INT data type if anyone wants to know. I tried to treat them as strings in the query, but that still didn't help.
this is the error i get
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 'AND prospect = 1 AND type = 'Buyer'' at line 1
You're not showing us the same query, or the relevant PHP code, as nowhere does the above query use the string 'Buyer'.
That said, you may need to escape the column name type with backticks:
AND `prospect` = 1 AND `type` = 'Buyer'

Categories