Okay I have this syntax for an UPDATE to a table in mysql inside a php script:
mysqli_query($con,"UPDATE ted SET description=$line[5]
WHERE speaker='$speaker' AND event='$event'");
Is there somehting wrong with it? it runs properly in my scriipt (no error's) however no updates are made even though: it is called multiple times (and has lines which match the WHERE condition) heres the entire script
<?php
$contents = file_get_contents('ted_csv.txt');
$con=mysqli_connect("localhost","root","admin","Media2net");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM ted");
$i=0;
while($row = mysqli_fetch_array($result))
{
$speaker =$row['speaker'];
$event =$row['event'];
$pattern2 = preg_quote($speaker, '/');
$pattern1 = preg_quote($event, '/');
$pattern1 = "/^.*$pattern1.*\$/m";
$pattern2 = "/^.*$pattern2.*\$/m";
if(preg_match_all($pattern1, $contents, $matches)){
$submatch = implode("\n", $matches[0]);
if (preg_match_all($pattern2, $submatch, $better)){
echo "got match" . $i . "\n";
$line =str_getcsv( $better[0][0] );
$a_bool = mysqli_query($con,"UPDATE ted SET description=$line[5]
WHERE speaker='$speaker' AND event='$event'");
if ($a_bool){
echo "got match" . $i . "\n";
}else{
echo "query unsuccesful for match" . $i . "\n";
}
}
}
$i++;
}//end of while loop results
mysqli_close($con);
?>
As you can see a match should be available as same string's $speaker and $event were pulled from table ted
So clearly there's something wrong with my syntax as for each query $a_bool is false resulting in echo "query unsuccessful for match" . $i . "\n" being called for each query . Any explanation of what I have done wrong would be greatly appreciated!
SET description=$line[5] should be in quotes
like
mysqli_query($con,"UPDATE ted SET description='{$line[5]}'
WHERE speaker='$speaker' AND event='$event'");
Related
I've made this code but for some reason when i submit the form the data is not inserted to the table name posts. here's my code, i might have a typo or something, it'd be great if someone could have a look.
$fnames = Array("","","","","");
$fcnt = 0;
if (isset($_POST['submit']))
{
$allowedExts = array("gif", "jpeg", "jpg", "pjpeg", "x=png","png",);
// do all 5 files!
for ( $fnum = 1; $fnum <= 5; ++$fnum )
{
$curfile = $_FILES["uploaded_file" . $fnum];
if ($curfile["error"] > 0) {
echo "Return Code: " . $curfile["error"] . "<br>\n";
} else {
$ftype = explode( "/", $curfile["type"])[1]; // get the part after the /
$fsize = $curfile["size"];
if ( in_array($ftype, $allowedExts) && $fsize < 20000000 )
{
echo "Upload: " . $curfile["name"] . "<br>\n";
echo "Type: " . $ftype . "<br>\n";
echo "Size: " . ($fsize/1024) . " KB<br>\n";
echo "Temp file: " . $curfile["tmp_name"] . "<br>\n";
$fname = $_SESSION["userid"] . "_" . $curfile["name"];
if (file_exists("uploads/$fname"))
{
echo "$fname already exists.<br>\n";
} else {
move_uploaded_file($curfile["tmp_name"], "uploads/$fname");
$fnames[$fnum-1] = $fname;
++$fcnt;
}
}
else
{
echo "No valid file in slot $fnum<br>\n";
}
}
}
if ( $fcnt > 1 )
{
$sql = "INSERT INTO posts (picture1, picture2, picture3, picture4, picture5) VALUES( ". "'" . implode("','", $fnames) . "')";
echo "DEBUG SQL: $sql <hr>\n";
mysqli_query($sql);
}
}
With a quick glance:
A) error in your mysqli_query($sql);.
The mysqli_ extensin needs the connection pointer, something like: mysqli_query($dbConn, $sql);
B) Also, modify your query to look like mysqli_query($dbConn, $sql) or die(mysqli_error($dbConn));. It will show you the sql errors, if any.
EDIT 1
If no errors appear after you put the mysqli_error(), then i think your script never gets to the sql part. Something stops it before that if.
Put on top of your script:
error_reporting(E_ALL);
ini_set('display_errors', '1');
and check if any php errors appear on the page.
Most of the time is a string/integer mismatch. Double check all your string escape characters. Copy your final query string and use some external tool to submit the query. You could start hardcoding all your data in the query and then proceed by adding one parameter at a time. Eventually you'll find the field (or fields) that causes the problem.
However, read carefully the error message first instead of guessing blindly what's causing the problem :-)
Make sure your fields count and values count are the same. Also correct this as well:
"'".implode("','", $fnames)."'"
in values passed.
I'm trying to create an app using the simple HTML DOM php script, but im running into a wall currently with it - hope you can help.
The aim is to read product numbers from mySQL database, concat these numbers with a url constant and then parse this resulting website for a specific class. The result should then be printed to the screen.
My problem is that the script is returning only the first result from the function array, i have tried a few things, such as trying to call $prices->children[4], but nothing seems to help.
When i trigger the function get_prices_array() with a url, it brings back multiple results -> but when i return this inside my while loop it only brings back the first result in the array.
Heres my code, hope you can point me in the right direction!
Thanks!
<?php
include('simple_html_dom.php');
function get_prices_array($url) {
$x = file_get_html($url);
foreach ($x->find('span.price')as $dom) {
$y = $dom->outertext;
return $y;
}
$x->clear();
}
$con = mysqli_connect("localhost", "***", "***", "***");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit();
}
$result = mysqli_query($con, "SELECT * FROM articles");
while ($row = mysqli_fetch_array($result)) {
$constant = '***';
$prices = get_prices_array($constant . $row["product_number"]);
echo $row["product_number"] . " - " . $prices . '<br />';
}
mysqli_close($con);
?>
// EDIT //
I changed the function get_prices_array() to loop through each span price class and add the result to an array, the array is then returned from the function. The first 5 results from the array are then stored to variables and added to the return string. Thanks for your help!
<?php
include('simple_html_dom.php');
function get_prices_array($url) {
$x = file_get_html($url);
$y = array();
foreach ($x->find('span.price')as $dom) {
$x = ($dom->outertext);
$y[] = $x;
}
return $y;
//$x->clear();
}
$con = mysqli_connect("localhost", "***", "***", "***");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit();
}
$result = mysqli_query($con, "SELECT * FROM articles");
while ($row = mysqli_fetch_array($result)) {
$constant = '***';
$prices = get_prices_array($constant . $row["product_number"]);
$pos1 = $prices[0];
$pos2 = $prices[1];
$pos3 = $prices[2];
$pos4 = $prices[3];
$pos5 = $prices[4];
echo $row["product_number"] . " - " . $pos1 . " - " . $pos2 . " - " . $pos3 . " - " . $pos4 . " - " . $pos5 .'<br />';
}
mysqli_close($con);
?>
I think problem is because of return used in foreach loop of function get_prices_array($url).
it is executing foreach loop only once. There is no meaning of loop if you are returning without condition inside loop.
I am trying to figure out what this ancient php sql code does by having it write to a text file instead of editing the sql database. This for loop is giving me major issues though. It just doesn't return anything! I think it has something to do with the curly bracket variable ${$currID}.
The $ids variable is an array of gages pulled from a website which works fine because I can echo $ids[$i]; and it returns the number of the gage.
Oh yeah, and the parts that are commented out are original parts of code that I've ommited to avoid editing the sql database. I thought it might be important to include them.
$file = fopen("test.txt","w");
$intizzler = count($ids);
for($i=0; $i<$intizzler; $i++){
//echo ($i+1) . " / " . $intizzler . ":";
$currID = $ids[$i];
${$currID} = new gage($currID);
//mysql_query("INSERT INTO gage
//(id,lng,lat,title,text,pic,datum,coords,county)VALUES(
echo fwrite($file,${$currID}->getField('id'));
echo fwrite($file,${$currID}->getField('long'));
echo fwrite($file,${$currID}->getField('lat'));
echo fwrite($file,${$currID}->getField('title'));
echo fwrite($file,${$currID}->getField('text'));
echo fwrite($file,${$currID}->getField('pic'));
echo fwrite($file,${$currID}->getField('datum'));
echo fwrite($file,${$currID}->getField('coords'));
echo fwrite($file,${$currID}->getField('county'));
//)") or die(mysql_error());
//echo "Write complete for $currID <br/>";
}
I'm completely stumped. Any help would be appreciated.
As stated in the comments when using variable variables the variable still has to resolve to a valid variable name. Try this instead:
<?php
$file = fopen("test.txt","w");
$intizzler = count($ids);
for($i=0; $i<$intizzler; $i++){
//echo ($i+1) . " / " . $intizzler . ":";
$currID = $ids[$i];
$gage = new gage($currID);
//mysql_query("INSERT INTO gage
//(id,lng,lat,title,text,pic,datum,coords,county)VALUES(
echo fwrite($file,$gage->getField('id'));
echo fwrite($file,$gage->getField('long'));
echo fwrite($file,$gage->getField('lat'));
echo fwrite($file,$gage->getField('title'));
echo fwrite($file,$gage->getField('text'));
echo fwrite($file,$gage->getField('pic'));
echo fwrite($file,$gage->getField('datum'));
echo fwrite($file,$gage->getField('coords'));
echo fwrite($file,$gage->getField('county'));
//)") or die(mysql_error());
//echo "Write complete for $currID <br/>";
}
I forgot to include a mysql_query! Now I'm able to access the code!
$result = mysql_query("select * from mytable");
It was so simple!
i am a beginner. but I'm practicing a lot for few days with php mysql, and I am trying to use for loop to search an exploded string, one by one from mysql server.
Till now I have no results.
I'm giving my codes,
<?php
// Example 1
$var = #$_GET['s'] ;
$limit=500;
echo " ";
echo "$var";
echo " ";
$trimmed_array = explode(" ", $var);
echo "$trimmed_array[0]"; // piece1
echo " ";
$count= count($trimmed_array);
echo $count;
for($j=0;$j<$count;$j++)
{
e cho "$trimmed_array[$j]";;
echo " ";
}
echo " ";
for($i=0; $i<$count ; $i++){
$query = "select * from book where name like \"%$trimmed_array[$i]%\" order by name";
$numresults=mysql_query($query);
$numrows =mysql_num_rows($numresults);
if ($numrows == 0)
{
echo "<h4>Results</h4>";
echo "<p>Sorry, your search: "" . $trimmed_array[i] . "" returned zero results</p>";
}
if (empty($s)) {
$s=0;
}
$query .= " limit $s,$limit";
$result = mysql_query($query) or die("Couldn't execute query");
echo "<p>You searched for: "" . $var . ""</p>";
echo "Results<br /><br />";
$count=1;
while ($row= mysql_fetch_array($result)) {
$name = $row["name"];
$publisher=$row["publisher"];
$total=$row["total"];
$issued=$row["issued"];
$available=$row["available"];
$category=$row["category"];
echo "<table border='1'><tr><td>$count)</td><td>$name </td><td>$publisher </td><td>$total </td><td>$issued </td><td>$available </td><td>$category </td></tr></table>" ;
$count++ ;
}
}
?>
In your case, you do for every record in your array ($trimmed_array) a new select. Thats not really good.
It would be better when you create just one select...
For example this:
// you need 1=1 for example when $i<count is false...
$baseQuery = "select * from book where 1=1";
$query = $baseQuery;
for($i=0; $i<$count ; $i++){
$query .= " OR name like ?";
}
// do your ordering:
$query.= " order by name";
But what does this "?" mean?
--> Do you know what sql-injection means? somebody could really easy put some information in this array wich could give any information about your database.. therefore you have to escape every userinput...
i like the mysqli package in php5. watch this example:
$query = "SELECT `id` FROM employees WHERE `name`=?";
// Setup parameter to be bound into query
$name = "Joey";
// Get instance of statement
$stmt = $mysqli->stmt_init();
// Prepare Query
if($stmt->prepare($query)){
// Bind Parameters [s for string]
$stmt->bind_param("s",$name);
// Execute statement
$stmt->execute();
// Bind result variables
$stmt->bind_result($employee_id);
// Fetch Value
$stmt->fetch();
// Echo results
echo "$name has an ID of $employee_id";
// Close Statement
$stmt->close();
}
Damn, your code really extremely crazy. Here you example about how to work with this:
<?php
$var = $_GET['s'];
$exp = explode(" ",$var);
$total = count($exp) - 1;
for($i = 0; $i <= $total; $i++) {
echo "Search for: " . $exp[$i] ."\n";
$sql = mysql_query("SELECT * FROM `book` WHERE `name` LIKE '%" . mysql_real_escape_string($exp[$i]) ."%'") or die(mysql_error());
if (mysql_fetch_num($sql) != 0) {
// Somthing found
}
}
?>
You have an error on line 25,
e cho "$trimmed_array[$j]";;
should be
echo "$trimmed_array[$j]";
Also, it seems that you are using $GET_[] variables, which are passed via the url string, which does not allow spaces. On line 15, you are splitting the array with explode(" ", $var);
I would also urge you, if you have not, look into sanitizing your database queries.
Heres my code
<?php
session_start();
include('config.php');
if(isset($_GET['search_word']))
{
// echo $_GET['search_word'] . '<br />'; // debugging
$search_word = $_GET['search_word'];
$search_word = mysql_escape_string($search_word);
$search_word_fix = str_replace(" ","%",$search_word);
$query = "SELECT * FROM article WHERE article_title LIKE '%" . $search_word . "%' AND article_live = '1' ORDER BY article_id DESC";
// echo $query . '<br />'; // debugging
$sql = mysql_query($query);
$count = mysql_num_rows($sql);
// echo $count . '<br />'; // debugging
// echo mysql_num_rows($sql) . '<br />'; // debugging
if($count > 0)
{
while($row=mysql_fetch_array($sql))
{
$msg=$row['article_title'];
$bold_word='<b>'.$search_word.'</b>';
$final_msg = str_ireplace($search_word, $bold_word, $msg);
echo $final_msg;
}
}
else
{
echo "No Results";
}
}?>
Can anyone see an issue with it? I cant pick out what is not working with this script and ive been staring at it for a while. It never makes it to the WHILE loop only the "No Results" and the count returns blank when i uncomment my debugging.
Count returning blank means your query failed for some reason.
Are you connecting to the db properly? Try using mysql_error() right after your query:
$error_msg = mysql_error();
Use mysql_real_escape_string() instead of mysql_escape_string() - it respects the character set so that you don't have UTF8 issues
If you're using this publicly, you may want to learn about using binds to eliminate the possibility of SQL injection via a library like PDO.
Here's a pretty good tutorial/introduction to PDO explaining why it's important!