I'm running the following query using MySQL workbench and I'm getting the exact results from the database :
SELECT *
FROM ODB_RG
WHERE fullAddressV1 = 'רמת גן חרושת 1'
OR fullAddressV2 = 'רמת גן חרושת 1'
OR fullAddressV3 = 'רמת גן חרושת 1'
OR fullAddressV4 = 'רמת גן חרושת 1'
On the other hand, running the following php code does, that actually generated an equivalent query to the one mentioned above,does not return any record :
$fullAddress = "1 רמת גן חרושת";
$stmt = $con->prepare("SELECT * FROM ODB_RG WHERE fullAddressV1 = :address1 "
. "OR fullAddressV2 = :address2 OR fullAddressV3 = :address3 "
. "OR fullAddressV4 = :address4");
$stmt->bindParam(':address1',$fullAddress);
$stmt->bindParam(':address2',$fullAddress);
$stmt->bindParam(':address3',$fullAddress);
$stmt->bindParam(':address4',$fullAddress);
$status = $stmt->execute();
The only reasonable cause that might lead to the difference between the solution is the Hebrew string that is passed as a parameter.
Any of you have any idea what should be done in order to fix it ?
Thanks in advance !
EDIT :
This is the collation i'm using for the relevant table:
engine=MyISAM charset=UTF8 COLLATE = utf8_general_ci;
This is what I meant by error checking:
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$fullAddress = "1 רמת גן חרושת";
$stmt = $con->prepare("SELECT * FROM ODB_RG WHERE fullAddressV1 = :address1 "
. "OR fullAddressV2 = :address2 OR fullAddressV3 = :address3 "
. "OR fullAddressV4 = :address4");
if (!$stmt) {
echo "\nPDO::errorInfo():\n";
print_r($con->errorInfo());
die();
}
$stmt->bindParam(':address1',$fullAddress);
$stmt->bindParam(':address2',$fullAddress);
$stmt->bindParam(':address3',$fullAddress);
$stmt->bindParam(':address4',$fullAddress);
$status = $stmt->execute();
if (!$status ) {
echo "\nPDO::errorInfo():\n";
print_r($con->errorInfo());
die();
}
if($row = $stmt->fetch()){
var_dump($row);
}else{
echo 'no row found';
}
I know its ulgy, sometime called defensive programming, but it lets you know whats going on.
Related
Using PHP + Oracle 12c
I'm trying to insert many rows but i got an error "oci_execute(): ORA-00001: unique constraint (S95417.FIRMA__IDX)" This is strange for me because in loop i'm getting last id and incrementing it.
I used debbuger and (On INSERT) i'm getting last id but incrementing is not working.
Could you tell me why?
Data which i added
INSERT INTO FIRMA VALUES(18,MICROSOFT,2432213715,2020-03-26,23)
INSERT INTO FIRMA VALUES(19,APPLE,7512202082,2020-03-26,42)
SELECT NVL(MAX(firmaid),0)+1
I made code very similar using that for other tables and it's working fine.
My code:
$ile_razy = $_POST['liczba_powtorzen'];
$firma = "SELECT * FROM FIRMA";
$c = oci_connect($username, $password, $database);
if (!$c) {
$m = oci_error();
trigger_error('Could not connect to database: '. $m['message'], E_USER_ERROR);
}
$file = 'firma.txt';
$current = file_get_contents($file);
for ($i = 1; $i <= $ile_razy; $i++) {
$nazwa = randCompanyName();
$nip = randNIP();
$dataWspolpracy = date("Y-m-d");
$ids_array = array();
$adresid = "SELECT adresid FROM ADRES";
$stmtt = oci_parse($c, $adresid);
$result = oci_execute($stmtt);
while($row = oci_fetch_array($stmtt))
{
$ids_array[] = $row['ADRESID'];
}
$randIndex = array_rand($ids_array);
$adresId = $ids_array[$randIndex];
// HERE IS PROBLEM
$firmaQuery = "INSERT INTO FIRMA SELECT NVL(MAX(firmaid),0) + 1,'$nazwa', '$nip', '$dataWspolpracy', '$adresId' from FIRMA";
$ex = oci_parse($c,$firmaQuery);
// "zapytanie" is working fine
$zapytanie = "SELECT NVL(MAX(firmaid),0)+1 from FIRMA";
$stmt = oci_parse($c, $zapytanie);
$results = oci_execute($stmt);
while($row = oci_fetch_assoc($stmt)){
$rowid = $row["NVL(MAX(FIRMAID),0)+1"];
}
$firmaIdForTxt = "INSERT INTO FIRMA VALUES(".$rowid.",".$nazwa.",".$nip.",".$dataWspolpracy.",".$adresId.")";
echo $rowid. ", ";
oci_execute($ex);
$current .= $i. ".".$firmaIdForTxt."\n";
file_put_contents($file, $current);
}
In my db
I have changed that but error still appears
You can make your FIRMAID an identity column : Oracle will handle the increment internally, and it is much more safer for your data.
Then you can insert your data with this query :
INSERT INTO FIRMA(nazwa, nip, datawspolpracy, adresid) VALUES('$nazwa', '$nip', '$dataWspolpracy', '$adresId')
NOTE : this is for a quick answer, for a safer solution and avoid SQL injections, use prepared statements : PHP oci examples (See example #2)
I want to search a certain string in all the columns of different tables, so I am looping the query through every column name. but if i give it as dynamic value it does not seem to work.
what is wrong?
<?php
$search = $_POST['search'];
$columns = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'feedback'";
$columns_result = $conn->query($columns);
$columns_array = array();
if (!$columns_result) {
echo $conn->error;
} else {
while ($row = $columns_result->fetch_assoc()) {
//var_dump($row);
//echo $row['COLUMN_NAME']."</br>";
array_push($columns_array, $row['COLUMN_NAME']);
}
}
var_dump($columns_array);
$row_result = array();
for ($i = 0; $i < count($columns_array); $i++) {
echo $columns_array[$i] . "</br>";
$name = "name";
// $sql = 'SELECT * FROM feedback WHERE "'.$search.'" in ("'.$columns_array[$i].'")';
$sql = 'SELECT * FROM feedback WHERE ' . $name . ' like "' . $search . '"';
$result = $conn->query($sql);
if (!$result) {
echo "hi";
echo $conn->error;
} else {
foreach ($result as $row) {
array_push($row_result, $row);
echo "hey";
}
}
}
var_dump($row_result);
I am getting the column names of the table and looping through them because I have so many other tables which I need to search that given string. I don't know if it is optimal I did not have any other solution in my mind. If someone can tell a good way I will try that.
It looks to me that you want to generate a where clause that looks at any available nvarchar column of your table for a possible match. Maybe something like the following is helpful to you?
I wrote the following with SQL-Server in mind since at the beginning the question wasn't clearly tagged as MySql. However, it turns out that with a few minor changes the query work for MySql too (nvarchar needs to become varchar):
$search='%';$tbl='feedback';
if (isset($_POST['search'])) $search = $_POST['search'];
$columns = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = '$tbl' AND DATA_TYPE ='nvarchar'";
$columns_result = $conn->query($columns);
$columns_array = array();
if(!$columns_result) print_r($conn->errorInfo());
else while ($row = $columns_result->fetch(PDO::FETCH_ASSOC))
array_push($columns_array, "$row[COLUMN_NAME] LIKE ?");
$where = join("\n OR ",$columns_array);
$sth = $conn->prepare("SELECT * FROM $tbl WHERE $where");
for ($i=count($columns_array); $i;$i--) $sth->bindParam($i, $search);
$sth->execute();
$result = $sth->fetchAll(PDO::FETCH_ASSOC);
print_r($result);
The above is a revised version using prepared statements. I have now tested this latest version using PHP 7.2.12 and SQL-Server. It turned out that I had to rewrite my parameter binding part. Matching so many columns is not a very elegant way of doing queries anyway. But it has been a nice exercise.
It looks like you are using mysqli, so I wanted to give another way of doing it via mysqli.
It does more or less the same as cars10m solution.
$search = $_POST['search'];
$columns = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'feedback'";
$columns_result = $conn->query($columns)->fetch_all(MYSQLI_ASSOC);
// Here dynamically prepare WHERE with all the columns joined with OR
$sql = 'SELECT * FROM feedback WHERE ';
$arrayOfWHERE = [];
foreach($columns_result as $col){
$arrayOfWHERE[] = '`'.$col['COLUMN_NAME'].'` LIKE ?';
}
$sql .= implode(' OR ', $arrayOfWHERE);
// prepare/bind/execute
$stmt = $conn->prepare($sql);
$stmt->bind_param(str_repeat("s", count($arrayOfWHERE)), ...array_fill(0, count($arrayOfWHERE), $search));
$stmt->execute();
$result = $stmt->get_result();
$row_result = $result->fetch_all(MYSQLI_ASSOC);
var_dump($row_result);
Of course this will search for this value in every column of the table. It doesn't consider data type. And as always I have to point out the using PDO is better than mysqli. If you can switch to PDO.
I have this code:
<?php
//MYSQL
$dbserver="..."; //adresa MySQL
$dblogin="..."; //jméno uživatele MySQL
$dbheslo="..."; //heslo MySQL
$dbnazev="..."; //název databáze MySQL
$mysqli = new mysqli($dbserver, $dblogin, $dbheslo, $dbnazev);
if ($mysqli->connect_error) {
die('Nepodařilo se připojit k MySQL serveru (' . $mysqli->connect_errno . ') '
. $mysqli->connect_error);
}
$mysqli->query("SET NAMES 'utf8'"); // nastavíme kódování MySQL
while($row = $mysqli->query("SELECT * FROM `importovat_fyz` WHERE `tempid` IS NOT NULL")->fetch_assoc()){
$tempid = $row['tempid'];
$jmeno = $row['jmeno'];
$prijmeni = $row['prijmeni'];
$email = $row['email'];
$bydliste = $row['bydliste'];
$souhlas = "on";
$aktuality = "on";
$timestamp = time();
$hash = md5("77c0a83besxxxcg1a190ab90d".time().$tempid.rand(10000000, 99999999));
$poznamky = "import19052018";
$vloz ="INSERT into `potvrzenotest` set jmeno='".$jmeno."', prijmeni='".$prijmeni."', bydliste='".$bydliste."', email='".$email."', souhlas='".$souhlas."', aktuality='".$aktuality."', timestamp='".$timestamp."', hash='".$hash."', poznamky='".$poznamky."';";
$result=$mysqli->query($vloz);
$cas = date('H:i');
echo '['.$cas.'] ID '.$tempid.' imported.', PHP_EOL;
}
mysqli_close($mysqli); .
?>
I have one table with some data and I have to copy it to another table with some additional data (like hash etc.).
When I run the code above, I got this:
[17:17] ID 1 imported.
[17:17] ID 1 imported.
[17:17] ID 1 imported.
[17:17] ID 1 imported.
[17:17] ID 1 imported.
So, only 1 row is being copied.
Could you please help me, where is the problem?
while($row = $mysqli->query("SELECT * FROM `importovat_fyz` WHERE `tempid` IS NOT NULL")->fetch_assoc()){ ... }
This loop will never end. And it will fetch the first row again and again.
You should execute the query outside the loop:
$selectResult = $mysqli->query("SELECT * FROM `importovat_fyz` WHERE `tempid` IS NOT NULL");
while ($row = $selectResult->fetch_assoc()) { ... }
As a side note: Consider to use a prepared statement for your INSERT statement in the loop. This will prevent SQL syntax errors if some of the values may contail special characters like '. If you run them in one transaction, you might even improve the performance.
I have the following Postgres query:
$sql_afect = "SELECT SUM(r.num_tiempo_afectado) FROM ctl_reportes r
WHERE 1 = 1 AND r.num_tiempo_afectado <> '00:00:00' " . (!empty($idu_clase) ?
"AND r.idu_clase = $idu_clase" : "") . " " . (!empty($idu_prioridad) ?
"AND r.idu_prioridad = $idu_prioridad" : "");
I'm working on a PHP program, and this query sums a bunch of some specific hours, which are in this format on a table (ctl_reportes): '00:00:00'.
How could I save this query's result into a PHP variable in order to echo the result on the screen?
See the code below to execute query in PHP using PDO
<?php
$user = 'root';
$pass = 'toor';
$dbh = new PDO('mysql:host=localhost;dbname=db_scrapper', $user, $pass);
$query = "SELECT SUM(r.num_tiempo_afectado) FROM ctl_reportes r
WHERE 1 = 1 AND r.num_tiempo_afectado <> '00:00:00' " . (!empty($idu_clase) ?
"AND r.idu_clase = $idu_clase" : "") . " " . (!empty($idu_prioridad) ?
"AND r.idu_prioridad = $idu_prioridad" : "");
$sth = $dbh->prepare($query);
$sth->execute();
/* Exercise PDOStatement::fetch styles */
print("PDO::FETCH_ASSOC: ");
print("Return next row as an array indexed by column name\n");
$result = $sth->fetch(PDO::FETCH_ASSOC);
var_dump($result);
Here after query is executed, the result is stored in $result. I assume you have some
basic knowledge to use PHP. Please refer to PHP PDO to have more insights into it.
Please let us know if this works for you or not. And I'll update my answer accordingly.
I've got this code:
$query = 'SELECT * FROM users WHERE username = "' . $user . '" AND password = MD5("' . $pass . '") LIMIT 1';
echo $query;
$result = $mysqli->query($query);
echo "<br>Here: " . $result->num_rows;
Using the output from $query I put it into phpmyadmin and it returns 1 row but when trying to get the number of rows using num_rows it doesn't return anything at all - not even 0;
Any ideas?
http://ru2.php.net/manual/en/mysqli.query.php
Returns FALSE on failure.
Have you established a connectection to your DB?
Looks like the SQL query is messed up. As far as I know there is no MD5 function built into MySQL nor the SQL standard. Therefore if it does exist then it is probably proprietary to the particular DB.
That said you can use PHP to check it. Try this to see what is going on.
$encrypted_pass = md5($pass);
$query = "SELECT * FROM users WHERE username = '$user' AND password = '$encrypted_pass' LIMIT 1";
echo $query;
$result = $mysqli->query($query);
if ($result !== FALSE) {
echo "<br>Here: " . $result->num_rows;
}
else {
echo "Something is broken.";
}
Ref:
http://us2.php.net/manual/en/mysqli-result.num-rows.php