mySQL->updating/inserting "compound" records - php

I have 2 tables structured like this:
CREATE TABLE `exp_ws_gk_text` (
`WGT_RID` INT(9) NOT NULL AUTO_INCREMENT,
`WGT_PRG_CODE` VARCHAR(5) NOT NULL,
`WGT_TEXT` VARCHAR(4000) NOT NULL,
INDEX `PrimaryKey` (`WGT_RID`)
)
CREATE TABLE `exp_ws_gk_state` (
`WGS_RID` INT(9) NOT NULL AUTO_INCREMENT,
`WGS_TYPE` INT(9) NOT NULL,
`WGS_STATE` VARCHAR(3) NOT NULL,
`WGS_WGT_RID` INT(9) NOT NULL,
INDEX `PrimaryKey` (`WGS_RID`),
INDEX `SecondaryKey` (`WGS_TYPE`, `WGS_STATE`)
)
This is how I query the data to be used in a site:
SELECT a.wgt_rid id, a.wgt_text text, a.wgt_prg_code prg_code,
b.wgs_state state, b.wgs_type type,
FROM exp_ws_gk_text a, exp_ws_gk_state b
WHERE a.wgt_rid = b.wgs_wgt_rid
I present the record with all the data returned. Now, when I want to edit or append a record, how would I save the data correctly if the data got sent from a form with these parameters:
$id = intval($_REQUEST['id']);
$prg_code = $_REQUEST['prg_code'];
$state = $_REQUEST['state'];
$crs_type = $_REQUEST['type'];
$text = $_REQUEST['text'];
An insert:
$sql = "BEGIN; ".
" INSERT INTO exp_ws_gk_text (WGT_PRG_CODE, WGT_TEXT) ".
" VALUES('".$prg_code."', '".$text."'); " .
" INSERT INTO exp_ws_gk_state (WGS_STATE, WGS_TYPE, WGS_WGT_RID) ".
" VALUES('".$state."', ".$course_type.", LAST_INSERT_ID()); ".
"COMMIT;";
$mysql_query($sql);
$sql = "SELECT WGS_WGT_RID id FROM exp_ws_gk_text WHERE WGS_RID = ".mysql_insert_id();
$result = mysql_query($sql);
$r = mysql_fetch_array($result, MYSQL_ASSOC);
echo json_encode(array(
'id' => $r["id"],
'prg_code' => $prg_code,
'state' => $state,
'type' => $type,
'text' => $text
));
A delete:
DELETE a, b FROM exp_ws_gk_text a
JOIN exp_ws_gk_state b ON a.WGT_RID = b.wgs_wgt_rid
WHERE a.WGT_RID = :id

$sql = "UPDATE exp_ws_gk_text a, exp_ws_gk_state b
SET a.WGT_PRG_CODE = ".$prg_code.", a.WGT_TEXT = ".$text.", b.WGS_STATE = ".$state.", b.WGS_TYPE = ".$crs_type."
WHERE
a.WGT_RID = ".$id." AND a.WGT_RID = b.wgs_wgt_rid";

Related

MYSQL: Insert variables into variable name table

I am trying to insert PHP variables in a mysql table, where the table name is also a variable, using mysqli_query. I've tried multiple solutions from stackoverflow but it still does not work.
I try to do it like this, maybe I am missing something. Thank you in advance!
<?php
session_start();
#include_once "modules/connections/dbconn.php";
$value = $_POST['value'];
$playerid = $_SESSION["steamid"];
$playername = fetchinfo("name","users","steamid",$playerid);
$playeravatar = fetchinfo("avatar","users","steamid",$playerid);
$playercoins = fetchinfo("coins", "users","steamid",$playerid);
if($playercoins - $value < 0){
die(json_encode(array('message' => 'ERROR', 'code' => "Not enough coins!")));
}
$game = fetchinfo("value","parameters","name","raffleRound");
$maxitems = fetchinfo("value","parameters","name","raffleMaxritems");
$items = fetchinfo("itemsnum","rafflegames","id",$game);
$itemname = "Coins";
$itemavatar = "images/creditcardicon.png";
$color = "D2D2D2";
$initialvalue = fetchinfo("value","rafflegames","id",$game);
$from = $initialvalue * 100;
$to = $from + $value * 100;
$tablename = 'rafflegame'.$game;
if($items < $maxitems){
mysqli_query($GLOBALS["connect"], "UPDATE rafflegames SET `value`=`value`+$value, `itemsnum`=`itemsnum`+1 WHERE `id`=$game");
mysqli_query($GLOBALS["connect"], "UPDATE users SET `coins`=`coins`-$value WHERE `steamid`=$playerid");
mysqli_query($GLOBALS["connect"], "INSERT INTO `" . $tablename . "` VALUES ('".$playerid."', '".$playername."','".$itemname."','".$color."','".$value."','".$playeravatar."','".$itemavatar."','".$from."','".$to."')");
}
else {
die(json_encode(array('message' => 'ERROR', 'code' => "Too many items in the current game")));
}
?>
The other two queries work just fine.
The table structure is this:
mysqli_query($GLOBALS['connect'],"CREATE TABLE `rafflegame$roundNumber` (
`id` int(11) NOT NULL auto_increment,
`userid` varchar(70) NOT NULL,
`username` varchar(70) NOT NULL,
`item` text,
`color` text,
`value` float,
`avatar` varchar(512) NOT NULL,
`image` text NOT NULL,
`from` int NOT NULL,
`to` int NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;");
mysqli_query($GLOBALS['connect'],"TRUNCATE TABLE `rafflegame$roundNumber`");
There is difference between table structure and insert column coumnt, When you want id column as auto incremented in that case column name should be included in insert query.
Please use the code as below:
<?php
session_start();
#include_once "modules/connections/dbconn.php";
$value = $_POST['value'];
$playerid = $_SESSION["steamid"];
$playername = fetchinfo("name","users","steamid",$playerid);
$playeravatar = fetchinfo("avatar","users","steamid",$playerid);
$playercoins = fetchinfo("coins", "users","steamid",$playerid);
if($playercoins - $value < 0){
die(json_encode(array('message' => 'ERROR', 'code' => "Not enough coins!")));
}
$game = fetchinfo("value","parameters","name","raffleRound");
$maxitems = fetchinfo("value","parameters","name","raffleMaxritems");
$items = fetchinfo("itemsnum","rafflegames","id",$game);
$itemname = "Coins";
$itemavatar = "images/creditcardicon.png";
$color = "D2D2D2";
$initialvalue = fetchinfo("value","rafflegames","id",$game);
$from = $initialvalue * 100;
$to = $from + $value * 100;
$tablename = 'rafflegame'.$game;
if($items < $maxitems){
mysqli_query($GLOBALS["connect"], "UPDATE rafflegames SET `value`=`value`+$value, `itemsnum`=`itemsnum`+1 WHERE `id`=$game");
mysqli_query($GLOBALS["connect"], "UPDATE users SET `coins`=`coins`-$value WHERE `steamid`=$playerid");
mysqli_query($GLOBALS["connect"], "INSERT INTO `" . $tablename . "`(`userid`,`username`,`item`,`color`,`value`,`avatar`,`image`,`from`,`to`) VALUES ('".$playerid."', '".$playername."','".$itemname."','".$color."','".$value."','".$playeravatar."','".$itemavatar."','".$from."','".$to."')");
}
else {
die(json_encode(array('message' => 'ERROR', 'code' => "Too many items in the current game")));
}
?>

Check if empty not working for me

I want to check if a row value from my database is NULL or empty so I did the following:
$existcheck = "
SELECT *
FROM snm_content";
$existcheckcon = $conn->query($existcheck);
$existcheck = $existcheckcon->fetch_assoc();
if((!empty($existcheck['plaats'])) AND (!empty($existcheck['straat']))){
echo 'vol';
}else{
$vultable = "
ALTER TABLE snm_content
ADD (straat varchar(255) NULL,
plaats varchar(255) NULL)";
$vultablecon = $conn->query($vultable);
$vultable = $vultablecon->fetch_assoc();
$updatetable = "
UPDATE snm_content
SET straat = '".$straatnaam."', plaats = '".$bedrijven['plaats']."'";
$updatetablecon = $conn->query($updatetable);
$updatetable = $updatetablecon->fetch_assoc();
}
But I get the following message:
There was an error running the query [Duplicate column name 'straat']
Both straat and plaats in snm_content are all filled with NULL.
So why does it get to the else statement if the values are NULL?
I should mention, this code is inside a while loop from another query.
You should check if the column exist not if column have a data so you have to do like this :
$existcheck = "DESC snm_content";
$existcheckcon = $conn->query($existcheck);
$existcheck = $existcheckcon->fetch_assoc();
if((!empty($existcheck['plaats'])) AND (!empty($existcheck['straat']))){
echo 'vol';
}else{
$vultable = "
ALTER TABLE snm_content
ADD (straat varchar(255) NULL,
plaats varchar(255) NULL)";
$vultablecon = $conn->query($vultable);
$vultable = $vultablecon->fetch_assoc();
$updatetable = "
UPDATE snm_content
SET straat = '".$straatnaam."', plaats = '".$bedrijven['plaats']."'";
$updatetablecon = $conn->query($updatetable);
$updatetable = $updatetablecon->fetch_assoc();
}

MySQL update column only if value not empty where

I have an UPDATE query and using Ajax, I wanted to know if any value is empty can I only update the values that not empty in the database. I don't know if this is possible to have a if statement or something to check to skip the empty values. I know I can just add another form element but just wanted to know if there was another solution.
Only if the data is POST from front end form. If data not POST don't update this Title = '.$title .',
$id = $_POST['id'];
$title = "";
$description = $_POST['Description'];
$date = $_POST['Date'];
$query = 'UPDATE user SET
`id` = '.$id.',
`Title` = '.$title .',
`Description` = '.$description.',
`Date` = '.$date =.'
WHERE `id` = '.$id;
$result = mysql_query($query) or die("<b>A fatal MySQL error occured</b>.<br />Query: ".$query."<br />Error: (".mysql_errno().") ".mysql_error());
Update: This is what worked for me. Thanks Karim Daraf
$query = " UPDATE user SET
Title = Coalesce($title,Title ) etc...
Try it with Coalesce .
$query = " UPDATE user
SET
`Title` = CASE WHEN `Title`='' or `Title` IS NULL THEN '$title' END,
`Description` = CASE WHEN `Description`='' Or `Description` IS NULL THEN '$description' END,
`Date` = CASE WHEN `Date`='' Or Date` IS NULL THEN '$date' END
WHERE `id` = '".$id."' ";
or :
$query = " UPDATE user
SET
`id` = Coalesce('$id''".$id."' , NULLIF(`id`,'')),
`Title` = Coalesce('$title''".$title."',NULLIF(`Title`,'') ) ,
`Description` = Coalesce('$description''".$description."' , NULLIF(`Description`,'') ) ,
`Date` = Coalesce('$date''".$date."',NULLIF(`Date`,''))
WHERE `id` = '$id''".$id."' ";
$query = 'UPDATE user SET
`id` = '.$id.',
`Title` = COALESCE(NULLIF("'.$title.'", ""),`Title`),
`Description` = "'.$description.'",
`Date` = "'.$date.'"
WHERE `id` = "'.$id.'"';
Not sure to understand: you have data and want to update, but only if some fied in the DB are empty?
In the case perfom only a where:
$query = 'UPDATE user SET
`id` = '.$id.',
`Title` = '.$title .',
`Description` = '.$description.',
`Date` = '.$date =.'
WHERE `id` = '.$id.' AND Title = '';
for example

MySQL encoding parsed wrong [duplicate]

This question already has answers here:
UTF-8 all the way through
(13 answers)
Closed 8 years ago.
Im trying to add some text with this command, included in my php file:
$sql = "INSERT INTO $this->table_name_category (name, marker_icon) VALUES ('".$name."', '".$marker_icon."')";
Everything looks fine in English characters, but in GREEK one's, the parsed text is being converted to question marks "??????"
Is there something else that i must take care off? Is there a way to tell INSERT command to use UTF8 in order to support Greek characters?
Thanks in advance.
My database is set to utf8_unicode_ci (tables too).
My code is:
<?php
class Store_locator_wpress_db {
var $wpdb;
var $table_name;
var $table_name_category;
function Store_locator_wpress_db() {
global $wpdb;
$this->wpdb = $wpdb;
$this->table_name = $wpdb->prefix . "store_wpress";
$this->table_name_category = $wpdb->prefix . "store_wpress_category";
$this->table_name_category2 = $wpdb->prefix . "store_wpress_category2";
}
function setup_tables() {
self::create_tables();
self::update_stores_table();
//self::update_categories_table();
}
function update_stores_table() {
$sql = "DESCRIBE $this->table_name";
$result = $this->wpdb->get_results($sql, 'ARRAY_N');
for($i=0; $i<count($result); $i++) {
$field[] = $result[$i][0];
}
if(!in_array('category_id',$field)) {
$sql = "ALTER TABLE `$this->table_name` ADD `category_id` INT NOT NULL AFTER `post_id`";
$this->wpdb->query($sql);
}
if(!in_array('category2_id',$field)) {
$sql = "ALTER TABLE `$this->table_name` ADD `category2_id` INT NOT NULL AFTER `category_id`";
$this->wpdb->query($sql);
}
if(!in_array('country',$field)) {
$sql = "ALTER TABLE `$this->table_name` ADD `country` VARCHAR( 60 ) NOT NULL AFTER `email`";
$this->wpdb->query($sql);
}
if(!in_array('city',$field)) {
$sql = "ALTER TABLE `$this->table_name` ADD `city` VARCHAR( 60 ) NOT NULL AFTER `email`";
$this->wpdb->query($sql);
}
}
function update_categories_table() {
$sql = "DESCRIBE $this->table_name_category";
$result = $this->wpdb->get_results($sql, 'ARRAY_N');
for($i=0; $i<count($result); $i++) {
$field[] = $result[$i][0];
}
if(!in_array('marker_icon',$field)) {
$sql = "ALTER TABLE `$this->table_name_category` ADD `marker_icon` VARCHAR( 200 ) NOT NULL AFTER `name`";
$this->wpdb->query($sql);
}
}
function create_tables() {
$sql = "CREATE TABLE IF NOT EXISTS " . $this->table_name . " (
`id` BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`user_id` BIGINT NOT NULL ,
`post_id` BIGINT NOT NULL ,
`category_id` INT NOT NULL ,
`name` VARCHAR( 160 ) NOT NULL ,
`logo` VARCHAR( 160 ) NOT NULL ,
`address` VARCHAR( 160 ) NOT NULL ,
`lat` VARCHAR( 20 ) NOT NULL ,
`lng` VARCHAR( 20 ) NOT NULL ,
`url` VARCHAR( 160 ) NOT NULL ,
`description` TEXT NOT NULL ,
`tel` VARCHAR( 30 ) NOT NULL ,
`email` VARCHAR( 60 ) NOT NULL ,
`created` DATETIME NOT NULL
) ENGINE = MYISAM;";
$this->wpdb->query($sql);
$sql = "CREATE TABLE IF NOT EXISTS " . $this->table_name_category . " (
`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`name` VARCHAR( 120 ) NOT NULL,
`marker_icon` VARCHAR( 200 ) NOT NULL
) ENGINE = MYISAM ;";
$this->wpdb->query($sql);
$sql = "CREATE TABLE IF NOT EXISTS " . $this->table_name_category2 . " (
`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`name` VARCHAR( 120 ) NOT NULL
) ENGINE = MYISAM ;";
//$this->wpdb->query($sql);
}
function get_locations($criteria) {
$lat = $criteria['lat'];
$lng = $criteria['lng'];
$page_number = $criteria['page_number'];
$nb_display = $criteria['nb_display'];
$distance_unit = $criteria['distance_unit'];
$category_id = $criteria['category_id'];
$category2_id = $criteria['category2_id'];
$radius_id = $criteria['radius_id'];
$start = ($page_number*$nb_display)-$nb_display;
if($distance_unit=='miles') $distance_unit='3959'; //miles
else $distance_unit='6371'; //km
$sql = "SELECT s.*, c.marker_icon, c.name category_name,
( $distance_unit * acos( cos( radians('".$lat."') ) * cos( radians( lat ) ) * cos( radians( lng ) - radians('".$lng."') ) + sin( radians('".$lat."') ) * sin( radians( lat ) ) ) ) AS distance
FROM ".$this->table_name." s
LEFT JOIN ".$this->table_name_category." c
ON s.category_id=c.id
WHERE 1 ";
if($category_id!='') $sql .= " AND category_id='$category_id'";
if($category2_id!='') $sql .= " AND category2_id='$category2_id'";
if($radius_id!='') $sql .= " HAVING distance<='".$radius_id."'";
if($lat!=''&&$lng!='') $sql .= " ORDER BY distance";
else $sql .= " ORDER BY id DESC";
if($nb_display!='') $sql .= " LIMIT $start, $nb_display";
$locations = $this->wpdb->get_results($sql, 'ARRAY_A');
return $locations;
}
function return_nb_stores($criteria=array()) {
$category_id = $criteria['category_id'];
$sql = "SELECT count(*) as nb
FROM $this->table_name WHERE 1";
if($category_id!='') $sql .= " AND category_id='$category_id'";
$results = $this->wpdb->get_results($sql, 'ARRAY_A');
return $results[0];
}
function return_stores($criteria=array()) {
$id = $criteria['id'];
$post_id = $criteria['post_id'];
$category_id = $criteria['category_id'];
$sql = "SELECT s.*, c.marker_icon
FROM $this->table_name s
LEFT JOIN ".$this->table_name_category." c
ON s.category_id=c.id
WHERE 1";
if($id>0) $sql .= " AND s.id='$id'";
if($post_id>0) $sql .= " AND s.post_id='$post_id'";
if($category_id>0) $sql .= " AND s.category_id='$category_id'";
$sql .= ' ORDER BY s.created DESC';
$results = $this->wpdb->get_results($sql, 'ARRAY_A');
return $results;
}
function return_categories($criteria=array()) {
$id = $criteria['id'];
$sql = "SELECT * FROM $this->table_name_category WHERE 1";
if($id>0) $sql .= " AND id='$id'";
$sql .= ' ORDER BY name';
$results = $this->wpdb->get_results($sql, 'ARRAY_A');
return $results;
}
function return_categories2($criteria=array()) {
$id = $criteria['id'];
$sql = "SELECT * FROM $this->table_name_category2 WHERE 1";
if($id>0) $sql .= " AND id='$id'";
$sql .= ' ORDER BY name';
$results = $this->wpdb->get_results($sql, 'ARRAY_A');
return $results;
}
function return_nb_stores_by_category() {
$sql = 'SELECT c.id, count(*) nb
FROM '.$this->table_name.' s, '.$this->table_name_category.' c
WHERE s.category_id=c.id GROUP BY s.category_id';
$results = $this->wpdb->get_results($sql, 'ARRAY_A');
for($i=0; $i<count($results); $i++) {
$storesCat[$results[$i]['id']] = $results[$i]['nb'];
}
return $storesCat;
}
function return_nb_stores_by_category2() {
$sql = 'SELECT c.id, count(*) nb
FROM '.$this->table_name.' s, '.$this->table_name_category2.' c
WHERE s.category2_id=c.id GROUP BY s.category2_id';
$results = $this->wpdb->get_results($sql, 'ARRAY_A');
for($i=0; $i<count($results); $i++) {
$storesCat[$results[$i]['id']] = $results[$i]['nb'];
}
return $storesCat;
}
function delete_store($id) {
$user_id = get_current_user_id();
$sql = "SELECT * FROM $this->table_name WHERE id='$id' AND user_id='$user_id'";
$results = $this->wpdb->get_results($sql, 'ARRAY_A');
if(count($results)>0) {
$sql = "DELETE FROM $this->table_name WHERE id='%d'";
$this->wpdb->query($this->wpdb->prepare($sql, $id));
return 'The store has been deleted.';
}
else {
return 'Only the author of this store, can delete it.';
}
}
function delete_category($id) {
$sql = "SELECT * FROM $this->table_name WHERE category_id='$id'";
$results = $this->wpdb->get_results($sql, 'ARRAY_A');
if(count($results)>0) {
return "You cannot delete this category because it's containing ".count($results)." store(s). Please delete the stores first then try again.";
}
else {
$sql = "DELETE FROM $this->table_name_category WHERE id='%d'";
$this->wpdb->query($this->wpdb->prepare($sql, $id));
return 'The category has been deleted.';
}
}
function delete_category2($id) {
$sql = "SELECT * FROM $this->table_name WHERE category2_id='$id'";
$results = $this->wpdb->get_results($sql, 'ARRAY_A');
if(count($results)>0) {
return "You cannot delete this category because it's containing ".count($results)." store(s). Please delete the stores first then try again.";
}
else {
$sql = "DELETE FROM $this->table_name_category2 WHERE id='%d'";
$this->wpdb->query($this->wpdb->prepare($sql, $id));
return 'The category has been deleted.';
}
}
function update_store($criteria) {
$sql = "UPDATE $this->table_name SET
post_id='".$criteria['post_id']."', category_id='".$criteria['category_id']."', category2_id='".$criteria['category2_id']."',
name='".$criteria['name']."', logo='".$criteria['logo']."', url='".$criteria['url']."',
address='".$criteria['address']."', lat='".$criteria['lat']."', lng='".$criteria['lng']."',
description='".$criteria['description']."', tel='".$criteria['tel']."', email='".$criteria['email']."'
WHERE id='".$criteria['id']."'";
$this->wpdb->query($sql);
}
function update_category($criteria) {
$sql = "UPDATE $this->table_name_category SET name='".$criteria['name']."', marker_icon='".$criteria['marker_icon']."'
WHERE id='".$criteria['id']."'";
$this->wpdb->query($sql);
}
function update_category2($criteria) {
$sql = "UPDATE $this->table_name_category2 SET name='".$criteria['name']."'
WHERE id='".$criteria['id']."'";
$this->wpdb->query($sql);
}
function add_store($criteria) {
$sql = "INSERT INTO $this->table_name
(user_id, post_id, category_id, category2_id, name, logo, address, lat, lng, url, description, tel, email, created)
VALUES ('".$criteria['user_id']."', '".$criteria['post_id']."', '".$criteria['category_id']."', '".$criteria['category2_id']."', '".$criteria['name']."', '".$criteria['logo']."', '".$criteria['address']."', '".$criteria['lat']."', '".$criteria['lng']."',
'".$criteria['url']."', '".$criteria['description']."', '".$criteria['tel']."', '".$criteria['email']."', '".date('Y-m-d H:i:s')."')";
//echo $sql.'<br>';
$this->wpdb->query($sql);
}
function add_category($criteria=array()) {
$name = $criteria['name'];
$marker_icon = $criteria['marker_icon'];
$sql = "INSERT INTO $this->table_name_category (name, marker_icon) VALUES ('".$name."', '".$marker_icon."')";
$this->wpdb->query($sql);
}
function add_category2($criteria=array()) {
$name = $criteria['name'];
$sql = "INSERT INTO $this->table_name_category2 (name) VALUES ('".$name."')";
$this->wpdb->query($sql);
}
}
?>
before you do any query or CRUD in mysql issue this command
"SET NAMES utf8"
"SET CHARACTER SET utf8"
in PHP...
mysql_query("SET NAMES utf8");
to make sure everything is in UTF-8 and you use PDO... modify your PDO connection into this
depending on what API you use
$pdo = new PDO(
'mysql:host=hostname;dbname=defaultDbName',
'username',
'password',
array(PDO::MYSQL_ATTR_INIT_COMMAND => "utf8")
);
reference:
Accented characters in mySQL table
Couple of things to check are the connection and the column. Columns can have their own char set
http://www.php.net/manual/en/mysqli.set-charset.php
http://dev.mysql.com/doc/refman/5.0/en/charset-column.html
1.Use show create table X to see the encoding of the table.
something like:
mysql> show create table user;
+-------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table | Create Table |
+-------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| user | CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
`password` varchar(64) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 |
+-------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)
2.If charset is not utf8, change it such.
mysql> alter table y character set 'utf8';

PHP & MySQL array question

I'm trying to add the articles id to the title, summary and content but I don't know how to do it can some one help me solve this problem.
Here is the code that is giving me the problem.
while($row = mysqli_fetch_assoc($run)) {
$id[] = $row['id'];
$title[] = $row['id']['title'];
$summary[] = $row['id']['summary'];
$content[] = $row['id']['article_content'];
}
And here is my PHP and MySQL code in full below.
$x = 0;
$con = null;
$search = $_REQUEST['search'];
$id = array();
$title = array();
$summary = array();
$content = array();
$search_explode = mysqli_real_escape_string($dbc, $search);
$search_explode = explode(' ', $search_explode);
foreach($search_explode as $search_each) {
$x++;
if($x == 1){
$con .= " article_content LIKE '%$search_each%' OR title LIKE '%$search_each%' OR summary LIKE '%$search_each%'";
} else {
$con .= " OR article_content LIKE '%$search_each%' OR title LIKE '%$search_each%' OR summary LIKE '%$search_each%'";
}
}
$con = "SELECT users.*, users_articles.* FROM users_articles
INNER JOIN users ON users_articles.user_id = users.user_id
WHERE ($con)
AND users.active IS NULL
AND users.deletion = 0";
$run = mysqli_query($dbc, $con);
$search_term = mysqli_num_rows($run);
while($row = mysqli_fetch_assoc($run)) {
$id[] = $row['id'];
$title[] = $row['id']['title'];
$summary[] = $row['id']['summary'];
$content[] = $row['id']['article_content'];
}
while($row = mysqli_fetch_assoc($run)) {
// $id[] = $row['id']; you probably do not need this anymore
$title[$row['id']] = $row['title'];
$summary[$row['id']] = $row['summary'];
$content[$row['id']] = $row['article_content'];
}
// at this point, each array will contain rows
// with keys matching the corresponding id
var_dump($title);
var_dump($summary);
var_dump($content);
$title[] = $row['id']['title'];
$summary[] = $row['id']['summary'];
$content[] = $row['id']['article_content'];
mysqli_fetch_assoc will fetch an associated array. Accessing the data directly like so $row['summary'] should fix your problem.
EDIT
Are you talking about string concatenation?
$title[] = $row['id'] . ' ' . $row['title'];
$summary[] = $row['id'] . ' ' . $row['summary'];
$content[] = $row['id'] . ' ' . $row['article_content'];
The above code will basically append the title/summary/content to your article ID and add it into respective arrays.
I am not sure what you want to achieve but I would suggest the the following solution. Please take a look.
CREATE TABLE IF NOT EXISTS users (
user_id int(11) NOT NULL AUTO_INCREMENT,
name varchar(100) NOT NULL,
deletion int(11) NOT NULL DEFAULT '0',
active int(11) NOT NULL DEFAULT '1',
PRIMARY KEY (user_id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
--
-- Dumping data for table users
INSERT INTO users (user_id, name, deletion, active) VALUES
(1, 'John', 0, 1),
(2, 'George', 0, 1);
--
-- Table structure for table users_articles
CREATE TABLE IF NOT EXISTS users_articles (
id int(11) NOT NULL AUTO_INCREMENT,
user_id int(11) NOT NULL,
article_content varchar(255) NOT NULL,
title varchar(255) NOT NULL,
summary text NOT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;
--
-- Dumping data for table users_articles
INSERT INTO users_articles (id, user_id, article_content, title, summary) VALUES
(1, 1, 'test', 'test', 'test test test test'),
(2, 2, 'test 2', 'test 2', 'test test'),
(3, 1, 'test 3', 'test 3 ', 'test test test test 3'),
(4, 2, 'test 3', 'test 3', 'test test 3');
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
$mysqli = new mysqli("localhost", "root", "", "articles");
/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
/* Select queries return a resultset */
$con = 1;
$sql = "SELECT users.*, users_articles.* FROM users_articles
INNER JOIN users ON users_articles.user_id = users.user_id
WHERE ($con)
AND users.active = 1
AND users.deletion = 0";
$results = array();
if ($result = $mysqli->query($sql)) {
printf("Select returned %d rows.\n", $result->num_rows);
print '<pre>';
while ($row = $result->fetch_assoc()) {
$results[] = $row;
}
print_r($results);
print '</pre>';
/* free result set */
$result->close();
}
$mysqli->close();
?>
and when you will iterate $results you can concatenate id and other fields in that case you can utilize the result array in other areas too.

Categories