I have to change an old mysql to PDO, I am working with a code its made by someone else, so I have this following code to change in PDO
The original code is
function liste($a,$b,$c)
{
$queryliste= "SELECT id,nom,prenom
FROM table";
$this->list = Connection_Base($querylistactu);
}
//Connection_Base
function Connection_Base($query)
{
$link = mysql_connect(DATABASESERVER, DATABASEUSER, DATABASEPASSWORD);
$ret = mysql_select_db(DATABASEDB, $link);
if (!$ret)
{
die("Echec de connection");
} else {
$mysql_desc = DATABASEDB;
if(!$result = mysql_query( $query))
{
return 0;
} else {
return $result;
}
mysql_close($link);
}
}
This is the part with which I have problem. I want to change it using PDO.
while( list($x,$y,$z) = mysql_fetch_row($lactu->list) )
I am proceed like this but it doesn't work
while( list($x,$y,$z) = $lactu->list->fetch(PDO::FETCH_NUM)
any ideas ?
Why don't you use PDO::FETCH_ASSOC? Check the code sample for connecting to database, executing the query, fetching all rows and iterate over the rows.
//Your query
$queryliste = "SELECT id, nom, prenom FROM table";
//Initialize pdo connection use your $name, $host, $username and $password
$pdoLink = new PDO("mysql:dbname={$name};host={$host};charset=utf8", $username, $password);
//Prepare statement
$statement = $pdoLink-> prepare($queryliste);
//Execute query
$statement -> execute();
//(1) Fetch rows using PDO::FETCH_ASSOC
$rows = $statement -> fetchAll(PDO::FETCH_ASSOC);
$statement -> closeCursor();
foreach($rows as $row) {
echo $row['id'];
echo $row['nom'];
echo $row['prenom'];
}
//(2) or you can use PDO::FETCH_NUM
$rows = $statement -> fetchAll(PDO::FETCH_NUM);
$statement -> closeCursor();
foreach($rows as list($x, $y, $z)) {
echo $x;
echo $y;
echo $z;
}
//(3) or you can rewrite the last in the same form you are using as
while((list($x, $y, $z) = $statement->fetch(PDO::FETCH_NUM))) {
echo $x;
echo $y;
echo $z;
}
$statement -> closeCursor();
Related
I want to replace a string but I use PDO. Whatever I have tried is not working. Have you ever replaced a mysql string by using PDO connection?
Here is an example which is not working.
try
{
$image = $_POST['data1'];
$id= $_POST['data2'];
$insert = "UPDATE myTable SET images=REPLACE(images,':image','') where id = :id";
$insertStmt = $conn->prepare($insert);
$insertStmt->bindValue(":image", $image);
$insertStmt->bindValue(":id", $id);
$insertStmt->execute();
echo "success";
}
catch(PDOException $ex)
{
echo $ex->getMessage();
}
write :image instead of ':image'
$insert = "UPDATE myTable SET images=REPLACE(images,:image,'') where id = :id";
if ($tag == 'get_rajkot')
{
$data=$db->get_rajkot();
if($data!=false)
{
$valueresult=array();
foreach ($data as $value)
{
$valueresult=$value;
echo json_encode($valueresult);
}
}
else
{
// failed to store
$response["error"] = 1;
$response["error_msg"] = "Error occured..No get_headlines image found...";
echo json_encode($response);
}
}
db_function.php
public function get_rajkot()
{
$result = mysql_query("SELECT * FROM wp_term_relationships join wp_posts where ID=`object_id` and term_taxonomy_id=19 ORDER BY object_id DESC LIMIT 10") or die(mysql_error());
// check for result
$no_of_rows = mysql_num_rows($result);
if ($no_of_rows > 0)
{
$rows = array();
while($r = mysql_fetch_assoc($result))
{
$rows[] = $r;
//print_r($rows);
}
return $rows;
}
else
{
// profile not found
return false;
}
}
Result:
It's not giving comma between two objects and brakets [] at the start and at the end.
set my sql char set after mysql_connect query like this...
this problem was occurring due to Gujarati font
$con = mysql_connect($host,$username,$password) or die(mysql_error());
mysql_set_charset('utf8mb4',$con);
I have written a function that will query the database. The sql statement includes a where clause. However, I keep getting this error
"Message: odbc_exec(): SQL error: [Microsoft][ODBC SQL Server
Driver][SQL Server]Invalid column name 'home'., SQL state S0022 in
SQLExecDirect".
The column name should be banner_category while "home_banner) is the value.
How should I go about achieving it?
public function get_landing_banners()
{
$query = $this->db->query(
'SELECT *
FROM o2o_banner
WHERE banner_category='home_banner'');
$data = array();
foreach ($query->result_array() as $row)
{
$data[] = $row;
}
return $data;
}
If you want to return an array try this:
public function get_landing_banners()
{
$this->db->select('*')->from('o2o_banner')->where('banner_category', 'home_banner');
$q = $this->db->get();
if ($q->num_rows() > 0) {
return $q->result_array();
}
}
Try this coding
public function get_landing_banners()
{
$query = $this->db->query(
'SELECT *
FROM o2o_banner
WHERE banner_category="home_banner"');
$data = array();
foreach ($query->result_array() as $row)
{
$data[] = $row;
}
return $data;
}
Am using drupal to manage my content. I want to search all my contents title and body and find how many times each word is repeated in the whole contents.
It may be by an sql query, but I have no experience with sql.
Any ideas?
This code searches the body field and ALL fields of ANY Content Types for a specific string. You can run it via command line. Say you save it as "fieldsearch.php", you can then run it as:
php fieldsearch.php "myStringForWhichToSearch"
You need to fill in your connection data and database name. It outputs the array of matching nodes but you can format that output into anything you'd like (I recommend csv).
<?php
//Set Parameters here
$env = "dev"; // Options [dev|prod] - Defaults to dev
$prodConnection = array(
"host" => "",
"user" => "",
"pass" => ""
);
$devConnection = array(
"host" => "",
"user" => "",
"pass" => ""
);
//Use the selected env settings
if($env == "prod"){
$connection = $prodConnection;
} else {
$connection = $devConnection;
}
function getTables($con, $database){
//Get the set of field tables
$sql = "SHOW TABLES FROM $database";
$result = mysqli_query($con, $sql);
if (!$result) {
echo "DB Error, could not list tables\n";
echo 'MySQL Error: ' . mysql_error();
exit;
}
$tables = array();
while ($row = mysqli_fetch_row($result)) {
$tables[] = $row[0];
}
mysqli_free_result($result);
return $tables;
}
function getFieldTables($con,$database){
$allTables = getTables($con, $database);
$fieldTables = array();
foreach($allTables as $key => $table){
if( isFieldTable($table) ){
$fieldTables[] = $table;
}
}
//add the common tables
$fieldTables[] = "field_data_body";
$fieldTables[] = "field_data_comment_body";
return $fieldTables;
}
function isFieldTable($table){
//echo $table . "\n";
if( stripos($table, "field_data_field") !== FALSE){
return TRUE;
}
}
//Set the search term here:
if (array_key_exists(1, $argv)) {
$searchString = $argv[1];
}
else {
die('usage: php fieldsearch.php "search string"' . "\n");
}
$databaseName = "myDatabaseName";
$outArray = array();
//Connect
$con=mysqli_connect($connection['host'],$connection['user'],$connection['pass'],$databasePrefix.$databaseNum);
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//getFieldTables
$fieldTables = getFieldTables($con, $databaseName);
//Query each field tables data for the string in question
foreach($fieldTables as $key => $table){
//get Field value column name
$valueCol = str_replace("field_data_field_", '', $table);
$result = mysqli_query($con,"SELECT
entity_id
FROM
$table
WHERE
field_" . $valueCol . "_value
LIKE
'%$searchString%';");
if($result){
while($row = mysqli_fetch_assoc($result)){
$dataArray[$table][$row['entity_id']]['nid'] = $row['entity_id'];
}
}
}
//Add the body table
$result = mysqli_query($con,"SELECT
entity_id
FROM
field_data_body
WHERE
body_value
LIKE
'%$searchString%';");
if($result){
while($row = mysqli_fetch_assoc($result)){
$dataArray['field_data_body'][$row['entity_id']]['nid'] = $row['entity_id'];
}
}
var_dump($dataArray);
I am building a Live Search function on my website, I used the W3schools example, which worked perfectly. But I want to use MySQL database instead of the XML file, so I am working on a code to take the MySQL database and turn it into an XML file.
<?php
header("Content-type: text/xml");
include 'dbc.php';
$query = "SELECT * FROM airports";
$result = mysql_query($query, $link)
or die('Error querying database.');
$xml_output = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
$xml_output .= "<entries>\n";
for($x = 0 ; $x < mysql_num_rows($result) ; $x++){
$row = mysql_fetch_assoc($result);
$xml_output .= "\t<entry>\n";
$xml_output .= "\t\t<ident>" . $row['ident'] . "</ident>\n";
// Escaping illegal characters
$row['name'] = str_replace("&", "&", $row['name']);
$row['name'] = str_replace("<", "<", $row['name']);
$row['name'] = str_replace(">", ">", $row['name']);
$row['name'] = str_replace("\"", """, $row['name']);
$xml_output .= "\t\t<name>" . $row['name'] . "</name>\n";
$xml_output .= "\t</entry>\n";
}
$xml_output .= "</entries>";
echo $xml_output;
?>
I am getting this error:
Warning: DOMDocument::load() [domdocument.load]: Start tag expected, '<' not found in /public_html/sql2xml.php, line: 11 in /public_html/livesearch.php on line 12
no suggestion
I have read the explanation at: Avoid DOMDocument XML warnings in php
But I have no idea how to fix that in my code. Any suggestions?
This will take the data from the 'Name' column in your mysql table and put it into an array its the same array w3c school looks up as you type
$mysqli = new mysqli(HOST,USER,PASSWORD,DATABASE);
/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$query = "SELECT * FROM table";
$result = $mysqli->query($query);
while($row = $result->fetch_array())
{
$a[]=$row["Name"];
}
/* free result set */
$result->free();
/* close connection */
$mysqli->close();
// get the q parameter from URL
$q = $_REQUEST["q"];
$hint = "";
// lookup all hints from array if $q is different from ""
if ($q !== "") {
$q = strtolower($q);
$len=strlen($q);
foreach($a as $name) {
if (stristr($q, substr($name, 0, $len))) {
if ($hint === "") {
$hint = $name;
} else {
$hint .= ", $name";
}
}
}
}
if (isset($q))
{
// Output "no suggestion" if no hint was found or output correct values
echo $hint === "" ? "no suggestion" : $hint;
}