I connect to MSSQL server and my query does not return any results - if I use the echo $sql; statement all that I have returned is Array so I can't even check for a syntax issue!
How should this syntax be ammended so that all 3 where statements execute as they should?
<select name="employee" id="employee"></select>
$option = array();
$option['driver'] = 'mssql';
$option['host'] = 'IP ADDRESS';
$option['user'] = 'USER';
$option['password'] = 'Pass';
$option['database'] = 'DB';
$option['prefix'] = '';
$db = JDatabase::getInstance($option);
$query = $db->getQuery(true);
$query->select($db->quotename(array('Red,Blue,Green')));
$query->from($db->quoteName('EMS'));
$datefield_name = $db->quoteName('TermDate');
$employee_name = $db->quoteName('employee');
$query->where("$datefield_name >= " . $db->quote($d1), 'AND');
$query->where("$datefield_name <= " . $db->quote($d2));
if ($employeename != 'All') {
$query->where("$employee_name <= " . $db->quote($employee));
}
$db->setQuery($query);
echo $query;
$query = $db->loadObjectList();
I'm no expert at MSSQL, but my first impression is that in your where-statements you should not include your variables inside the quotes. So instead of
$query->where("$datefield_name <= " . $db->quote($d2));
try
$query->where($datefield_name . " <= " . $db->quote($d2));
Related
I am passing value from android using POST and run the query in SQL DB using PHP. I am always getting
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 '' at line 1.
The code is working fine if i pass the values directly insted $_POST[].
I've gone through SO but no questions solved my problem. I tried with mysql_real_escape_string($searchTermBits) also but that doesn't worked.
PHP:
<?php
$username = "xxxx";
$password = "xxxx";
$host = "xxxx";
$database = "xxxx";
$server = mysql_connect($host, $username, $password);
$connection = mysql_select_db($database, $server);
$search = $_POST["deskey"];
$search = explode(" ", $search);
$commonwords = "a,an,and,I,it,is,do,does,for,from,go,how,the,etc,in,on,are";
$commonwords = explode(",", $commonwords);
foreach ($search as $value)
{
if (!in_array($value, $commonwords))
{
$query[] = $value;
}
}
$query = implode(" ", $query);
$searchTerms = explode(" ", $query);
$searchTermBits = array();
foreach ($searchTerms as $term)
{
$term = trim($term);
if (!empty($term))
{
$searchTermBits[] = "description LIKE '%$term%'";
}
}
$myquery = "SELECT * FROM `logins` WHERE " . implode(' OR ', mysql_real_escape_string($searchTermBits)) . "";
$query = mysql_query($myquery);
if (!$query)
{
echo mysql_error();
die;
}
$data = array();
for ($x = 0; $x < mysql_num_rows($query); $x++)
{
$data[] = mysql_fetch_assoc($query);
}
echo json_encode($data);
mysql_close($server);
?>
What changes can i make this code to work with $_POST[].
This first part work very well in other script of mine. But in this example the script simply skip this part and goes to the end and execute the last query..
I don't know what I'm doing wrong because I do it exactly same yet it doesn't work. This is full script.
for ($i = 1; $i <= $numofservers; $i++)
{
if($servers[$i][1] == $server)
{
$srv = $i;
$connect = mysql_connect($servers[$srv][3], $servers[$srv][4], $servers[$srv][5]) or die('Could not connect: ' . mysql_error());
mysql_select_db($servers[$srv][6]);
}
}
$sql = mysql_query("SELECT * FROM db_users WHERE username = '".$nick."'") or die('Nick na serveru Neexistuje!' . mysql_error());
$sql = mysql_fetch_array($sql);
$balance = $sql['donate_balance'];
$steamid = $sql['steam_id'];
$balance = $balance + $price_sms;
$money = mysql_query("UPDATE db_users SET `donate_balance`='". $balance ."' WHERE steam_id = '".$steam_id."'");
<?php
$db_site_name = ''; // db connection name
$db_site_password = '';
$db_site_username = 'root'; // username of connection
$db_site_ip = '127.0.0.1:3306';
$link = mysql_connect($db_site_ip, $db_site_username, $db_site_password) or die('Could not connect: ' . mysql_error());
mysql_select_db($db_site_name) or die('Not connected<br>');
$serversquery = mysql_query("SELECT * FROM db_servers ORDER BY id");
$numofservers = 0;
while ($servers_array = mysql_fetch_array($serversquery))
{
$numofservers++;
$servers[$numofservers] = array(
$servers_array['id'],
$servers_array['name'],
$servers_array['about'],
$servers_array['server_ip'],
$servers_array['server_username'],
$servers_array['server_password'],
$servers_array['server_name'],
$servers_array['server_admin_rank'],
$servers_array['donate_factor']
);
}
if (isset($_GET["request"])){
$request_sms = ($_GET["request"]);
$status = ($_GET["status"]);
$message = ($_GET["message"]);
$request = mysql_query("UPDATE `sms_confirm` SET `status` = '".$status."' WHERE `sms_id` = '".$request_sms."'");
$findid = mysql_query("SELECT * FROM `sms_confirm` WHERE `sms_id` = '".$request_sms."' LIMIT 1") or die(mysql_error()); ;
$query = mysql_fetch_array($findid);
if ($query['status'] == 'DELIVERED' AND $query['added'] == 'false'){
$price_sms = $query['cena'];
$nick = $query['nick'];
$server = $query['server'];
for ($i = 1; $i <= $numofservers; $i++)
{
if($servers[$i][1] == $server)
{
$srv = $i;
$connect = mysql_connect($servers[$srv][3], $servers[$srv][4], $servers[$srv][5]) or die('Could not connect: ' . mysql_error());
mysql_select_db($servers[$srv][6]);
}
}
$sql = mysql_query("SELECT * FROM db_users WHERE username = '".$nick."'") or die('Nick na serveru Neexistuje!' . mysql_error());
$sql = mysql_fetch_array($sql);
$balance = $sql['donate_balance'];
$steamid = $sql['steam_id'];
$balance = $balance + $price_sms;
$money = mysql_query("UPDATE db_users SET `donate_balance`='". $balance ."' WHERE steam_id = '".$steam_id."'");
$link = mysql_connect($db_site_ip, $db_site_username, $db_site_password) or die('Could not connect: ' . mysql_error());
mysql_select_db($db_site_name) or die('Not connected<br>');
//this executes fine
$request = mysql_query("UPDATE `sms_confirm` SET `added` = 'true' WHERE `sms_id` = '".$request_sms."'");
}
}
//Header("HTTP/1.1 204 NO_CONTENT");
//Header("Content-type: text/plain");
?>
First of all, don't use mysql_* functions. It's deprecated and will be removed.
And if you want to use more than one database connection, you have to pass link to it to every function that will contact with your databases.
Eg, check here (second parameter).
Sample code
$link = mysql_connect($db_site_ip, $db_site_username, $db_site_password);
mysql_select_db($db_site_name, $link);
mysql_query($query, $link);
The problem I'm having is making preg_match work correctly for my array returned from my form.
<input type="checkbox" name="receiver-check[]" class="checkbox-id" value="Username 1 (123)">
<input type="checkbox" name="receiver-check[]" class="checkbox-id" value="Username 2 (456)">
<input type="checkbox" name="receiver-check[]" class="checkbox-id" value="Username 3 (789)">
So I wish to use preg_match on the values received through my form.
This is how I use it.
$msg_receivers = !empty($_POST['receiver-check']) && is_array($_POST['receiver-check']) ? $_POST['receiver-check'] : array();
$receiverIds = array();
foreach($msg_receivers as $receiver) {
$receiverIds[] = preg_replace('/\((\d+)\)$/', "$1", $receiver);
}
$number_of_receivers = count($receiverIds);
$while_count = 0;
while($number_of_receivers >= ($while_count + 1)){
$sql = <<< EOF
INSERT INTO private_messages (
message_subject,
message_content,
message_deliver,
message_receive,
message_status,
message_datetime,
message_to_stab
)VALUES
(?,?,?,?,'2',?,?);
EOF;
$stmt = $mysqli->prepare($sql) or die ("Feil i database<br>" . $sql . "<br><b>Feilmelding:</b> " . $mysqli->error);
$stmt->bind_param("ssiiii",$message_subject,$message_content, $_SESSION['user_id'],$receiverIds[$while_count],$message_datetime,$message_to_stab);
$stmt->execute() or die("noe gikk galt");
$msg_num_rows = $stmt->num_rows;
if($msg_num_rows = 0){
$msg = "Feilmelding: Klarte ikke å sende meldingen.";
}
else{
$msg = "Meldingen har blitt sendt.";
}
$stmt->free_result();
$stmt->close();
$while_count ++;
}
Then I use $msg_receiver_query to asign a value in the query INSIDE the while loop.
What I currently receive in my database is 0 and 1. Nothing else. What would the correct preg_match be for me to output JUST the numbers inside the paranthesis? and is there a more effective solution to this problem of mine?
It looks like you don't want to match, you want to extract just a portion of each $_POST['receiver-check'] value - so preg_replace() would be the right function to use.
$msg_receivers = !empty($_POST['receiver-check']) && is_array($_POST['receiver-check'])
? $_POST['receiver-check'] : array();
$receiverIds = array();
foreach($msg_receivers as $receiver) {
$receiverIds[] = preg_replace('/^.*\((\d+)\)$/', "$1", $reciever);
}
That should give you an array of reciever ids ($receiverIds) like:
array(
[0] => 123,
[1] => 456,
[2] => 789
);
You could do something like this.
This way you can insert it in to your DB. but you will query your Db 3 times to insert 3 records.
<?php
//use your connection Data
$user = "root";
$pass = "***";
$host = "localhost";
$dbdb = "TestDataBase";
$connect = mysqli_connect($host, $user, $pass, $dbdb);
if(!$connect)
{
trigger_error('Error connection to database: '.mysqli_connect_error());
}
//check if receiver-check is set or not
if(isset($_POST['receiver-check'])){
$msg_receivers = $_POST['receiver-check'];
// iterate through $msg_receivers
foreach($msg_receivers AS $value){
preg_match_all("/([0-9]{3})/", $value, $msg_receiver_query);
//Query, just change the table name and columns to what ever you need.
$sql = "INSERT INTO `table` (`column1`) VALUES ('" .$msg_receiver_query[0][0] . "')";
if (mysqli_query($connect, $sql)) {
echo 'Record(s) created successfully<br>';
} else {
echo $sql . '"<br>"' . mysqli_error($connect);
}
}
}else{
echo "nothing is set";
}
?>
Maybe a ittle to advanced but you can do this in one query aswell.
<?php
//use your connection Data
$user = "root";
$pass = "***";
$host = "localhost";
$dbdb = "TestDataBase";
$connect = mysqli_connect($host, $user, $pass, $dbdb);
if(!$connect)
{
trigger_error('Error connection to database: '.mysqli_connect_error());
}
//check if receiver-check is set or not
if(isset($_POST['receiver-check'])){
$msg_receivers = $_POST['receiver-check'];
$inputArray = '';
// iterate through $msg_receivers
foreach($msg_receivers AS $value){
preg_match_all("/([0-9]{3})/", $value, $msg_receiver_query);
//insert all output in to an array
$inputArray [] = "('" . $msg_receiver_query[0][0] . "')";
}
//Insert all outputs in 1 query
$sql = "INSERT INTO `testtable` (`column1`) VALUES " . implode(",",$inputArray) . "";
if (mysqli_query($connect, $sql)) {
echo 'Record(s) created successfully<br>';
} else {
echo $sql . '"<br>"' . mysqli_error($connect);
}
}else{
echo "nothing is set";
}
?>
I have this code for a multiple insert query (I have to transfer data from db to another and makes some update, so I wanna use a code that could do all this automatically)
$query = "select * from pubblicate order by idPubblicate asc";
$dbh = newPdo2();
$dbh->exec("set names utf8");
$sth = $dbh->prepare($query);
$sth->execute();
$count = 0;
$query2 = "insert into published_offer
(codice_onshop,nome,inbreve,anteprima,
galleria1,galleria2,galleria3,galleria4,prezzo,
tp_prezzo,bonus_usabile,proposta,condizioni,
prenotare,categoria,description,keywords,
valido_da,valido_a) ";
while($offerta = $sth->fetch(PDO::FETCH_ASSOC)) {
$array[$count]['id'] = $offerta['idPubblicate'];
$array[$count]['co'] = $offerta['codiceOfferta'];
$array[$count]['no'] = $offerta['nomeOfferta'];
$array[$count]['ib'] = $offerta['inBreve'];
$array[$count]['ke'] = $offerta['keywords'];
$array[$count]['de'] = $offerta['description'];
$array[$count]['pr'] = $pfferta['prezzo'];
$array[$count]['pe'] = $offerta['persona'];
$array[$count]['da'] = $offerta['daTimer'];
$array[$count]['a'] = $offerta['aTimer'];
$array[$count]['an'] = $offerta['anteprima'];
$array[$count]['g1'] = $offerta['galleria1'];
$array[$count]['g2'] = $offerta['galleria2'];
$array[$count]['g3'] = $offerta['galleria3'];
$array[$count]['g4'] = $offerta['galleria4'];
$array[$count]['pro'] = $offerta['proposta'];
$array[$count]['con'] = $offerta['condizioni'];
$array[$count]['pre'] = $offerta['prenotare'];
$array[$count]['bo'] = 999;
if($offerta['italia']=="Sì") $array[$count]['ca'] = "ita";
else if($offerta['europa']=="Sì") $array[$count]['ca'] = "eur";
else if($offerta['mondo']=="Sì") $array[$count]['ca'] = "mon";
$count++;
}
$query2 .= "values (:co,:no,:ib,:an,:g1,:g2,
:g3,:g4,:pr,:pe,:bo,:pro,:con,
:pre,:ca,:de,:ke,:da,:a)";
$dbh = newPdo();
$dbh->exec("set names utf8");
$sth = $dbh->prepare($query2);
$i=0;
echo $array[0]['no'] . " " . count($array) . " " . $array[125]['no'] . "<br>" . $query2 . "<br>";
while($i<count($array)) {
$sth->bindParam(":co", $array[$i]['co']);
$sth->bindParam(":no", $array[$i]['no']);
$sth->bindParam(":ib", $array[$i]['ib']);
$sth->bindParam(":an", $array[$i]['an']);
$sth->bindParam(":g1", $array[$i]['g1']);
$sth->bindParam(":g2", $array[$i]['g2']);
$sth->bindParam(":g3", $array[$i]['g3']);
$sth->bindParam(":g4", $array[$i]['g4']);
$sth->bindParam(":pr", $array[$i]['pr']);
$sth->bindParam(":pe", $array[$i]['pe']);
$sth->bindParam(":bo", $array[$i]['bo']);
$sth->bindParam(":pro",$array[$i]['pro']);
$sth->bindParam(":con",$array[$i]['con']);
$sth->bindParam(":pre",$array[$i]['pre']);
$sth->bindParam(":ca", $array[$i]['ca']);
$sth->bindParam(":de", $array[$i]['de']);
$sth->bindParam(":ke", $array[$i]['ke']);
$sth->bindParam(":da", $array[$i]['da']);
$sth->bindParam(":a", $array[$i]['a'] );
$sth->execute();
$i++;
}
But this code doesn't work. I've also tried to use try-catch(PDOException) for $sth->execute() but it doesn't show me anything.
Why?
Who says "this question is a duplicated" doesn't read really the question. Infact the error was a wrong character: $array[$count]['pr'] = $pfferta['prezzo'] would be been $array[$count]['pr'] = $offerta['prezzo']so I couldn't find an answer in another question.
Try adding some simple checks that things actually worked like this
$res = $sth->execute();
if ( ! $res ) {
echo sprintf('ERROR: %d - %s', $sth->errorCode(), $sth->errorInfo() );
}
I have a function in PHP and I would like to export an array from my MYSQL Database and then use the rows in a loop to do some stuff with them.
$DB_Server = "XXX.XXX.XXX.XXX";
$DB_Username = "XXXX";
$DB_Password = "XXXXX";
$DB_Database = "XXXXX";
$conn = new mysqli($DB_Server, $DB_Username, $DB_Password, $DB_Database);
$query = "Select Name, Wert from test.DBPBX";
function show(array $options) {
global $showresult, $master, $conn, $query;
$result = mysqli_query($conn, $query);
while ($row = mysqli_fetch_assoc($result)) {
$cnlongname = $row["Name"];
$usercontent = $row["Wert"];
$cn = $cnlongname;
$options['config']->value = 1;
$config = $options["config"]->value;
$show = new SimpleXMLElement("<show/>");
$user = $show->addChild("user");
$user->addAttribute("cn", $cn);
if ($config)
$user->addAttribute("config", "true");
print "cmd: " . htmlspecialchars($show->asXML()) . "\n";
$showresult = $master->Admin($show->asXML());
print "result: " . htmlspecialchars($showresult) . "\n";
$mod = "text=".$usercontent;
$modify = new SimpleXMLElement("$showresult");
$user = $modify->user;
$path = explode("/device/hw/", $mod);
$srch = $user;
$nsegments = count($path);
$i = 1;
foreach ($path as $p) {
if ($i == $nsegments) {
// last part, the modification
list($attr, $value) = explode("=", $p);
$srch[$attr] = $value;
} else {
$srch = $srch->$p;
}
$i++;
}
$modify = new SimpleXMLElement("<modify>" . $user->asXML() . "</modify>");
print "cmd: " . htmlspecialchars($cmd = $modify->asXML()) . "\n";
// do it
$result = $master->Admin($cmd);
print "result: " . htmlspecialchars($result);
}
}
For $cn I would like to use $cnlongname (or $row["Name"]). And for $mod I would like to use $usercontent (or $row["Wert"]). However when I would like to use it I get an error after the first loop:
Warning: mysqli_fetch_assoc() expects parameter 1 to be
mysqli_result, string given in /sample.php on
line 175
Line 175 is:
while ($row = mysqli_fetch_assoc($result)) {
Can you please help me?
Inside your while loop you overwrite your result, therefore you lose your mysql result and cannot query it any more.
// do it
$result = $master->Admin($cmd);
Use a different variable there. :)