SQL UPDATE broken - php

I have been troubleshooting this code for awhile, but it won't work and I can't find out why. Does anyone see an error? Also, I'm aware that there is no WHERE statement, I intentionally want to update all records.
<?php
// Connect to database
$link = mysqli_connect('*****', '*****', '*****');
if (!$link) {
die('Could not connect: ' . mysqli_connect_error());
}
mysqli_select_db(bullseye);
// Varaible setting
$header = $_POST['header'];
$video = $_POST['video'];
$m_title = $_POST['m_title'];
$m_sub = $_POST['m_sub'];
$w_title = $_POST['w_title'];
$w_sub = $_POST['w_sub'];
$w_t1 = $_POST['w_t1'];
$w_t2 = $_POST['w_t2'];
$w_t3 = $_POST['w_t3'];
$w_d1 = $_POST['w_d1'];
$w_d2 = $_POST['w_d2'];
$w_d3 = $_POST['w_d3'];
$p_title = $_POST['p_title'];
$p_sub = $_POST['p_sub'];
mysqli_query($link, "UPDATE tbl_name SET
header=$header,
video=$video,
mtitle=$m_title,
msub=$m_sub,
wtitle=$w_title,
wsub=$w_sub,
wt1=$w_t1,
wt2=$w_t2,
wt3=$w_t3,
wd1=$w_d1
wd2=$w_d2,
wd3=$w_d3,
ptitle=$p_title,
psub=$p_sub");
?>
EDIT:
mysqli_query($link, "UPDATE about SET
header='$header',
video='$video',
mtitle='$m_title',
msub='$m_sub',
wtitle='$w_title',
wsub='$w_sub',
wt1='$w_t1',
wt2='$w_t2',
wt3='$w_t3',
wd1='$w_d1',
wd2='$w_d2',
wd3='$w_d3',
ptitle='$p_title',
psub='$p_sub'");

First off, you should prepare it using MySQLi as to protect yourself from MySQL injection:
$mysqli = new mysqli("localhost", "my_user", "my_password", "bullseye");
$query = $mysqli->prepare("UPDATE tbl_name SET
header=?,
video=?,
mtitle=?,
msub=?,
wtitle=?,
wsub=?,
wt1=?,
wt2=?,
wt3=?,
wd1=?
wd2=?,
wd3=?,
ptitle=?,
psub=?");
$query->bind_param("ssssssssssssss, $header, $video, $m_title, $m_sub, $w_title, $w_t1, $w_t2, $w_t3, $w_d1, $w_d2, $w_d3, $p_title, $p_sub");
$query->execute();
$query->close();
$mysqli->close();
This code should work. If it doesn't please post the error.

It looks you need to concat your query with your variables. And not just a big string.

You should use the following to chose your database:
mysqli_select_db($link, "bullseye");

Related

Connect to Multiple Databases using MySQLi

I need to connect to two databases using PHP and use the results from the first query to get the rest of the data I need out of a second database.
So for the second connection, I need to connect to the second database and Select state and zipcode where the results from connection 1 (client) is equal to the firstname in database 2. How would I do this?
<?php
// check if the 'id' variable is set in URL, and check that it is valid
if (isset($_GET['cd']) && is_numeric($_GET['cd'])) {
// get id value
$id = intval($_GET['cd']);
}
$results = $id;
//Open a new connection to the MySQL server
require "calendarconnect.php";
//chained PHP functions
$client = $mysqli->query("SELECT client FROM appointments WHERE ID = $results")->fetch_object()->client;
print $client; //output value
$mysqli->close();
Connection To Database Code is similar to the below
<?php
//Open a new connection to the MySQL server
$mysqli = new mysqli('localhost','some database','some password','some username');
//Output any connection error
if ($mysqli->connect_error) {
die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}
This isn't tested, but I think it would go something like this.
<?php
$dbc1 = new MySQLi()or die('error connecting to database');
$dbc2 = new MySQLi()or die('error connecting to database');
//build query 1
$query1 = "SELECT * FROM Table";
$result1 = $dbc1->query($query) or die("Error in query");
$thing1 = '';
// check result
if($result1->num_rows){
//fetch result as object
$row = $result1->fetch_object();
//set attributes
$thing1 = $row->Name;
}
//build query 2
$query2 = "SELECT * FROM AnotherTable WHERE Id = '$thing1'";
$result2 = $dbc2->query($query) or die("Error in query");
$thing2 = '';
// check result
if($result2->num_rows){
//fetch result as object
$row = $result2->fetch_object();
//set attributes
$thing2 = $row->Name;
}
?>
You would need to make 2 different connections
<?php
$mysqliDB1 = new mysqli('localhost', 'DB1UserId', 'pwd', 'db1');
$mysqliDB2 = new mysqli('localhost', 'DB2UserId', 'pwd', 'db2');
Now when you use the $mysqliDB1->.... you are talking to the DB1 database and when you use the $mysqliDB2->.... you are talking to the DB2 database
So
$client = $mysqliDB1->query("SELECT client FROM appointments WHERE ID = $results")
->fetch_object();
$locn = $mysqliDB2->query("SELECT state,zipcode
FROM location
WHERE ClientID = {$client->FirstName}")
->fetch_object();
echo $locn->state;
echo $locn->zipcode;
I am guessing the table name and so on, but I am not clarevoyant so you will have to fill that in for yourself.
If you want to perform queries in two databases at the same time you need to have two separate mysqli objects. To open the connection you can use the following code:
// Don't forget to enable error reporting!
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$db1 = new mysqli('localhost', 'user', 'pass', 'dbName');
$db1->set_charset('utf8mb4'); // always set the charset
$db2 = new mysqli('localhost', 'user', 'pass', 'dbName2');
$db2->set_charset('utf8mb4'); // always set the charset
Then you can perform your two statements in each database separately.
// get id value
$id = intval($_GET['cd']);
// Get client name from DB1
$stmt = $db1->prepare('SELECT client FROM appointments WHERE ID = ?');
$stmt->bind_param('s', $id);
$stmt->execute();
$client = $stmt->get_result()->fetch_object();
// Get state and zipcode from DB2
$stmt = $db2->prepare('SELECT state,zipcode FROM location WHERE ClientName = ?');
$stmt->bind_param('s', $client->client);
$stmt->execute();
$location = $stmt->get_result()->fetch_object();
echo $location->state;
echo $location->zipcode;

Notice: Undefined index error in php

I have data's stored with the delimiter / in my table. I need to separate them and need to store them in different table. While doing that i'm getting:
Notice: Undefined index: VSX1 in /opt/lampp/htdocs/disease.php on line 21
How can I solve this kind of error?
<html>
<body>
<?php
$username = "root";
$password = "****";
$hostname = "localhost";
$dbhandle = mysql_connect($hostname, $username, $password) or die("Unable to connect to MySQL");
$selected = mysql_select_db("disease",$dbhandle) or die("Could not select disease");
$result = mysql_query("SELECT * FROM `primary_data` LIMIT 0, 30");
while($row = mysql_fetch_array($result))
{
$string = $row['gene_name'];
$tok = strtok($string, "/");
while ($tok !== false) {
mysql_query("insert into temp_gene gene_name values('".$_POST[$tok]."')");
$tok = strtok("/");
}
}
mysql_close($dbhandle);
?>
</table>
</body>
</html>
You transfer data from one table and save it to another. You need no $_POST variable at all!
Of course, data MUST be escaped well.
while (($tok = strtok($string, '/')) !== false) {
$tok = mysql_real_escape_string($tok);
mysql_query("INSERT INTO temp_gene(gene_name) VALUES('{$tok}')");
}
I second Brad:s advice of using PDO & prepared statements - it is way more elegant and efficient.
Here's some code for you... as I have no idea what you want to do with tokensizing, etc. I've not written the logic for what to do with $gene_name, but I'm sure you do =)
Have a look at http://www.php.net/manual/en/book.pdo.php
I also advice you to use Doctrine as a wrapper/ORM on top of PDO, it makes things real easy: http://www.doctrine-project.org/
$dsn = "mysql:dbname={$db_name};host={$db_host}";
try {
// init db handler.
$db = new PDO( $dsn, $db_username, $password );
// Execute selecting query.
$select_sql = "SELECT gene_name FROM `primary_data` LIMIT 0, 30";
$select_stmt = $db -> prepare( $sql );
$select_stmt -> execute();
// Bind row column 1 (1-indexed) to $gene_name.
$select_stmt -> bindColumn( 1, $gene_name );
// Prepare insert query to temp_gene.
$temp_sql = "INSERT INTO temp_gene(gene_name) VALUES(?)";
$temp_stmt = $db -> prepare( $temp_sql );
// Begin transaction, it is more efficient to use transactions as your actual queries becomes 1 instead of O(rows).`enter code here`
$db -> beginTransaction();
while ( $row = $select_stmt -> fetch( PDO::FETCH_BOUND ) ) {
$string =& $gene_name;
// do your tokenizing logic here... also do escaping for security.
$temp_stmt -> execute( array( $your_value_string ) );
}
// Commit the inserts.
$db -> commit();
} catch (PDOException $e) {
die( $e->getMessage() );
}

how to concatenate sql queries

i am trying to concatenate sql queries and run later after loop. how is that possible? this is my vision:
for($i=1;$i<=10;$i++){
$item_.$i = "value_".$i;
sql = sql . " insert into table (`item`) values ('$item_'.$i.'')";
// this should be but an array
}
and save into db:
for($j=0;$j<sqlarray.length;$j++){
$sql_done = mysql_query($sqlarray[$j]);
}
i didnot try anything yet, because the database is big and i am afraid of destroying something important with my code..
thanks a lot
Use mysqli and bindings
see http://www.php.net/manual/en/mysqli.prepare.php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
// define your query
$query = "INSERT INTO tablename (column1,column2) VALUES (:col1,:col2)";
if ($stmt = $mysqli->prepare($query)) {
// loop of insert
for($i=0;$i<10;$i++){
$stmt->bind_param("col1", $i);
$stmt->bind_param("col2", 'test'.$i);
$stmt->execute();
}
$stmt->close();
}else{
throw new Exception("unable to prepare query");
}
$mysqli->close();
Binding will avoid a lot of security issue, no one should use something else then binding ever.
Even better put everything in a transaction and in case of error your database remains unchanged.
see: http://www.php.net/manual/en/mysqli.commit.php for more info
and here is a proposal with commit or rollback
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
if (mysqli_connect_errno()) {
throw new Exception("Unable to connect");
}else{
try{
$mysqli->autocommit(FALSE);
// define your query
$query = "INSERT INTO tablename (column1,column2) VALUES (:col1,:col2)";
if ($stmt = $mysqli->prepare($query)) {
// loop of insert
for($i=0;$i<10;$i++){
$stmt->bind_param("col1", $i);
$stmt->bind_param("col2", 'test'.$i);
$stmt->execute();
}
$stmt->close();
}else{
throw new Exception("unable to prepare query");
}
$mysqli->commit();
}catch(Exception $e){
$mysqli->rollback();
}
$mysqli->close();
}
I did not try it but we should be near a good (best practice?) solution.
I hope this could help you.
For insert query you can write code like below:
$sql .= " insert into table (`item`) values ";
for($i=1;$i<=10;$i++){
$item_.$i = "value_".$i;
$sql = $sql . " ('$item_'.$i.''),";
}
mysqli_query( substr($sql ,0,-1) );
The above will concatenate all the insert data in a single string and execute at once.
I hope you were looking for this
$query = "insert into table_name values";
for($i=0;$i<4;$i++) {
$data1 = "test_".$i;
$data2 = "new_".$i;
$query .= "('','$data1','$data2'),";
}
$query = substr($query,0,-1);
echo $query;
Let me know
try below code
$sql="":
for($i=1;$i<=10;$i++)
{
$item_.$i = "value_".$i;
$sql.=" insert into table (`item`) values ('$item_'.$i.'')";
// this should be but an array
}
mysql_query($sql);

PHP / SQL Query dynamic record from url

I currently have this:
<?php
$con = mysql_connect('localhost', 'root', 'dev');
if(!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("myDB");
$query = "SELECT * FROM pages where id=1";
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
$contents = $row['content'];
echo $contents;
?>
See this part: SELECT * FROM pages where id=1
1 is the record id and it's currently hardcoded. What I need to do is change it so it get's the record id from the url...for example: mysite.com/index.php?2 would show record id 2 ...
How do I go about doing this?
Turn that hardcoded value into a variable.
<?php
//assumes you have a querystring like: http://mysite.com/index.php?id=3
$id = $_GET['id'];
$con = mysql_connect('localhost', 'root', 'dev');
if(!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("myDB");
//Make your variable safe for use with mysql
$id = mysql_real_escape_string($id);
$query = "SELECT * FROM pages where id=" . $id;
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
$contents = $row['content'];
echo $contents;
?>
let say the url is something like that: mysite.com/index.php?id=2
in your index.php:
<?php
$id = $_GET['id'];
// your sanitizing methods for id to avoid SQL injection
$con = mysql_connect('localhost', 'root', 'dev');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("diy");
$query = "SELECT * FROM pages where id = ".$id;
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
$contents = $row['content'];
echo $contents;
?>
Beware of SQL injection
Basic example using mysite.com/index.php?id=x as your URLs where x is the Id:
$id = (int)$_GET['id'];
$query = sprintf("
SELECT *
FROM pages
WHERE id = %d",
mysql_real_escape_string($id)
);
With your connection lines included of course, you should also validate.
URL data is interpreted using the GET method. First, you should look here for how to use it, and here for how to read it.
Basically, your URL will look like this:
mysite.com/index.php?id=2
Then, you could read in the URL variable like this:
$id = mysql_real_escape_string($_GET['id']);
mysql_real_escape_string() will help avoid SQL injection, but requires an existing connection, so your code would look like this:
<?php
// Set up connection
$id = mysql_real_escape_string($_GET['id']);
$query = 'SELECT * FROM pages where id = '.$id;
// Run the query
?>
You could use a regular expression to extract it from the URL.
$retval=preg_match( "#(\d+)$#", $_SERVER['REQUEST_URI'], $match );
$index=-1;
if( $retval ) {
$index = $match[1];
}
This approach allows you to continue using the URL scheme you described in the question without prepending id=. Whether that's a good idea or not is probably debateable.
http://pastebin.com/NEZe7jjL
<?php
$dbh = new PDO('mysql:host=127.0.0.1;dbname=test', 'user', 'password', array(
PDO::ATTR_EMULATE_PREPARES => true,
PDO::MYSQL_ATTR_INIT_COMMAND => 'set names utf8',
));
$stmt = $dbh->prepare('SELECT * FROM `pages` WHERE `id` = :page');
$stmt->bindValue(':page', $_GET['page'], PDO::PARAM_INT);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
?>
yoursite.com/index.php?page=2

Wrong implementation of mysqli?

I am trying to use mysqli for the first time because i have some problems with multiple Query's in one php file. for start im just trying to retrieve data from the stored procedure and print it. but it looks like the code get's stuck somewhere it printed 'succesfull localhost' but it never get's to the code under it. The data never get printed neither the failed.
<?php
$link = mysqli_init();
if (!$link) {
die('mysqli_init failed');
}
if (!mysqli_options($link, MYSQLI_INIT_COMMAND, 'SET AUTOCOMMIT = 0')) {
die('Setting MYSQLI_INIT_COMMAND failed');
}
if (!mysqli_options($link, MYSQLI_OPT_CONNECT_TIMEOUT, 5)) {
die('Setting MYSQLI_OPT_CONNECT_TIMEOUT failed');
}
if (!mysqli_real_connect($link, 'localhost', 'root', '', 'fabiola')) {
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
echo 'Success... ' . mysqli_get_host_info($link) . "\n";
//require 'header.php';
$resID = mysqli_real_escape_string($_REQUEST['resID']);
$materialen_id = mysqli_real_escape_string($_REQUEST['materialen_id']);
$aantal = mysqli_real_escape_string($_REQUEST['aantal']);
$effectief_gebruikt = mysqli_real_escape_string($_REQUEST['effectief_gebruikt']);
$opmerking = mysqli_real_escape_string($_REQUEST['opmerking']);
$datum_van = $_REQUEST['datum_van'];
$datum_tot = $_REQUEST['datum_tot'];
$sqm = "CALL aantal_besch_mat_van_tot($datum_van,$datum_tot,$materialen_id,$resID)";
//$result = $mysqli->query($sqm) or die('Query Failed!');
/* Select queries return a resultset */
if ($result = $mysqli->query($sqm)) {
printf("Select returned %d rows.\n", mysqli_num_rows($result));
/* free result set */
mysqli_free_result($result);
}else{
echo 'failed';
}
mysqli_close($link);
?>
Where is $mysqli set or initialized?
There should be something like:
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
but I can't see it.
btw it's weird that you're mixing the function calling convention 'mysqli_real_escape_string(...)' with the object-orientated functions '$mysqli->query(...)' I'm not sure it's safe to do both.
Also, you will save yourself a lot of heartache by using the MySQLi prepared statements rather than trying to make all your input safe by hand e.g.
$query = "CALL aantal_besch_mat_van_tot(?, ?, ?, ?);";
$statement = $mysqli->prepareStatement($query);
$statement->bind_param('iiii', $datum_van, $datum_tot, $materialen_id, $resID);
$statement->execute();
//get the results.
$statement->close();
$mysqli->close();
It's just so much easier, and more secure to use prepared statements (at the cost of a few percent of performance) that really you should almost always use them.

Categories